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

Laravel使用Mailtrap发送重置邮件时触发空值数组偏移错误

Laravel使用Mailtrap发送密码重置邮件时出现"Trying to access array offset on value of type null"错误排查

错误信息

触发错误:Trying to access array offset on value of type null,错误栈指向vendor/symfony/mailer/Transport/Smtp/Stream/AbstractStream.php第92行,对应代码error_get_last()['message']——当error_get_last()返回null时,访问其数组偏移触发该错误。

相关配置与代码

.env邮件配置

MAIL_MAILER=smtp
MAIL_HOST=sandbox.smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=5bbd4ea216db1c
MAIL_PASSWORD=********8e96
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="admin@school.com"
MAIL_FROM_NAME="${APP_NAME}"

忘记密码邮件类

class ForgotPasswordMail extends Mailable
{
    use Queueable, SerializesModels;
    public $user;

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

    public function envelope(): Envelope
    {
        return new Envelope(
            subject: 'Forgot Password ',
        );
    }

    public function content(): Content
    {
        return new Content(
            markdown: 'email.forgot',
            with: [
                'user' => $this->user,
            ],
        );
    }

    public function attachments(): array
    {
        return [];
    }
}

控制器代码

public function postForgotPassword(Request $request)
{
    $user = User::getEmailSingle($request->email);

    if (!empty($user)) {
        $user->remember_token == Str::random(30);
        $user->save();
        mail::to($user->email)->send(new ForgotPasswordMail($user));
        return redirect()->back()->with('success', "Please check your email and reset your password");

    } else {
        return redirect()->back()->with('error', "Email not found in the system");
    }
}

邮件视图

@component('mail::message')
Hello{{$user->name}},
<p>We understand it happens</p>

@component('mail::button', ['url' => url('reset/', $user->remember_token)])
Reset your Password
@endcomponent
<p> In case you have any issues recovering your password,please contact us.</p>
Thanks,<br>
{{config('app.name')}}
@endcomponent 

问题根源与修复步骤

1. 修复SMTP加密配置

MAIL_ENCRYPTION=null配置错误,Mailtrap的2525端口需要使用tls加密(STARTTLS协议)。该错误会导致SMTP连接建立失败,进而使error_get_last()返回null,触发数组偏移访问错误。

修改.env:

MAIL_ENCRYPTION=tls

2. 修复控制器中的赋值错误

控制器内$user->remember_token == Str::random(30);使用了比较运算符==,未实际更新用户的remember_token值,应改为赋值运算符=:

$user->remember_token = Str::random(30);
$user->save();

此错误虽不是当前邮件发送错误的直接原因,但会导致后续密码重置链接无效,必须修复。

3. 确保Mailtrap凭据正确

验证MAIL_USERNAME和MAIL_PASSWORD与Mailtrap沙箱中的凭据完全一致,避免多余空格或字符。

4. 清除配置缓存

修改.env后执行命令,确保新配置生效:

php artisan config:clear

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 22:42:13