监听 mailer.sending 事件时消息 getBody 为空

Message getBody null when listening on mailer.sending event

我正在尝试捕获通过 Laravel 的邮件 class 发送的电子邮件的 body。监听事件 mailer.sending 允许我得到一个 Swift_Message object,然而,当我调用 getBody() 它时 returns null.

不过,我可以使用 __toString() 魔术方法打印出整封电子邮件(使用 headers)。有人知道是否有办法获取电子邮件的 body?

使用修补程序($消息从事件触发中检索):

>>> $message
=> <Swift_Message #000000004598a18f0000000059c6cf6b> {}
>>> $message->getBody(); 
=> null
>>> echo (string) $message;
Message-ID: <135138ac89676fd3487ff75b10989803@swift.generated>
Date: Fri, 07 Oct 2016 22:41:02 +0000
Subject: ...
From: ...
To: ...
MIME-Version: 1.0
Content-Type: multipart/alternative;
 boundary="_=_swift_v4_1475880062_895bd5de56ade4842a3c198ee264ced0_=_"


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

Email body here

--_=_swift_v4_1475880062_895bd5de56ade4842a3c198ee264ced0_=_--

深入研究 Laravel 代码,他们使用 Mime 部分而不是纯文本电子邮件的正文。 (可能是Swiftmailer设计的问题,我对这个库还不够了解)。

我的快速解决方案是:

        $htmlBody = $message->getBody();
        $textBody = '';
        $children = $message->getChildren();
        if (isset($children[0]) && $children[0] instanceof \Swift_MimePart) {
            $textBody = $children[0]->getBody();
        }
        $body = ($htmlBody) ? $htmlBody : $textBody;

但是,可能需要进行额外检查以确保第一个子项是纯文本电子邮件。希望这对遇到问题的其他人有所帮助。