MK

How to attach or create an EML file with Symfony Mailer

25/07/2023

Using Symfony Mailer we can attach an EML file to our email.

use Symfony\Component\Mime\Email;
use Symfony\Component\Mime\Part\DataPart;

$email = (new Email())
    ->to('[email protected]')
    ->from('[email protected]')
    ->subject('Your email subject')
    ->text('Please see attached');

// Your raw email
$emlContents = '...';

$email->addPart(new DataPart(
    $emlContents,
    'file.eml',
    'message/rfc822',
    '8bit'
));

Importantly when attaching an EML file we need to adhere to the RFC so the content-type must be message/rfc822 and you will need to change the encoding to one of the valid options (see options), for this example I selected 8bit.

Creating an EML

You may also want to create a new email and convert it into an EML to attach, here we create a new email and utilise the ->toString() method to get the raw email.

use Symfony\Component\Mime\Email;
use Symfony\Component\Mime\Part\DataPart;

$email = (new Email())
    ->to('[email protected]')
    ->from('[email protected]')
    ->subject('Your email subject')
    ->text('Please see attached');

$eml = (new Email())
    ->to('[email protected]')
    ->from('[email protected]')
    ->subject('Your other email subject')
    ->text('Some body...');

$email->addPart(new DataPart(
    $eml->toString(),
    'file.eml',
    'message/rfc822',
    '8bit'
));

If we now toString our $email you’ll see the result

To: [email protected]
From: [email protected]
Subject: Your email subject
MIME-Version: 1.0
Date: Tue, 25 Jul 2023 12:23:56 +0000
Message-ID: 
Content-Type: multipart/mixed; boundary=l4MT1TQ9

--l4MT1TQ9
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: quoted-printable

Please see attached
--l4MT1TQ9
Content-Type: message/rfc822; name=file.eml
Content-Transfer-Encoding: 8bit
Content-Disposition: attachment; name=file.eml; filename=file.eml

To: [email protected]
From: [email protected]
Subject: Your other email subject
MIME-Version: 1.0
Date: Tue, 25 Jul 2023 12:23:56 +0000
Message-ID: 
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: quoted-printable

Some body...
--l4MT1TQ9

© Myles Kingsnorth