无法在 Laravel 5.2 内发送电子邮件

Cannot send email in Laravel 5.2

我正在尝试使用 Laravel 5.2 发送电子邮件。这是我在 Laravel 中第一次发送电子邮件。但它抛出了这个错误

Swift_TransportException in AbstractSmtpTransport.php line 162: Cannot send message without a sender address

这是我发送邮件的代码:

Route::get('test',function(){
    $message  = "hello";
    Mail::send('welcome', ['key' => 'value'], function($message)
    {

       $message->to('iljimae.ic@gmail.com', 'John Smith')->subject('Welcome!');
    });
});

这是我在 env 文件中的电子邮件设置

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=iljimae.ic@gmail.com
MAIL_PASSWORD=xxxxxx

MAIL_ENCRYPTION=null

我的欢迎视图只有一条消息"Hello world"

我已经在 Gmail 设置中为我的电子邮件配置了不太安全的应用程序设置。那么,我的代码有什么问题,为什么会抛出该错误?

您的 $message 链有 'To' 和 'Subject' 字段,但缺少 'From' 字段。

只需将 ->from() 添加到链中:

$message->to('iljimae.ic@gmail.com', 'John Smith')
    ->subject('Welcome!')
    ->from(Config::get('mail.from.address'), Config::get('mail.from.name'));

假设在您的 config/mail.php 文件中设置了 'from'(它可能引用也可能不引用环境变量)。如果不是,您可以直接指定它:

$message->to('iljimae.ic@gmail.com', 'John Smith')
    ->subject('Welcome!')
    ->from('iljimae.ic@gmail.com', 'John Smith');

错误信息Cannot send message without a sender address很清楚。您只需要在消息中添加from

Route::get('test',function(){
    $message  = "hello";
    Mail::send('welcome', ['key' => 'value'], function($message)
    {

       $message->from('myEmail@test.com')
           ->to('iljimae.ic@gmail.com', 'John Smith')
           ->subject('Welcome!');
    });
});

为了能够发送邮件,您必须将 .env 文件中的邮件加密更改为:

MAIL_ENCRYPTION=tls

如果您的邮件没有被发送,请确保从您的 .env 文件中删除此参数 "MAIL_FROM_ADDRESS=null"。这对我有用。