Monday 15 June 2009

Creating Multipart Emails in PHPCreating Multipart Emails in PHP

Left QuoteText 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);

?>


This will attach the file test.pdf to the email and call it Important_Newsletter.pdf.Right Quote

Next article: Email Address Format Function (24 November 2009)

Next Websites article: PHP Email Read Receipt (24 November 2009)

CommentsComments

Add your comments

Name

Comments

Question

3 * 7 = (this security question stops automated submissions)