在 Laravel 8 中,可以使用 mail::send
方法来发送邮件。要在 mail::send
方法中动态指定 from
地址,可以通过在邮件类中设置 from
属性来实现。
首先,创建一个邮件类,例如 DynamicFromMail
,并在该类中定义 from
属性。在构造函数中,接收一个参数用于动态指定 from
地址。然后,在 build
方法中构建邮件内容。
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
类,并使用 Queueable
和 SerializesModels
traits。$fromAddress
变量用于存储动态指定的 from
地址。
接下来,在 build
方法中使用 from
方法来设置邮件的发送地址为 $fromAddress
。
然后,创建一个邮件视图文件 dynamic_from.blade.php
,用于定义邮件的内容。
<!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
地址的邮件:
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
地址了。
领取专属 10元无门槛券
手把手带您无忧上云