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:
From: valid@email.addr\nX-Mailer: PHP 4.x\nMIME-Version: 1.0\nContent-Type: multipart/mixed; boundary=\"unique_separator\"\n--unique_separator\nContent-Type: text/html; charset=\"iso-8859-1\"\nContent-Disposition: inline\nContent-Transfer-Encoding: 7bit\n\nemail message body goes here \n\n--unique_separator\nContent-Type: application/octet-stream; name=\"attachment_file_name.ext\"\nContent-Transfer-Encoding: base64\nContent-Disposition: attachment; filename=\"attachment_file_name.ext\"\n\nbase64 encoded data goes here\n\n--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: