Skip to content

Instantly share code, notes, and snippets.

@m-manu
Last active May 23, 2016 09:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save m-manu/4722278 to your computer and use it in GitHub Desktop.
Save m-manu/4722278 to your computer and use it in GitHub Desktop.
PHP function to send e-mail with attachments
<?php
/*
Copyright (c) 2012, Manu Manjunath
All rights reserved.
Redistribution and use of this program in source/binary forms, with or without modification are permitted.
Link to this gist is preferred, but not a condition for redistribution/use.
*/
function mail_with_attachments($to, $subject, $message, Array $filepaths, $from = null, $replyto = null) {
$uid = md5(uniqid(time()));
$from = str_replace(array("\r", "\n"), '', $from);
$headers = (empty($from) ? "" : "From: $from\r\n")
. (empty($replyto) ? "" : "Reply-To: $replyto\r\n")
. "MIME-Version: 1.0\r\n"
. "Content-Type: multipart/mixed; boundary=\"$uid\"\r\n\r\n"
. "This is a multi-part message in MIME format.\r\n"
. "--$uid\r\n"
. "Content-type: text/plain; charset=iso-8859-1\r\n"
. "Content-Transfer-Encoding: 7bit\r\n\r\n"
. "$message\r\n\r\n";
foreach ($filepaths as $filepath) {
if(!file_exists($filepath))
continue;
$filename = basename($filepath);
$file_contents = file_get_contents($filepath);
$file_contents_base64 = base64_encode($file_contents);
$content = chunk_split($file_contents_base64);
$headers .= "--$uid\r\n"
. "Content-Type: application/octet-stream; name=\"$filename\"\r\n"
. "Content-Transfer-Encoding: base64\r\n"
. "Content-Disposition: attachment; filename=\"$filename\"\r\n\r\n"
. "$content\r\n\r\n";
}
$headers .= "--$uid--";
return mail($to, $subject, "", $headers);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment