Laravel邮件功能通过Mailable类和Mail门面实现,配置在.env文件中设置MAIL_MAILER、SMTP参数及发件人信息,使用php artisan make:mail创建邮件类,定义envelope、content方法指定主题和视图,Blade模板渲染内容,通过Mail::to()->send()发送,支持queue()异步队列,常用驱动包括SMTP、Mailgun、SES、log、array、null,适用于不同环境,调试时可借助日志、Mailtrap工具、服务商日志及队列监控,确保邮件正确发送。

Laravel的邮件功能是其框架的核心服务之一,通过
Mailable
config/mail.php
在Laravel中发送邮件,通常需要几个核心步骤。首先,是配置你的邮件服务。这通常在
.env
MAIL_MAILER
smtp
mailgun
ses
log
MAIL_HOST
MAIL_PORT
MAIL_USERNAME
MAIL_PASSWORD
MAIL_ENCRYPTION
MAIL_FROM_ADDRESS
MAIL_FROM_NAME
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io # 或者是你实际的SMTP服务器,比如smtp.gmail.com
MAIL_PORT=2525 # 或者是你的SMTP端口,比如465或587
MAIL_USERNAME=your_username
MAIL_PASSWORD=your_password
MAIL_ENCRYPTION=tls # 或者ssl,或者null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"配置好之后,下一步是创建一个
Mailable
php artisan make:mail WelcomeEmail
这个命令会在
app/Mail
WelcomeEmail.php
Mailable
build
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
class WelcomeEmail extends Mailable
{
use Queueable, SerializesModels;
public $userName;
/**
* Create a new message instance.
*/
public function __construct($userName)
{
$this->userName = $userName;
}
/**
* Get the message envelope.
*/
public function envelope(): Envelope
{
return new Envelope(
subject: '欢迎来到我们的平台!',
);
}
/**
* Get the message content definition.
*/
public function content(): Content
{
return new Content(
view: 'emails.welcome', // 指向你的Blade视图文件
with: [
'name' => $this->userName,
],
);
}
/**
* Get the attachments for the message.
*
* @return array<int, \Illuminate\Mail\Mailables\Attachment>
*/
public function attachments(): array
{
return [];
}
}对应的Blade视图文件(例如
resources/views/emails/welcome.blade.php
<h1>你好,{{ $name }}!</h1>
<p>感谢你注册我们的服务。</p>最后,在你的控制器、服务或任何你想发送邮件的地方,使用
use App\Mail\WelcomeEmail;
use Illuminate\Support\Facades\Mail;
// ...
public function sendWelcomeEmail($user)
{
Mail::to($user->email)->send(new WelcomeEmail($user->name));
// 如果想发送到多个收件人,可以使用 Mail::to(['first@example.com', 'second@example.com'])->send(...)
// 或者 Mail::to($user->email)->cc($ccEmail)->bcc($bccEmail)->send(...)
}为了提高应用的响应速度,特别是对于大量邮件发送,强烈建议将邮件发送推送到队列中。只需要让你的
Mailable
ShouldQueue
class WelcomeEmail extends Mailable implements ShouldQueue
{
// ...
}然后发送方式就变成了:
Mail::to($user->email)->queue(new WelcomeEmail($user->name));
这样,邮件发送任务就会被交给队列处理,不会阻塞用户请求。
在Laravel的邮件配置中,我们有很多种驱动(Mailer Driver)可以选择,每种都有其独特的适用场景和优缺点。理解这些驱动能帮助我们为项目选择最合适的邮件发送方案。
1. SMTP (Simple Mail Transfer Protocol) 这是最传统的邮件发送方式。你需要提供一个SMTP服务器的地址、端口、用户名和密码。
2. Mailgun, Postmark, SES (Amazon Simple Email Service), SendGrid 等第三方服务 这些都是专业的事务性邮件服务提供商。它们提供了API接口,Laravel通过SDK或HTTP请求与它们交互。
3. Log (日志驱动) 这个驱动不会真正发送邮件,而是将邮件内容写入Laravel的日志文件。
MAIL_MAILER
log
4. Array (数组驱动) 与Log驱动类似,Array驱动也不会发送邮件。它会将所有邮件存储在一个内存中的数组里。
5. Null (空驱动) 这个驱动会简单地丢弃所有邮件,不进行任何操作。
选择合适的驱动,关键在于平衡开发、测试和生产环境的需求。通常的流程是:开发时使用
log
array
在Laravel中创建自定义邮件模板并向其传递数据是一个非常常见且实用的功能,它让邮件内容更加灵活和个性化。这个过程主要围绕
Mailable
首先,如前所述,你需要使用Artisan命令创建一个
Mailable
php artisan make:mail OrderShipped
假设我们现在要发送一封订单发货通知邮件。在
app/Mail/OrderShipped.php
1. 定义需要传递的数据: 在
Mailable
<?php
namespace App\Mail;
use App\Models\Order; // 假设你有一个Order模型
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
class OrderShipped extends Mailable
{
use Queueable, SerializesModels;
public $order; // 定义一个公共属性来存储订单对象
/**
* Create a new message instance.
*/
public function __construct(Order $order) // 在构造函数中接收Order模型实例
{
$this->order = $order; // 将接收到的订单实例赋值给公共属性
}
// ... 其他方法
}2. 定义邮件信封 (Envelope): 在
envelope()
/**
* Get the message envelope.
*/
public function envelope(): Envelope
{
return new Envelope(
subject: '您的订单 #' . $this->order->id . ' 已发货!', // 使用订单数据动态设置主题
);
}3. 定义邮件内容 (Content) 和视图: 在
content()
with()
/**
* Get the message content definition.
*/
public function content(): Content
{
return new Content(
view: 'emails.orders.shipped', // 指定视图文件路径
// with: [ // 也可以在这里传递数据,但通常公共属性更直接
// 'orderId' => $this->order->id,
// 'trackingNumber' => $this->order->tracking_number,
// ],
);
}4. 创建Blade视图模板: 在
resources/views/emails/orders/shipped.blade.php
Mailable
<!DOCTYPE html>
<html>
<head>
<title>订单发货通知</title>
</head>
<body>
<h1>订单 #{{ $order->id }} 已发货!</h1>
<p>亲爱的 {{ $order->user->name }},</p>
<p>我们很高兴地通知您,您的订单已于 {{ $order->shipped_at->format('Y-m-d H:i') }} 发货。</p>
<p>追踪号码:<strong>{{ $order->tracking_number }}</strong></p>
<p>您可以点击以下链接查看订单详情:</p>
<p><a href="{{ url('/orders/' . $order->id) }}">查看订单</a></p>
<h3>订单商品:</h3>
<ul>
@foreach ($order->items as $item)
<li>{{ $item->product->name }} (x{{ $item->quantity }}) - {{ $item->price }}</li>
@endforeach
</ul>
<p>感谢您的惠顾!</p>
<p>此致,<br>您的商店团队</p>
</body>
</html>5. 发送邮件: 在你的代码中,实例化
OrderShipped
use App\Mail\OrderShipped;
use App\Models\Order;
use Illuminate\Support\Facades\Mail;
// ...
public function notifyOrderShipped(Order $order)
{
// 假设$order对象包含了所有需要的数据,包括关联的user和items
Mail::to($order->user->email)->send(new OrderShipped($order));
}Markdown Mailable (额外提示): Laravel还提供了Markdown邮件模板,它能让你用Markdown语法编写邮件内容,并且框架会自动将其渲染成美观的HTML邮件,同时提供纯文本版本。这对于那些不希望深入HTML和CSS细节的开发者来说非常方便。创建Markdown Mailable也很简单:
php artisan make:mail WelcomeUser --markdown=emails.welcome-user
然后在
build
public function build()
{
return $this->markdown('emails.welcome-user')
->with(['name' => $this->userName]);
}在Markdown视图中,你可以使用
@component('mail::message')邮件发送失败是开发中经常会遇到的问题,特别是在不同环境(开发、测试、生产)之间切换时。有效的调试和排查方法能帮助我们快速定位问题。
1. 检查.env
config/mail.php
MAIL_USERNAME
MAIL_PASSWORD
MAIL_HOST
MAIL_PORT
smtp.gmail.com
587
465
MAIL_ENCRYPTION
tls
ssl
null
MAIL_FROM_ADDRESS
2. 使用MAIL_MAILER=log
.env
MAIL_MAILER
log
storage/logs/laravel.log
Mailable
3. 使用邮件捕获工具 (Mailtrap/Mailhog/Helo): 这些工具在本地开发时非常有用。它们模拟一个SMTP服务器,捕获所有发送到它的邮件,并在一个Web界面中显示出来,而不会真正将邮件发送到外部。
MAIL_HOST
MAIL_PORT
MAIL_USERNAME
MAIL_PASSWORD
Mailable
4. 检查Laravel日志 (storage/logs/laravel.log
Connection refused
Authentication failed
Expected response code 250 but got code xxx
5. 检查第三方邮件服务提供商的日志: 如果你使用的是Mailgun、SES、SendGrid等服务,登录到它们的控制台,查看邮件发送日志。
6. 队列相关问题排查: 如果你将邮件发送推送到队列中,那么问题可能出在队列本身。
php artisan queue:work
failed_jobs
config/queue.php
7. 网络和防火墙问题: 在生产服务器上,确保服务器可以访问邮件服务的主机和端口。
telnet
nc
telnet smtp.mailgun.org 587
8. 代码逻辑审查: 回顾发送邮件的代码逻辑。
Mail::to()
Mailable
调试邮件问题需要耐心和系统性。通常我都是从
.env
log
以上就是Laravel邮件功能?邮件如何发送配置?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号