在Laravel中发送电子邮件非常简单,首先需要配置你的邮件驱动和邮件服务器信息,可以在`.env`文件中设置相关配置信息,例如:
```
MAIL_DRIVER=smtp
MAIL_HOST=smtp.example.com
MAIL_PORT=587
MAIL_USERNAME=your_email@example.com
MAIL_PASSWORD=your_email_password
MAIL_ENCRYPTION=tls
```
接下来,可以使用Laravel提供的`Mail` facade 来发送电子邮件。首先创建一个邮件类,可以使用Artisan命令生成:
```
php artisan make:mail OrderShipped
```
在生成的`OrderShipped`类中,可以设置邮件的内容和模板:
```php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class OrderShipped extends Mailable
{
use Queueable, SerializesModels;
protected $order;
public function __construct($order)
{
$this->order = $order;
}
public function build()
{
return $this->view('emails.orders.shipped')
->with([
'orderName' => $this->order->name,
'orderPrice' => $this->order->price,
]);
}
}
```
然后,在需要发送邮件的地方,可以使用`Mail` facade 发送邮件:
```php
use App\Mail\OrderShipped;
use Illuminate\Support\Facades\Mail;
$order = new stdClass();
$order->name = 'Product A';
$order->price = 100;
Mail::to('recipient@example.com')->send(new OrderShipped($order));
```
以上代码将会发送一个包含订单信息的邮件给`recipient@example.com`。