背景: 我正在开发一个 Laravel 应用程序,我需要使用自定义 Mailable 类发送带有附件的电子邮件 (
PdfEmail
)。该电子邮件应包含动态生成的 PDF 和服务报告模型中的其他附件。
代码: 我已经实现了
PdfEmail
类,其中包括设置电子邮件信封、内容和附件的方法。附件是从存储中获取的,其 MIME 类型是使用 ExtensionMimeTypeDetector
包中的 League\MimeTypeDetection
确定的。这是我的PdfEmail
课程的相关部分:
public function attachments(): array
{
// save pdf temporarily
// Define the directory where the PDF should be saved
$directory = storage_path('app/public/service-reports/' . $this->serviceReport->id);
// Check if the directory exists
if (!is_dir($directory)) {
// Create the directory, and make it recursive to create nested directories if necessary
mkdir($directory, 0755, true);
}
// Now save the PDF in the created directory
$pdfPath = $directory . '/service-report.pdf';
$this->pdf->save($pdfPath);
$attachments = [
Attachment::fromStorage(
path: 'service-reports/' . $this->serviceReport->id . '/service-report.pdf',
)->withMime('application/pdf'),
];
foreach ($this->serviceReport->attachments as $attachment) {
$attachments[] = Attachment::fromStorage(
path: $attachment->file,
)->withMime($this->getMimeType($attachment->file));
}
// check each attachment content type
foreach ($attachments as $attachment) {
\Log::info($attachment->mime);
}
return $attachments;
}
问题: 发送电子邮件时,我遇到了 Laravel 使用的 Symfony 组件中的
TypeError
。错误信息是:
TypeError: The body of "Symfony\Component\Mime\Part\TextPart" must be a string, a resource, or an instance of "Symfony\Component\Mime\Part\File" (got "null"). in /path/to/public_html/vendor/symfony/mime/Part/TextPart.php:52
发送电子邮件时会出现此错误。它似乎与处理附件或添加到电子邮件的方式有关。但是,当我将其部署到托管服务器时,代码在我的本地设置上完全正常工作,它只发生在那里
尝试解决:
问题:
TypeError
的原因可能是什么?Attachment::fromStorage()
方法或设置附件 MIME 类型的方式是否存在任何问题?任何见解或建议将不胜感激!
我面临着完全相同的问题。有人找到解决办法了吗