PHP library to generate EML email files?

2019-03-27 23:47发布

问题:

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.

回答1:

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.



回答2:

I think you don't need a library. It's just plain text (e.g. http://bitdaddys.com/example1.eml)

Date: Sat, 12 Aug 2006 14:25:25 -0400
From: John Doe <jdoes@someserver.com>
Subject: BitDaddys Software
To: sales@bitdaddys.com

Dear BitDaddys Corp.,

We have added your software to our approved list.

Thank you for your efforts.

Sincerely,
John Doe
Some Server Company

You can just output text with headers and save it using fwrite. For attachments use base64_encode() as stated here



回答3:

Use imap_savebody (part of the imap library http://us1.php.net/manual/en/function.imap-savebody.php) with a null $part_number. It creates a beautiful .eml file with one line of code with the entire message (null $part_number = all parts... not documented but works).

the other two solutions depend on the format of the email (only one attachment and no html section in the first solution, and only text email in the second).

imap_savebody creates a perfect .eml file no matter what the format of the incoming email is (as long as it's RFC-complaint of course).



标签: php email eml