Productive, Not Busy - Work smarter and get more done.

How to send emails with attachments using PHP's "mail()" function

29 Jun 2009

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 in a similar manner to the example below, then send it using PHP’s "mail()" function:

<?php

  $to = "someone@somewhere.com";

  $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);

?>
Do you like this? Share it:

Copyright © Geekology 2012. All Rights Reserved.