【问题标题】:Queuing mail with attachData in Laravel 5.1 / OctoberCMS在 Laravel 5.1 / OctoberCMS 中使用 attachData 排队邮件
【发布时间】:2018-01-11 14:44:03
【问题描述】:

当我使用 Mail::send

时,以下 IS 工作
$email = 'my@email.com';
$name = 'My Name';
$invoice = InvoicePdf::generate($invoice_id); // generates PDF as raw data

Mail::send('mail.template', null, function($message) use ($name, $email, $invoice) {

    $message->to($email, $name);
    $message->subject('Thank you for your order!');
    $message->attachData($invoicePdf, 'invoice.pdf', ['mime' => 'application/pdf']);

});

它工作正常,并生成了一封带有正确 PDF 附件的电子邮件。

但是,如果我将 Mail::send 更改为 Mail::queue,则会收到以下错误:

Unable to JSON encode payload. Error code: 5

/var/www/html/october/vendor/laravel/framework/src/Illuminate/Queue/Queue.php line 90

如果我取出 $message->attachData(); 行,那么它甚至可以与 Mail::queue 一起使用,因此附件中的原始数据似乎导致队列出现问题,但相关的 OctoberLaravel 文档中没有任何内容关于如何处理这个问题。

【问题讨论】:

    标签: laravel laravel-5.1 octobercms


    【解决方案1】:

    可能是因为$invoicePdf数据是PDF file的原始数据,而php在保存到数据库时无法处理该数据(attachData)。

    嗯,您也可以生成文件,然后将file path 附加到邮件中,然后添加到队列中。

    // generate tempfile name
    $temp_file = tempnam(sys_get_temp_dir(), 'inv');
    
    // this pdf is generated by renatio plugin but you can 
    // use your data and save it to disk
    PDF::loadTemplate('renatio::invoice')
        ->save($temp_file);
    
    Mail::queue('mail.template', null, function($message) use ($name, $email, $temp_file) {
        $message->to($email, $name);
        $message->subject('Thank you for your order!');
        $message->attach($temp_file, ['as' => 'Your_Invoice.pdf', 'mime' => 'application/pdf']);
    });
    

    它应该可以工作。

    @Joseph 指出在 Laravel 5.5 中有 mailable 可以使用。 @Joseph 指出了这个解决方案,它似乎有效,所以如果你的laravel 版本是>= 5.5,你也可以使用这个解决方案 https://laracasts.com/discuss/channels/laravel/sending-email-with-a-pdf-attachment

    谢谢@约瑟夫

    【讨论】:

    • 是的,保存它然后引用保存的文件是可行的,但这是我想避免的额外步骤。我希望有一种方法可以对原始数据进行编码,以便将其添加到队列中。如果没有人能找到解决方案,那么我会将您的答案标记为正确,但希望还有另一种方法。
    • 如果我找到更好的正确方法,我也会尝试解决这个问题并更新答案。
    • 我找到了更好的方法!我只记得当前版本的 OctoberCMS 实际上使用的是 Laravel 5.5 而不是 5.1,所以我可以使用新的“可邮寄”功能 (laravel.com/docs/5.4/mail#writing-mailables) 并按照 laracasts.com/discuss/channels/laravel/… 的 deselbi 的示例进行操作——我会弄清楚最好的方法,然后在 SO 上发布一个问答,并在此处的 cmets 中发布指向它的链接。我已将您的答案标记为正确,因为我认为这可能是 Laravel 5.1 中最好的方法!
    • 很酷,谢谢在答案中添加了您的链接,这样它也可以帮助其他人:)
    猜你喜欢
    • 1970-01-01
    • 2019-08-22
    • 2015-11-27
    • 2023-03-30
    • 1970-01-01
    • 2017-01-25
    • 2015-10-03
    • 1970-01-01
    • 2019-07-26
    相关资源
    最近更新 更多