Update 2009/11/19: Some readers emailed me to mention that the script below doesn’t always work properly on all platforms (email messages are sometimes received with attachments but no content, or are sometimes completely blank). If the script below doesn’t work for you, Geekology has another post that details a method of sending emails with attachments in a PHP script that makes use of an external library.

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);
 
?>
Share this article: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Twitter
  • GatorPeeps
  • Digg
  • Reddit
  • muti.co.za
  • DZone
  • del.icio.us
  • StumbleUpon
  • Technorati
  • Ma.gnolia
  • Slashdot

Related posts:

  1. A simpler way to send Text or HTML emails with attachments in PHP
  2. Forcing a Return-Path header when sending email with PHP’s mail() function
  3. Testing SMTP servers from a UNIX command line
  4. Validating and sanitizing URLs, Emails, and other inputs with PHP’s filter_* functions
  5. Transfer your business emails to Google Apps with Google Email Uploader for Mac