14 Apr 2011

Send HTML email with an attachment from PHP

It took me a painfully long time to find a PHP script that could send multi-part email (with plain text / fancy HTML body content) and an attachment that actually worked! But I have adapted this excellent script to suit my needs (excluding output buffering). So reposting it mostly for my own reference... hopefully it can help some other poor sods out too.


<?php

$htmlbody = "This is an <b>html</b> message";
$textmessage = "This is a plain text message";

//Set Recipient Address
$to = "recipient@domain.com";

//Set Email Subject
$subject = "HTML email with attachment";

//define the from \ reply to headers
$headers = "From: yourname@domain.com\r\nReply-To: yourname@domain.com";

//create a unique boundary string to delimit different parts of the email (plain text, html, file attachment)
$random_hash = md5(date('r', time()));

//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";

//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks for sending
$attachment = chunk_split(base64_encode(file_get_contents('attachment.zip')));

//define the body of the message.
$message = "--PHP-mixed-$random_hash\r\n"
."Content-Type: multipart/alternative; boundary=\"PHP-alt-$random_hash\"\r\n\r\n";
$message .= "--PHP-alt-$random_hash\r\n"
."Content-Type: text/plain; charset=\"iso-8859-1\"\r\n"
."Content-Transfer-Encoding: 7bit\r\n\r\n";

//Insert the plain text message.
$message .= strip_tags($textmessage);
$message .= "\r\n\r\n--PHP-alt-$random_hash\r\n"
."Content-Type: text/html; charset=\"iso-8859-1\r\n"
."Content-Transfer-Encoding: 7bit\r\n\r\n";

//Insert the html message.
$message .= $htmlbody;
$message .="\r\n\r\n--PHP-alt-$random_hash--\r\n\r\n";

//include attachment
$message .= "--PHP-mixed-$random_hash\r\n"
."Content-Type: application/zip; name=\"attachment.zip\"\r\n"
."Content-Transfer-Encoding: base64\r\n"
."Content-Disposition: attachment\r\n\r\n";
$message .= $attachment;
$message .= "/r/n--PHP-mixed-$random_hash--";

//send the email
$mail = mail( $to, $subject , $message, $headers );

if ($mail) {
echo "Mail sent!";
} else "Mail not sent!";

?>

3 comments:

Anonymous said...

How would you do multiple attachments?

Rich said...

Give this a try? http://www.emanueleferonato.com/2008/07/22/sending-email-with-multiple-attachments-with-php/

Rich said...

I've recently revisited a similar project and I would highly recommend using the PHP PEAR mail library over the example I posted above, there is a great tutorial here: http://www.tuxradar.com/practicalphp/15/5/2