laravel - 检索已发送电子邮件的附件名称和内容
问题描述
在 Laravel 中,我正在寻找一种方法来检索已发送的电子邮件的附件(如果有),然后将该附件存储在文件系统中。
我为该Illuminate\Mail\Events\MessageSent
事件创建了一个新的侦听器,目前正在获取附件名称,但我不知道如何获取附件的内容以供以后存储:
public function handle($event)
{
$subject = $event->message->getSubject();
$body = $event->message->getBody();
$recipient = array_keys($event->message->getTo())[0];
$attachments = [];
foreach ($event->message->getChildren() as $child) {
$attachments[] = [
'name' => str_replace('attachment; filename=', null, $child->getHeaders()->get('content-transfer-encoding')->getFieldBody()),
'contents' => '' // ?
];
}
}
有人知道怎么做这个吗?
谢谢。
解决方案
您应该通过 Swift_Attachment::class 过滤消息子项,您可以使用 getBody() 获取附件内容。由于swiftmailer 问题,您可能需要调用 getBody() 两次。文件名、内容类型和正文可以从 swift 附件对象中轻松访问。
foreach (collect($event->message->getChildren())->whereInstanceOf(Swift_Attachment::class) as $attachment) {
$attachment->getBody(); // issue workaround
$attachments[] = [
'name' => $attachment->getFilename(),
'contentType' => $attachment->getContentType(),
'contents' => $attachment->getBody(),
];
}