Text emails are quick and easy, but how do you put a proper multipart email together in PHP? This script shows how to create an email with text, html and attachments.
Two boundary strings are needed: one to separate the message from the attachments, and one to separate the text and the html in the message body.
<?php
$subject = "Test email with attachment";
$random_hash = md5(date("jS M Y", time()));
$boundsep = "boundary-alt-".$random_hash;
$boundary = "--".$boundsep;
$attboundsep = "boundary-mixed-".$random_hash;
$attachmentboundary = "--".$attboundsep;
$headers = "From: Live Server\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"".$attboundsep."\"";
$attachment = chunk_split(base64_encode(file_get_contents('test.pdf')));
$message = $attachmentboundary."\n"
."Content-Type: multipart/alternative; boundary=\"".$boundsep."\"\n"
.$boundary."\n"
."Content-Type: text/plain; charset=\"iso-8859-1\"\n"
."Content-Transfer-Encoding: 7bit\n"
."Text Section\nThis is the text section of the message.\n"
.$boundary."\n"
."Content-Type: text/html; charset=\"iso-8859-1\"\n"
."Content-Transfer-Encoding: 7bit\n"
."<h2>HTML Section</h2>"
."<p>This is the <b>HTML section</b> of the message.</p>\n"
.$boundary."--\n"
.$attachmentboundary."\n"
."Content-Type: application/zip; name=\"Important_Newsletter.pdf\"\n"
."Content-Transfer-Encoding: base64\n"
."Content-Disposition: attachment\n"
.$attachment."\n"
.$attachmentboundary."--\n";
@mail("mail@mail.com", "Email with Attachments", $message, $headers);
?>
>> Posted in Websites at 15:06, and viewed 11,368 times
Next article: Email Address Format Function (24 November 2009)
Next Websites article: PHP Email Read Receipt (24 November 2009)
Add your comments