Skip to content

Instantly share code, notes, and snippets.

@hdogan
Last active September 9, 2024 09:58
Show Gist options
  • Save hdogan/8649cd9c25c75d0ab27e140d5eef5ce2 to your computer and use it in GitHub Desktop.
Save hdogan/8649cd9c25c75d0ab27e140d5eef5ce2 to your computer and use it in GitHub Desktop.
Sending SMTP e-mail with curl/php
<?php
function read_cb($ch, $fp, $length) {
return fread($fp, $length);
}
$fp = fopen('php://memory', 'r+');
$string = "From: <[email protected]>\r\n";
$string .= "To: <[email protected]>\r\n";
$string .= "Date: " . date('r') . "\r\n";
$string .= "Subject: Test\r\n";
$string .= "\r\n";
$string .= "Deneme mesaji\r\n";
$string .= "\r\n";
fwrite($fp, $string);
rewind($fp);
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => 'smtps://smtp.example.com:465/example.com',
CURLOPT_MAIL_FROM => '<[email protected]>',
CURLOPT_MAIL_RCPT => ['<[email protected]>'],
CURLOPT_USERNAME => 'username',
CURLOPT_PASSWORD => 'password',
CURLOPT_USE_SSL => CURLUSESSL_ALL,
CURLOPT_READFUNCTION => 'read_cb',
CURLOPT_INFILE => $fp,
CURLOPT_UPLOAD => true,
CURLOPT_VERBOSE => true,
]);
$x = curl_exec($ch);
if ($x === false) {
echo curl_errno($ch) . ' = ' . curl_strerror(curl_errno($ch)) . PHP_EOL;
}
curl_close($ch);
fclose($fp);
@hdogan
Copy link
Author

hdogan commented Mar 16, 2024

Hello, it was written when PHP version 8 was not exist. Some parts may need to be updated.

For the SSL problem, it may be related to SSL/TLS version. (CURLOPT_SSLVERSION option).

Have you tried with using "smtp://" instead of "smtps://" schema? (start with plain text connection and upgrade to TLS - with CURLOPT_USE_SSL set to CURLUSESSL_ALL)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment