首页 > 解决方案 > 如何在 laravel 8 mail::send 中即时指定

问题描述

从我网站上的联系表中,我向访问者发送了一封确认电子邮件,并向网站管理员发送了一封电子邮件。两封电子邮件都将发送到 .env 中定义的电子邮件地址。如何更改发送给管理员的电子邮件的发件人字段?我当前的第二个 Mail:: 给出错误的代码。

   // send html email to user
   Mail::to(request('email'))
   ->send(new ContactWebsite($emailFields));
   // send html email to admin
   Mail::to("newemail@address")
   ->from(request('email'))
   ->send(new ContactWebsite($emailFields));

丹尼尔的解决方案很好,但我该如何实施呢?

在 Contact Contoller 存储函数中,我将 fromAddress 放在 $emailFields 对象中:

 $emailFields = (object) [
 'fromName' => $fullnameUser,
 'fromEmail' => request('email'),
 'fromAddress' => $fullnameUser.' <'.request('email').'>',
 'subject' => '...',
 'body' => request('body')
 ];

然后在Mailable中:

public function __construct($emailFields) {
    $this->emailFields = $emailFields;
    $this->fromAddress = $emailAddress['fromAddress'];
}

public function build() {
    return $this->markdown('emails.contact-confirm-user');
}

__construct 函数中的语法是否正确?

以及如何在构建函数中传递 $this->fromAddress ?

标签: laravelemail

解决方案


您应该将类​​函数中的->from()部分(在您的情况下)定义为 的一部分或作为第二个参数。然后你只需在函数中使用它:Mailablebuild()ContactWebsite$emailFieldsbuild

class ContactWebsite extends Mailable
{
    use Queueable, SerializesModels;
    
    private $fromAddress = 'default@value.com';

    public function __construct($emailFields, $fromAddress = null)
    {
        if ($fromAddress) {
            $this->fromAddress = $fromAddress;
        }
    }

    public function build()
    {
        return $this->from($this->fromAddress)
            // Whatever you want here
            ->send()
    }
}

推荐阅读