3

我想通过 laravel 发送邮件。出于某种原因,我只想cc在调用send方法之前设置:

Mail::cc($cc_mail)->send(new MyMailAlert());

to然后我直接在build我的 Mailable 类的方法中定义收件人( ):

$this->subject($subject)->to($to_email)->view('my-mail');

但它失败了:

Symfony\Component\Debug\Exception\FatalThrowableError: 调用未定义的方法 Illuminate\Mail\Mailer::cc()

在发送邮件之前如何在不知道收件人的情况下发送邮件build?换句话说,我想直接在build方法中设置收件人(to),我不知道该怎么做。

4

2 回答 2

2

这是解决此问题的技巧:

Mail::to([])->cc($cc_mail)->send(new MyMailAlert());

所以只需添加一个to()带有空数组的方法就可以了。它仍然是一个 hack,我不确定它是否会在未来起作用。

于 2017-04-24T09:13:59.073 回答
2

cc记录在Laravel DocsIlluminate\Mail\Mailer中,但我在源代码中找不到方法或属性,在Laravel API 文档中也找不到。所以你不能这样使用它。

Illuminate\Mail\Mailable有财产cc。所以,如果你想cc在发送前添加并to在构建方法上添加,你需要这样的东西:

MyMailAlert.php

class MyMailAlert extends Mailable implements ShouldQueue
{
    use Queueable, SerializesModels;

    /**
     * Create a new message instance.
     */
    public function __construct()
    {
        //
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->subject($this->subject)->to($this->to)->view('my-mail');
    }
}

在您的控制器中:

$myMailAlert = new MyMailAlert();
$myMailAlert->cc = $cc_mail;

// At this point you have cc already setted.

Mail::send($myMailAlert); // Here you sends the mail

注意 build 方法使用mailable 实例subjectto属性,所以你必须在发送之前设置它。

我不确定您从哪里检索您的$subjectand$to_email在您的构建方法示例中,但对于我的示例,您必须将这些值提供给$myMailAlert->subjectand $myMailAlert->to。您可以在构建方法中使用自定义变量,但鉴于该类已经具有这些属性,因此不需要自定义变量。

于 2017-04-24T10:35:44.487 回答