发送电子邮件时需要身份验证消息

Authentication required message when sending email

我正在尝试在用户注册时向他们发送电子邮件验证链接,但我收到一条消息 Authentication required 并且邮件未发送。我尝试使用 mailtrap 进行演示,并在生产中使用 sendgrid,但消息是一样的。这就是我的做法

在 运行 composer require guzzlehttp/guzzle 之后,我像这样更新了我的 env 文件

# MAIL_DRIVER=smtp
# MAIL_HOST=smtp.mailtrap.io
# MAIL_PORT=2525
# MAIL_USERNAME=mailtrap_username
# MAIL_PASSWORD=mailtrap_password
# MAIL_ENCRYPTION=tls

MAIL_DRIVER=smtp
MAIL_HOST=smtp.sendgrid.net
MAIL_PORT=587
MAIL_USERNAME=sendgrid_username
MAIL_PASSWORD=sendgrid_password
MAIL_ENCRYPTION=tls

在controller中,我想这样创建用户成功后发送邮件

...
use App\Mail\VerifyEmail;

...
use Illuminate\Support\Facades\Mail;

public function register(Request $request)
{
    // create and store new user record
    $user = User::create([
        'username'  => $request->username,
        'password'  => bcrypt($request->password)
    ]);

    // send user email verification link
    Mail::to($user->username)->send(new VerifyEmail());
}

VerifyMail.php

<?php

namespace App\Mail;

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

class VerifyEmail extends Mailable
{
    use Queueable, SerializesModels;

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

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        $from = 'support@fromus.com';
        $name = 'custom name';
        $subject = 'Welcome! Confirm Your Email';

        return $this->from($from, $name)
            ->subject($subject)
            ->view('auth.verify');
    }
}

按照电子邮件验证文档https://laravel.com/docs/5.8/verification#verification-routing,我将 Auth::routes(['verify' => true]) 添加到 api.php 文件,如下所示

<?php

// Register routes for email verification
Auth::routes(['verify' => true]);

Route::prefix('v1')->group(function () {

    // protected routes
    Route::middleware('auth:api')->group(function () {

        Route::get('products', 'ProductController@index'); // get products

    });

});

Route::fallback(function () {
    return response()->json(['error' => 'Not Found'], 404);
});

为什么我会收到 Authentication required 错误消息,我该如何解决?

首先,我从 api.php 文件中删除了 Auth::routes(['verify' => true]),并将其添加到 web.php 中。 然后我 运行 php artisan config:cache 缓存对 env 文件所做的更改。固定