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

时间:2019-07-17 15:34:05

标签: php sendgrid laravel-5.8

我正在尝试向用户注册时向用户发送电子邮件验证链接,但我收到消息Authentication required,但未发送邮件。我尝试将mailtrap用于演示和sendgrid,这些将在生产中使用,但消息是相同的。这就是我要怎么做

运行composer require guzzlehttp/guzzle后,我像这样更新了我的环境文件

# 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

在控制器中,我想在这样成功创建用户之后发送邮件

...
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错误消息,该如何解决?

1 个答案:

答案 0 :(得分:0)

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