如何创建swiftmailer消息并将其附加到另一条消息

We are using SwiftMailer in one of our functions who sends emails out. At the end, there is a general report sent to the department manager in order to keep trace and be informed about the function usage.

The manager is now willing to also receive a copy of the email sent out, we could do this by adding one email copy as attachment to the email report.

Any idea on how can we create a swiftmailer message and not sending it, only using it as attachment for a new swiftmailer email.

You could add your Swift_Message as an attachment like this:

$attachment = new \Swift_Attachment($messageAttachment, 'some-email.txt', 'text/plain');

However, your email would be now attached as an .txt file which contains all mail details. I'm not sure if this is the expected behaviour!?

Full example:

$messageAttachment = (new \Swift_Message('Attached Email'))
    ->setFrom('yourmail@gmail.com')->setTo('yourmail@gmail.com')
    ->setBody("Attached Email Body", 'text/plain');
$attachment = new \Swift_Attachment($messageAttachment, 'some-email.txt', 'text/plain');

$message = (new \Swift_Message('Real Email'))
    ->setFrom('yourmail@gmail.com')->setTo('yourmail@gmail.com')
    ->setBody("Real Email Body", 'text/plain')
    ->attach($attachment);
$mailer->send($message);

The content of the attached some-email.txt will look like this:

Message-ID: <568d128d97e530d1389cb83b154d64eb@swift.generated>
Date: Tue, 05 Dec 2017 17:00:05 +0100
Subject: Attached Email
From: yourmail@gmail.com
To: yourmail@gmail.com
MIME-Version: 1.0
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: quoted-printable

Attached Email Body