Skip to content

Instantly share code, notes, and snippets.

@hdogan
Last active March 16, 2024 07:49
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • 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: <no-reply@example.com>\r\n";
$string .= "To: <hdogan@example.com>\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 => '<no-reply@example.com>',
CURLOPT_MAIL_RCPT => ['<hdogan@example.com>'],
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);
@FALL1N1
Copy link

FALL1N1 commented Nov 18, 2021

Works like a charm, thank you!

@Anlimah
Copy link

Anlimah commented May 11, 2022

@hdogan, can you assist me on how to use this code? Do I need to call read_cb()?

@hdogan
Copy link
Author

hdogan commented May 11, 2022

@hdogan, can you assist me on how to use this code? Do I need to call read_cb()?

Yes you're. You can also pass closure to that option instead of function name as string and if you don't like to define a seperate function, like:

CURLOPT_READFUNCTION => function ($ch, $fp, $length) {
    return fread($fp, $length);
},

@luigifab
Copy link

luigifab commented Jul 12, 2022

Check your email sent, If you didn't found a Message-ID in headers, I encourage you to add a Message-ID to avoid: 550, 5.7.1 delivery not authorized: message missing a valid messageId header are not accepted (gmail) (this error does not occur all the time).

@mula-jeff
Copy link

Excellent example @hdogan ! Very helpful! Do you happen to have a pointer to code that also includes an attachment?

@hdogan
Copy link
Author

hdogan commented Aug 5, 2022

You need to create a multipart/mixed mail body string which includes appropriate/required headers and content (including base64 encoded attached file content) then push it into file pointer created by $fp = fopen('php://memory', 'r+'); line.

Quick example (taken from https://stackoverflow.com/questions/12301358/send-attachments-with-php-mail)

$content = file_get_contents($your_file_to_be_attached);
$chunked_content = chunk_split(base64_encode($content));
$uid = md5(uniqid(time()));
$file_name = basename($your_file_to_be_attached);
$message_id = time()  . '-' . $uid . '@yourdomain.com';

$string = "From: <no-reply@example.com>\r\n";
$string .= "To: <hdogan@example.com>\r\n";
$string .= "Date: " . date('r') . "\r\n";
$string .= "Subject: Test\r\n";
$string .= "Message-ID: $message_id\r\n" .
$string .= "MIME-Version: 1.0\r\n";
$string .= "Content-Type: multipart/mixed; boundary=\"$uid\"\r\n";
$string .= "\r\n";
$string = "--$uid\r\n";
$string .= "Content-Type: text/plain; charset=utf-8\r\n";
$string .= "Content-Transfer-Encoding: 7bit\r\n";
$string .= "\r\n";
$string .= "Hello there!\r\n";
$string .= "\r\n";
$string .= "--$uid\r\n";
$string .= "Content-Type: application/octet-stream; name=\"$filename\"\r\n";
$string .= "Content-Transfer-Encoding: base64\r\n";
$string .= "Content-Disposition: attachment; filename=\""$file_name\"\r\n";
$string .= "\r\n";
$string .= $chunked_content . "\r\n";
$string .= "\r\n";
$string .= "--$uid--\r\n";
# We might need extra CRLF here.
# $string .= "\r\n"; 

I haven't test it, so it may not work. There might be a PHP package which helps you to create proper headers and body string easily.

@mula-jeff
Copy link

@hdogan - sorry for the late response - thank you very much for taking the time to respond and provide such a detailed example here - much appreciated! I will try this over the weekend and see what happens. So much to consider with all the RFC-xxxx conventions and rules -- no wonder people just adopt 3rd party libraries to do this. My issue around using external libs is that our app is unfortunately locked to a very old PHP version and working with package dependencies is equally challenging. I like the simplicity of CURL (even for its bare-bones SMTP support), but maybe beyond its capabilities for what we're trying to do...

@philprl
Copy link

philprl commented Mar 11, 2024

I am sorry, but the example using curl/php given at first don't work for me:
First, I had to replace fopen('php://memory', 'r+') by fopen('php://temp', 'r+') otherwise I get "Warning: curl_setopt_array(): Cannot represent a stream of type MEMORY as a STDIO FILE* in ...",
and second, I get the error "35 = SSL connect error".
It is not a php/curl version problem, because it is recent (8.4.0) and my web server is written in PHP 8.3 on apache 2.4 under Windows 10 on my local PC machine.
It is not a configuration problem, because when I send the mail with an application written in C langage using libcurl's curl_easy_*() fonctions with the same options, with the same SMTP server (port 467 or 587) , on the same Windows 10 PC machine that works....
At this time, I have not solved the problem, any idea ?

@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