Created
November 11, 2015 11:42
-
-
Save jelmervdl/e9b63f280e3ee5524b62 to your computer and use it in GitHub Desktop.
PHP streaming email
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function send_mail_with_attachment($to, $subject, $message, $additional_headers, $file_handle, $file_name) | |
{ | |
if (!$file_handle) | |
throw new InvalidArgumentException("The provided file handle is not working"); | |
$fout = popen('sendmail ' . escapeshellarg($to), 'w'); | |
if (!$fout) | |
throw new Exception("Could not open sendmail"); | |
$boundary = md5(microtime()); | |
// Headers and dummy message | |
fwrite($fout, | |
"MIME-Version: 1.0\r\n" | |
. ($additional_headers ? (trim($additional_headers, "\r\n") . "\r\n") : "") | |
. "Subject: $subject\r\n" | |
. "Content-Type: multipart/mixed; boundary=\"$boundary\"\r\n" | |
. "\r\n" | |
. "This is a mime-encoded message" | |
. "\r\n\r\n"); | |
// Message content | |
fwrite($fout, "--$boundary\r\n" | |
. "Content-Type: text/plain; charset=\"UTF-8\"\r\n" | |
. "Content-Transfer-Encoding: quoted-printable\r\n\r\n"); | |
$filter = stream_filter_append($fout, 'convert.quoted-printable-encode'); | |
if (is_resource($message)) | |
stream_copy_to_stream($message, $fout); | |
else | |
fwrite($fout, $message); | |
stream_filter_remove($filter); | |
fwrite($fout, "\r\n\r\n"); | |
// Attachment | |
fwrite($fout, "--$boundary\r\n" | |
. "Content-Type: application/octet-stream; name=\"" . addslashes($file_name) . "\"\r\n" | |
. "Content-Transfer-Encoding: base64\r\n" | |
. "Content-Disposition: attachment\r\n\r\n"); | |
$filter = stream_filter_append($fout, 'convert.base64-encode', STREAM_FILTER_WRITE, [ | |
"line-length" => 80, | |
"line-break-chars" => "\r\n"]); | |
stream_copy_to_stream($file_handle, $fout); | |
stream_filter_remove($filter); | |
fwrite($fout, "\r\n\r\n" | |
. "--$boundary--\r\n"); | |
fclose($fout); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment