首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在laravel 8mail::send中动态指定from

在 Laravel 8 中,可以使用 mail::send 方法来发送邮件。要在 mail::send 方法中动态指定 from 地址,可以通过在邮件类中设置 from 属性来实现。

首先,创建一个邮件类,例如 DynamicFromMail,并在该类中定义 from 属性。在构造函数中,接收一个参数用于动态指定 from 地址。然后,在 build 方法中构建邮件内容。

代码语言:txt
复制
namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class DynamicFromMail extends Mailable
{
    use Queueable, SerializesModels;

    public $fromAddress;

    /**
     * Create a new message instance.
     *
     * @param string $fromAddress
     * @return void
     */
    public function __construct($fromAddress)
    {
        $this->fromAddress = $fromAddress;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->from($this->fromAddress)
                    ->view('emails.dynamic_from');
    }
}

在上述代码中,DynamicFromMail 类继承自 Mailable 类,并使用 QueueableSerializesModels traits。$fromAddress 变量用于存储动态指定的 from 地址。

接下来,在 build 方法中使用 from 方法来设置邮件的发送地址为 $fromAddress

然后,创建一个邮件视图文件 dynamic_from.blade.php,用于定义邮件的内容。

代码语言:txt
复制
<!DOCTYPE html>
<html>
<head>
    <title>Dynamic From Mail</title>
</head>
<body>
    <h1>Hello!</h1>
    <p>This is a dynamic from mail.</p>
</body>
</html>

最后,在需要发送邮件的地方,可以使用以下代码来发送动态指定 from 地址的邮件:

代码语言:txt
复制
use App\Mail\DynamicFromMail;
use Illuminate\Support\Facades\Mail;

$fromAddress = 'sender@example.com';
$mail = new DynamicFromMail($fromAddress);
Mail::to('recipient@example.com')->send($mail);

在上述代码中,首先创建一个 DynamicFromMail 实例,并传入动态指定的 from 地址。然后,使用 Mail::to 方法指定邮件的接收地址,并使用 send 方法发送邮件。

这样,就可以在 Laravel 8 的 mail::send 方法中动态指定 from 地址了。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券