首页 > PHP > Laravel教程 邮件

Laravel教程 邮件

2025-03-06 16:26:08

以下是一个完整的 Laravel 邮件发送教程及示例代码:

1. 环境准备

确保你已经安装了 Laravel 项目。如果还没有安装,可以使用 Composer 进行安装:

composer create-project --prefer-dist laravel/laravel my-mail-project
cd my-mail-project

2. 配置邮件驱动

打开 .env 文件,配置邮件驱动及相关信息。以 Gmail 为例:

MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=your_email@gmail.com
MAIL_PASSWORD=your_app_password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=your_email@gmail.com
MAIL_FROM_NAME="${APP_NAME}"

注意:对于 Gmail,你需要生成应用密码,而不是使用你的常规 Gmail 密码。具体步骤可参考 Google 的官方文档。

3. 创建邮件类

使用 Artisan 命令创建一个新的邮件类:

php artisan make:mail WelcomeMail

这将在 app/Mail 目录下生成一个 WelcomeMail.php 文件。打开该文件,添加以下代码:

<?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 WelcomeMail extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * Create a new message instance.
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the message envelope.
     */
    public function envelope(): Envelope
    {
        return new Envelope(
            subject: 'Welcome to Our Application',
        );
    }

    /**
     * Get the message content definition.
     */
    public function content(): Content
    {
        return new Content(
            view: 'emails.welcome',
        );
    }

    /**
     * Get the attachments for the message.
     *
     * @return array<int, \Illuminate\Mail\Mailables\Attachment>
     */
    public function attachments(): array
    {
        return [];
    }
}

4. 创建邮件视图

在 resources/views/emails 目录下创建一个 welcome.blade.php 文件,添加以下内容:

<!DOCTYPE html>
<html>
<head>
    <title>Welcome Email</title>
</head>
<body>
    <h1>Welcome to Our Application!</h1>
    <p>Thank you for signing up.</p>
</body>
</html>

5. 发送邮件

在控制器或路由中添加以下代码来发送邮件:

<?php

namespace App\Http\Controllers;

use App\Mail\WelcomeMail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;

class MailController extends Controller
{
    public function sendWelcomeMail()
    {
        $recipient = 'recipient_email@example.com';
        Mail::to($recipient)->send(new WelcomeMail());

        return 'Welcome email sent successfully!';
    }
}

6. 定义路由

打开 routes/web.php 文件,添加以下路由:

use App\Http\Controllers\MailController;

Route::get('/send-mail', [MailController::class, 'sendWelcomeMail']);
 

7. 测试邮件发送

启动 Laravel 开发服务器:

php artisan serve

然后在浏览器中访问 http://localhost:8000/send-mail,如果一切配置正确,你将看到 Welcome email sent successfully! 消息,并且收件人将收到欢迎邮件。

队列发送邮件(可选)

如果你想使用队列来发送邮件,可以在 config/mail.php 中设置 'queue' => true,并将邮件发送代码修改为:

Mail::to($recipient)->queue(new WelcomeMail());

同时,确保队列监听器正在运行:

php artisan queue:work

以上就是一个完整的 Laravel 邮件发送教程及示例代码。

使用 Ctrl+D 可将网站添加到书签
收藏网站
扫描二维码
关注早实习微信公众号
官方公众号
Top