php – 使用SWIFTMAIL发送base64电子邮件

我只是想用base64编写我的多部分电子邮件并通过
swiftmail发送.这是我到目前为止的代码:

$message = Swift_Message::newInstance("Email Template Test")
    ->setBoundary($boundary)
    ->setFrom(array('no-reply@domain.net' => 'Mailer Service'))
    ->setTo(array("a@d.com","a@b.com"))
    ->setBody($plaintext)
    ->addPart($htmlmail,"text/html");

$headers = $message->getHeaders();
$headers->addTextHeader('Content-Transfer-Encoding','base64');

$contenttype = $message->getHeaders()->get('Content-Type');
$contenttype->setValue('multipart/alternative');

据我所见,文档(我不太清楚),Content-Transfer-Encoding标题是一个文本标题,所以我应该能够像上面那样设置它.在此之前,我运行了所有当前标头的输出,并且没有列出Content-Transfer-Encoding,因此需要进行设置.因此,为什么在上面的代码中我试图设置它.

输出很好,我收到电子邮件,它们工作,但当我查看源他们没有编码.我尝试使用相同的上述代码,但将$plaintext更改为base64_encode($plaintext),但刚收到编码消息.怎么做>

最佳答案 在版本5.4中,您可以设置编码器.否则,Swift_Message将使用本机编码器对消息进行编码.

$message = \Swift_Message::newInstance("Email Template Test");
$message->setEncoder(\Swift_Encoding::getBase64Encoding());
//...

此外,还有一个带有编码和addPart的bug (as of version 4 and 5). MimePart不会从origin消息继承编码.
为此,您需要手动创建MimePart并将其附加到原始消息.

$part = \Swift_MimePart::newInstance();
$part->setEncoder($message->getEncoder());
$part->setBody($htmlmail, 'text/html');
$message->attach($part);

这将自动添加Content-Type:multipart / alternative; boundary = ****,boundary charset和Content-Transfer-Encoding:base64头信息.

结果:

var_dump($message->toString());

string 'Message-ID: <2f48c04910b97f730834e92f268d3410@example.com>
Date: Thu, 14 Jan 2016 20:45:30 +0000
Subject: Email Template Test
From: Mailer Service <no-reply@domain.net>
To: a@d.com, a@b.com
MIME-Version: 1.0
Content-Type: multipart/alternative;
 boundary="_=_swift_v4_1452804330_b0a47ad936ba98d2f513294958a235d0_=_"


--_=_swift_v4_1452804330_b0a47ad936ba98d2f513294958a235d0_=_
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: base64

VGhpcyBpcyBhbiBodG1sIG1lc3NhZ2U=

--_=_swift_v4_1452804330_b0a47ad936ba98d2f513294958a235d0_=_
Content-Type: text/html; charset=utf-8
Content-Transfer-Encoding: base64

VGhpcyBpcyBhIHRleHQgbWVzc2FnZQ==

--_=_swift_v4_1452804330_b0a47ad936ba98d2f513294958a235d0_=_--
' (length=751)
点赞