Skip to content

Instantly share code, notes, and snippets.

@phpdave
Created September 9, 2016 16:51
Show Gist options
  • Save phpdave/fdb885707e75b0709aea38aa2caf2186 to your computer and use it in GitHub Desktop.
Save phpdave/fdb885707e75b0709aea38aa2caf2186 to your computer and use it in GitHub Desktop.
<?
$email = '[email protected]';
$subject = "Here's a PDF";
$headers = "From: PDF Master <[email protected]>\r\nReply-To: [email protected]";
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"".$boundary."\"";
//build message with attachments
//message
$body = "Here's your PDFs!";
//attachments (3 pdfs)
$random_hash = md5(uniqid(time()));
$boundary = "PHP-mixed-".$random_hash;
$boundaryAlt = "PHP-alt-".$random_hash;
$attachments = array('/path/to/pdf/My1.pdf',
'/path/to/pdf/My2.pdf',
'/path/to/pdf/My3.pdf');
$displayFilenames = array("My1.pdf",
"My2.pdf",
"My3.pdf");
$attachmentSection="";
for($x=0;$x<count($attachments);$x++){
$file = fopen($attachments[$x],"rb");
$data = fread($file,filesize($attachments[$x]));
fclose($file);
$data = chunk_split(base64_encode($data));
$attachmentSection .= "--$boundary\n";
$attachmentSection .= "Content-Type: \"application/octet-stream\";\n" . " name=\"$displayFilenames[$x]\"\n" .
"Content-Disposition: attachment\n".
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
}
ob_start(); //Turn on output buffering
?>
--<?= $boundary; ?>
Content-Type: multipart/alternative; boundary="<?= $boundaryAlt; ?>"
--<?= $boundaryAlt; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
<?= $body; ?>
--<?= $boundaryAlt; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
<?= $body; ?>
--<?= $boundaryAlt; ?>--
<?= $attachmentSection; ?>
--<?= $boundary; ?>--
<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false)
{
//valid email address
$result = mail($email, $subject, $message, $headers);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment