You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 8 邮件发送失败问题排查求助

Laravel 8 注册欢迎邮件无法发送排查与解决

问题背景

使用Laravel 8开发应用,用户通过API完成注册后触发事件发送欢迎邮件,但邮件始终无法正常发送,相关配置与代码如下:

.env 配置

MAIL_MAILER=sendmail
MAIL_HOST=mailhog
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${APP_NAME}"

事件代码(SendWelcomeMailToNewUser)

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class SendWelcomeMailToNewUser
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $userId;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($userId)
    {
        $this->userId = $userId;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }
}

监听器代码(SendMailFired)

<?php

namespace App\Listeners;

use App\Events\SendWelcomeMailToNewUser;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
// use Illuminate\Support\Facades\Log;
use App\Mail\RegistrationMail;
use Illuminate\Support\Facades\Mail;

class SendMailFired
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  \App\Events\SendWelcomeMailToNewUser  $event
     * @return void
     */
    public function handle(SendWelcomeMailToNewUser $event)
    {
        //Log::info('info to log');  // This log is working fine.

        $details = [
            'title' => 'Mail from Promise 2 Deliver',
            'body'  => 'This is your first mail using smtp',
        ];

        Mail::to('abueabu@gmail.com')->send( new RegistrationMail($details) );
    }
}

邮件类代码(RegistrationMail)

<?php

namespace App\Mail;

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

class RegistrationMail extends Mailable
{
    use Queueable, SerializesModels;

    public $details;

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

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('email.registration_email');
    }
}

API注册接口代码

public function apiregister(StoreUserRequest $request)
{
    if( $request->is('api/*')){
        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'phone' => $request->phone,
            'address' => $request->address,
            'password' => Hash::make($request->password),
        ]);

        
        if ( $user ) {
            event(new SendWelcomeMailToNewUser($request->email));

            $response = ['user' => $user, "message" => "Registration successful"];
            return response( $response, 200 );
        } else {
            $response = ["message" => 'Registration failed.'];
            return response( $response, 422 );
        }
    }
}

排查与解决方案

1. 邮件驱动与服务不匹配

当前.env配置使用sendmail驱动,但你实际用的是MailHog(SMTP服务),需修改驱动为smtp:

MAIL_MAILER=smtp

修改后执行命令清除配置缓存:

php artisan config:clear

2. 发件人地址未配置

.env中MAIL_FROM_ADDRESS=null,多数邮件服务(包括MailHog)要求必须设置有效的发件人邮箱,否则会拒绝请求:

MAIL_FROM_ADDRESS=hello@your-app.com

3. 事件与监听器绑定检查

确保事件和监听器已在app/Providers/EventServiceProvider.php中正确绑定:

protected $listen = [
    \App\Events\SendWelcomeMailToNewUser::class => [
        \App\Listeners\SendMailFired::class,
    ],
];

若未绑定,执行命令刷新事件缓存:

php artisan event:clear
php artisan event:cache

4. 错误捕获与日志排查

在监听器handle方法中添加错误捕获,定位具体问题:

public function handle(SendWelcomeMailToNewUser $event)
{
    try {
        $details = [
            'title' => 'Mail from Promise 2 Deliver',
            'body'  => 'This is your first mail using smtp',
        ];

        Mail::to('abueabu@gmail.com')->send( new RegistrationMail($details) );
        \Illuminate\Support\Facades\Log::info('Welcome email sent successfully');
    } catch (\Exception $e) {
        \Illuminate\Support\Facades\Log::error('Failed to send welcome email: ' . $e->getMessage());
    }
}

查看storage/logs/laravel.log获取错误详情。

5. MailHog服务状态检查

确认MailHog已启动,访问http://localhost:8025(默认端口)查看控制台,验证服务是否在线。

6. 事件参数一致性优化

API接口中传递的是用户邮箱,但事件类参数名为$userId,虽不影响当前发送,但建议保持参数名称一致避免后续问题:

// 事件类修改
public $email;

public function __construct($email)
{
    $this->email = $email;
}

验证步骤

  1. 重启Laravel服务:php artisan serve
  2. 重新调用注册API
  3. 访问MailHog控制台查看邮件
  4. 检查日志确认是否有报错

内容的提问来源于stack exchange,提问作者abu abu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 04:53:07