PHP Mailer with Email Attachments that supports Mac OS X's Mail

PHP-mail-script-compatible-with-osx-apple-mailWe needed a server-side script recently to send emails with attachments from an iPhone App. We’ve chosen PHP because we wanted to keep it as simple as possible (we wanted no dependencies).

The emails sent (and attachments) looked good in a few email systems, until we checked with Mac Mail. Check the image at the left to see how it was displayed. Read on to learn how to solve this issue and see the full code for the script!

The attachment was an .ics file (a calendar file) and it was not displayed correctly because we used a wrong content-type (application/zip instead of text/plain).

You have below the complete mail_with_attachment function that we created (you can use it as a template for you own emails):

function mail_with_attachment($mailto, $subject, $message, $attachmment_content, $filename) {
  $content  = chunk_split(base64_encode($attachmment_content));

  $header = "MIME-Version: 1.0
From: Name
Content-Type: multipart/mixed; boundary=0016e6d78553954dae047ca714d4

Content-Type: multipart/alternative; boundary=0016e6d78553954da9047ca714d2

Content-Type: text/plain; charset=ISO-8859-1


Content-Type: text/html; charset=ISO-8859-1


Content-Type: text/plain; charset=US-ASCII; name="{$filename}"
Content-Disposition: attachment; filename="{$filename}"
Content-Transfer-Encoding: base64



  if (mail($mailto, $subject, "", $header)) {
    echo "OK";
  } else {
    echo "ERROR";

Don’t forget to change the Content-Type for the attachment to your corresponding type (on line 23).