Sending emails with attachments using PHP’s mail() function

php mail function

If you need to send an email with attachments using just PHP’s mail() function, you can do so by using a multipart/mixed content header and converting the attachments to base64 strings.

First, generate a random hash to serve as a MIME Boundary:

$random_hash = md5(date(‘r’, time()));

Next, set some email headers:

$headers = “From: noreply@geekology.co.za\r\nReply-To: noreply@geekology.co.za”;
$headers .= “\r\nContent-Type: multipart/mixed; boundary=\”PHP-mixed-“.$random_hash.”\”“;

… then convert the attachment into a base64 string:

$attachment = chunk_split(base64_encode(file_get_contents(“geekology.zip”)));

Finally, define the content of the email similar to the example below, then send it using PHP’s mail() function:

<?php

$to = “willem@geekology.co.za”;

$subject = “A test email”;

$random_hash = md5(date(‘r’, time()));

$headers = “From: noreply@geekology.co.za\r\nReply-To: noreply@geekology.co.za”;

$headers .= “\r\nContent-Type: multipart/mixed; boundary=\”PHP-mixed-“.$random_hash.”\”“;

$attachment = chunk_split(base64_encode(file_get_contents(“geekology.zip”)));

$output = ”
–PHP-mixed-$random_hash;
Content-Type: multipart/alternative; boundary=’PHP-alt-$random_hash’
–PHP-alt-$random_hash
Content-Type: text/plain; charset=’iso-8859-1′
Content-Transfer-Encoding: 7bit

Hello World!
This is the simple text version of the email message.

–PHP-alt-$random_hash
Content-Type: text/html; charset=’iso-8859-1′
Content-Transfer-Encoding: 7bit

<h2>Hello World!</h2>
<p>This is the <b>HTML</b> version of the email message.</p>

–PHP-alt-$random_hash–

–PHP-mixed-$random_hash
Content-Type: application/zip; name=geekology.zip
Content-Transfer-Encoding: base64
Content-Disposition: attachment

$attachment
–PHP-mixed-$random_hash–“;

echo @mail($to, $subject, $output, $headers);

?>

Mike The Situation

Mike The Situation

Geek Master at Geekology
Master of programming and general geekness.
Mike The Situation
About Mike The Situation
Master of programming and general geekness.

No Comments, Be The First!

Your email address will not be published.