Creating emails with attachments in PHP

Yesterday I was trying to create form that would upload a file to the server. PHP script would then accept it and send it as an attachment to an email address. In order to attach a file I had to add multipart/mixed type headers. Upload worked just fine, but making multipart email to work was a bit of a trouble. Email would be successfuly sent and received but no content or attachment would appear in an email client (I use Opera’s inbuilt client). I looked at headers and everything was there: message, base64 encoded data but still nothing was showing in the email body.

After a few hours I managed to figure out that mail headers should have a rather strict syntax, one surplus line break and your are done.

Below are the correctly set headers:

  1. From: valid@email.addr\n
  2. X-Mailer: PHP 4.x\n
  3. MIME-Version: 1.0\n
  4. Content-Type: multipart/mixed; boundary=\"unique_separator\"\n
  5. --unique_separator\n
  6. Content-Type: text/html; charset=\"iso-8859-1\"\n
  7. Content-Disposition: inline\n
  8. Content-Transfer-Encoding: 7bit\n\n
  9. email message body goes here \n\n
  10. --unique_separator\n
  11. Content-Type: application/octet-stream; name=\"attachment_file_name.ext\"\n
  12. Content-Transfer-Encoding: base64\n
  13. Content-Disposition: attachment; filename=\"attachment_file_name.ext\"\n\n
  14. base64 encoded data goes here\n\n
  15. --unique_separator--

NOTE: the number of new lines (\n) is important.

NOTE: here is now data was encoded:
$data = chunk_split(base64_encode($data));

Useful Resources:

Leave a comment

Please be polite and on topic. Your e-mail will never be published.