PHP library to generate EML email files?

laurent picture laurent · Jan 8, 2012 · Viewed 12.8k times · Source

I'm trying to generate EML files from PHP. Is there any library that will allow me to easily create them? I could find some ActiveX component on the internet but would rather use something more portable.

Answer

laurent picture laurent · Jan 8, 2012

I ended up building the MIME message myself using this kind of template, where each field is replaced by a TEMPLATE_<name> variable:

From: TEMPLATE_FROM_ADDRESS
MIME-Version: 1.0
To: TEMPLATE_TO_ADDRESS
Subject: TEMPLATE_SUBJECT
Content-Type: multipart/mixed; boundary="080107000800000609090108"

This is a message with multiple parts in MIME format.
--080107000800000609090108
Content-Type: text/plain

TEMPLATE_BODY
--080107000800000609090108
Content-Type: application/octet-stream;name="TEMPLATE_ATTACH_FILENAME"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;filename="TEMPLATE_ATTACH_FILENAME"

TEMPLATE_ATTACH_CONTENT
--080107000800000609090108

Then creating the final message is quite simple using str_replace:

$content = file_get_contents("Template.eml");
$content = str_replace("TEMPLATE_FROM_ADDRESS", $fromEmail, $content);
$content = str_replace("TEMPLATE_TO_ADDRESS", $toEmail, $content);
// etc. for each template parameter
// Also don't forget to base64_encode the attachment content;
$content = str_replace("TEMPLATE_ATTACH_CONTENT", base64_encode($attachContent), $content);

Additional info about file attachment in this post: Attachment name and file extension not working in email *.eml

Edit (2018): Since this answer was written it seems it's been copied and pasted a bit everywhere, the template in particular. To avoid any conflict with other MIME data, you should make sure that the boundary "080107000800000609090108" is unique - it's a string of random characters no longer than 70 characters.