this.lau_ this.lau_ - 1 year ago 77
PHP Question

PHP library to generate EML email files?

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 Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download