• 日常搜索
  • 百度一下
  • Google
  • 在线工具
  • 搜转载

如何在 Laravel 中发送电子邮件

如何在 Laravel 中发送电子邮件  第1张

在本文中,我们将探Laravel Web 框架中的 Mail api。Laravel 使用流行的 symfony Mailer 组件,该组件易于使用,并带有多种电子邮件驱动程序可供选择。

稍后,我将向您展示本文前半部分讨论的概念的深入演示。

设置先决条件

Laravel 在Symfony Mailer组件之上实现了一个包装器,这使得电子邮件管理非常容易同时配置和使用。您可以在config/mail.php找到默认邮件设置

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Mailer
    |--------------------------------------------------------------------------
    |
    | This option controls the default mailer that is used to send any email
    | messages sent by your application. Alternative mailers may be set up
    | and used as needed; however, this mailer will be used by default.
    |
    */

    'default' => env('MAIL_MAILER', 'smtp'),

    /*
    |--------------------------------------------------------------------------
    | Mailer Configurations
    |--------------------------------------------------------------------------
    |
    | Here you may configure all of the mailers used by your application plus
    | their respective settings. Several examples have been configured for
    | you, and you are free to add your own as your application requires.
    |
    | Laravel supports a variety of mail "transport" drivers to be used while
    | sending an email. You will specify which one you are using for your
    | mailers below. You are free to add additional mailers as required.
    |
    | Supported: "smtp", "sendmail", "mailgun", "ses",
    |            "postmark", "log", "array"
    |
    */

    'mailers' => [
        'smtp' => [
            'transport' => 'smtp',
            'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
            'port' => env('MAIL_PORT', 587),
            'encryption' => env('MAIL_ENCRYPTION', 'tls'),
            'username' => env('MAIL_USERNAME'),
            'password' => env('MAIL_PASSWORD'),
            'timeout' => null,
            'auth_mode' => null,
        ],

        'ses' => [
            'transport' => 'ses',
        ],

        'mailgun' => [
            'transport' => 'mailgun',
        ],

        'postmark' => [
            'transport' => 'postmark',
        ],

        'sendmail' => [
            'transport' => 'sendmail',
            'path' => '/usr/sbin/sendmail -bs',
        ],

        'log' => [
            'transport' => 'log',
            'channel' => env('MAIL_LOG_CHANNEL'),
        ],

        'array' => [
            'transport' => 'array',
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Global "From" Address
    |--------------------------------------------------------------------------
    |
    | You may wish for all emails sent by your application to be sent from
    | the same address. Here, you may specify a name and address that is
    | used globally for all emails that are sent by your application.
    |
    */

    'from' => [
        'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
        'name' => env('MAIL_FROM_NAME', 'Example'),
    ],

    /*
    |--------------------------------------------------------------------------
    | Markdown Mail Settings
    |--------------------------------------------------------------------------
    |
    | If you are using Markdown-based email rendering, you may configure your
    | theme and component paths here, allowing you to customize the design
    | of the emails. Or you may simply stick with the Laravel defaults!
    |
    */

    'markdown' => [
        'theme' => 'default',

        'paths' => [
            resource_path('views/vendor/mail'),
        ],
    ],

];

在发送电子邮件方面,Laravel 支持多种驱动程序可供选择。如您所见,默认MAIL_DRIVER设置为smtp因此,如果您想将其更改为其他内容,则需要更改.envMAIL_MAILER文件中的变量,因为这是config/mail.php文件读取邮件程序值的地方。

如果您打算使用smtp驱动程序发送电子邮件,那么您还需要.env文件中设置其他相关设置,如MAIL_HOSTMAIL_PORTMAIL_ENCRYPTIONMAIL_USERNAME和。MAIL_PASSWORD

另一方面,如果您要使用sendmail驱动程序,那么您需要确保在config/mail.php文件中将sendmail系统路径设置为正确的值。

您还可以在密钥from下设置发送电子邮件时将使用的地址。from最后,如果你想使用基于 Markdown 的电子邮件渲染,你可以在markdownkey 下指定这些设置。

最重要的是,您还可以使用 Mailgun、Postmark、SES 等第三方电子邮件服务提供商。如果您使用其中一项服务,则需要确保在config/services.php文件中设置了相应的设置。

以上就是 Laravel 中邮件 API 相关设置的基本介绍。从下一节开始,我们将通过一个自定义示例向您展示如何发送电子邮件。

创建可邮寄类

在本节中,我们将创建用于发送电子邮件的 mailable 类。mailable 类负责使用在config/mail.php文件中配置的邮件程序发送电子邮件。事实上,Laravel 已经提供了一个 artisan 命令,允许我们创建一个基本模板。

php artisan make:mail DemoEmail

这应该在app/Mail/DemoEmail.php创建一个空白电子邮件模板,如以下代码段所示。

<?php

namespace App\Mail;

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

class DemoEmail extends Mailable
{
    use Queueable, SerializesModels;

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

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

让我们用以下内容替换该文件的内容。

<?php

namespace App\Mail;

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

class DemoEmail extends Mailable
{
    use Queueable, SerializesModels;
     
    /**
     * The demo object instance.
     *
     * @var Demo
     */
    public $demo;
 
    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($demo)
    {
        $this->demo = $demo;
    }
 
    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->from('sender@example.com')
                    ->view('mails.demo')
                    ->text('mails.demo_plain')
                    ->with(
                      [
                            'testVarOne' => '1',
                            'testVarTwo' => '2',
                      ])
                      ->attach(public_path('/images').'/demo.jpg', [
                              'as' => 'demo.jpg',
                              'mime' => 'image/jpeg',
                      ]);
    }
}

mailable 类通常实现两个重要的方法:__constructbuild__construct方法用于初始化您应该在电子邮件模板中使用的对象。另一方面,该build方法用于初始化更多特定于电子邮件的值,例如来自、查看模板和附件。

在我们的例子中,我们将$demo对象作为构造函数参数传递,并将其分配给demo公共属性。

在该build方法中,我们已经初始化了一个特定于电子邮件的配置。

  • from用于设置将用作发件人地址的电子邮件地址

  • 使用该view方法,您可以设置使用此可邮寄邮件发送电子邮件时将使用的电子邮件模板。在我们的例子中,我们将其设置为mails.demo,这意味着您需要在resources/views/mails/demo.blade.php创建一个视图模板文件。

  • 接下来,该text方法用于设置电子邮件模板的纯文本版本。

  • 正如我们刚刚讨论的,该__construct方法用于设置将在电子邮件模板中使用的对象。您也可以使用该with方法,该方法允许您设置消息的视图数据。

  • 接下来,我们使用该attach方法将图像附加到消息中。请确保图像在public/images/demo.jpg中可用。

当然,我们需要创建我们应该在发送电子邮件时使用的电子邮件模板。继续创建文件resources/views/mails/demo.blade.php,如以下代码段所示。

Hello <i>{{ $demo->receiver }}</i>,
<p>This is a demo email for testing purposes! Also, it's the html version.</p>
 
<p><u>Demo object values:</u></p>
 
<div>
<p><b>Demo One:</b>&nbsp;{{ $demo->demo_one }}</p>
<p><b>Demo Two:</b>&nbsp;{{ $demo->demo_two }}</p>
</div>
 
<p><u>Values passed by With method:</u></p>
 
<div>
<p><b>testVarOne:</b>&nbsp;{{ $testVarOne }}</p>
<p><b>testVarTwo:</b>&nbsp;{{ $testVarTwo }}</p>
</div>
 
Thank You,
<br/>
<i>{{ $demo->sender }}</i>

另外,让我们在resources/views/mails/demo_plain.blade.php创建该文件的纯文本版本

Hello {{ $demo->receiver }},
This is a demo email for testing purposes! Also, it's the HTML version.
 
Demo object values:
 
Demo One: {{ $demo->demo_one }}
Demo Two: {{ $demo->demo_two }}
 
Values passed by With method:
 
testVarOne: {{ $testVarOne }}
testVarOne: {{ $testVarOne }}
 
Thank You,
{{ $demo->sender }}

这就是你可以使用的可邮寄类,我们还没有完成,因为我们需要使用Mail外观来实际发送电子邮件。在下一节中,我们将探讨如何使用Facade 使用本节中刚刚创建Mail的 Mailable 类发送电子邮件。DemoEmail

如何使用 Mailable 类

在本节中,我们将创建一个示例来演示如何使用Mailable在上一节中创建的类。

让我们使用以下命令创建一个控制器。

php artisan make:controller MailController

这应该在app/Http/Controllers/MailController.php中创建一个空白控制器文件,其中包含以下内容。

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class MailController extends Controller
{
    //
}

让我们将其替换为以下内容。

<?php
namespace App\Http\Controllers;
 
use App\Http\Controllers\Controller;
use App\Mail\DemoEmail;
use Illuminate\Support\Facades\Mail;
 
class MailController extends Controller
{
    public function send()
    {
        $objDemo = new \stdClass();
        $objDemo->demo_one = 'Demo One Value';
        $objDemo->demo_two = 'Demo Two Value';
        $objDemo->sender = 'SenderUserName';
        $objDemo->receiver = 'ReceiverUserName';
 
        Mail::to("receiver@example.com")->send(new DemoEmail($objDemo));
    }
}

需要注意的是,我们已经包含了Illuminate\Support\Facades\Mail将用于发送电子邮件的 Facade。在该方法中,以下语句首先通过初始化Mailablesend来负责发送电子邮件。App\Mail\DemoEmail

Mail::to("receiver@example.com")->send(new DemoEmail($objDemo));

Facadeto方法返回该类的一个实例,该实例已经包含在config/mail.php文件中配置的适当邮件程序。Illuminate\Support\Facades\Mail\Illuminate\Mail\Pendingmail

最后,我们使用发送实际电子邮件send的类的方法。\Illuminate\Mail\PendingMail

为了测试它,让我们在routes/web.php文件中添加一个关联的路由。

// Email related routes
Route::get('mail/send', 'MailController@send');

有了这些,您可以访问https://your-laravel-site.com/mail/send URL 以查看它是否按预期工作。

另一方面,如果你想快速测试你的电子邮件模板,而不发送实际的电子邮件,Laravel 中有一个规定允许你记录所有传出的电子邮件。

为此,您需要config/mail.php文件中设置MAIL_DRIVERto的值。接下来,您可以运行上述 URL 并检查日志文件以检查电子邮件模板是否记录在那里。log

如果一切正常,您应该会看到一封电子邮件被记录到storage/logs/laravel.log文件中。

就 Laravel 中的邮件功能而言,差不多就是这样,本文也到此结束。

结论

今天,我们浏览了 Laravel 内置的邮件 API,它也支持各种驱动程序。

从基本概念开始,我们实现了 mailable 类,它是 Laravel 中邮件 API 中的一个基本元素,随着我们继续前进。最后,我们还通过创建自定义控制器来测试 mailable 类,看看它是否真的有效。


文章目录
  • 设置先决条件
  • 创建可邮寄类
  • 如何使用 Mailable 类
  • 结论