【问题标题】:Sending a mail without `to` method in Laravel在 Laravel 中发送没有“to”方法的邮件
【发布时间】:2017-04-24 08:43:57
【问题描述】:

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

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

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

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

但它失败了:

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

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

【问题讨论】:

  • 您想要这样做的任何具体原因? build 方法是什么意思?
  • @imrealashu 我的可邮寄类的构建方法:laravel.com/docs/5.4/mail#generating-mailables 原因是在我的可邮寄类中做一些事情之前我不知道收件人

标签: php laravel laravel-5 laravel-5.4 laravel-mail


【解决方案1】:

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

但是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方法使用了可邮寄实例的subjectto属性,所以你必须在发送前设置。

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

【讨论】:

    【解决方案2】:

    这里有一个 hack 来解决这个问题:

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

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

    【讨论】:

      猜你喜欢
      • 2020-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-04
      • 2021-02-03
      • 2018-06-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多