如何在Laravel中发送电子邮件

在本文中,我们将探索Laravel Web框架中的Mail API。 Laravel利用了流行的SwiftMailer库,该库易于使用,并提供了多种电子邮件驱动程序供您选择。 在本文的后期,我们将对本文上半部分讨论的概念进行深入的演示。

设置先决条件

Laravel在SwiftMailer库的顶部实现了一个包装器,使电子邮件管理非常易于同时配置和使用。 您可以在config/mail.php找到默认的邮件设置。

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Mail Driver
    |--------------------------------------------------------------------------
    |
    | Laravel supports both SMTP and PHP's "mail" function as drivers for the
    | sending of e-mail. You may specify which one you're using throughout
    | your application here. By default, Laravel is setup for SMTP mail.
    |
    | Supported: "smtp", "sendmail", "mailgun", "mandrill", "ses",
    |            "sparkpost", "log", "array"
    |
    */

    'driver' => env('MAIL_DRIVER', 'sendmail'),

    /*
    |--------------------------------------------------------------------------
    | SMTP Host Address
    |--------------------------------------------------------------------------
    |
    | Here you may provide the host address of the SMTP server used by your
    | applications. A default option is provided that is compatible with
    | the Mailgun mail service which will provide reliable deliveries.
    |
    */

    'host' => env('MAIL_HOST', 'smtp.mailgun.org'),

    /*
    |--------------------------------------------------------------------------
    | SMTP Host Port
    |--------------------------------------------------------------------------
    |
    | This is the SMTP port used by your application to deliver e-mails to
    | users of the application. Like the host we have set this value to
    | stay compatible with the Mailgun e-mail application by default.
    |
    */

    'port' => env('MAIL_PORT', 587),

    /*
    |--------------------------------------------------------------------------
    | Global "From" Address
    |--------------------------------------------------------------------------
    |
    | You may wish for all e-mails 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 e-mails that are sent by your application.
    |
    */

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

    /*
    |--------------------------------------------------------------------------
    | E-Mail Encryption Protocol
    |--------------------------------------------------------------------------
    |
    | Here you may specify the encryption protocol that should be used when
    | the application send e-mail messages. A sensible default using the
    | transport layer security protocol should provide great security.
    |
    */

    'encryption' => env('MAIL_ENCRYPTION', 'tls'),

    /*
    |--------------------------------------------------------------------------
    | SMTP Server Username
    |--------------------------------------------------------------------------
    |
    | If your SMTP server requires a username for authentication, you should
    | set it here. This will get used to authenticate with your server on
    | connection. You may also set the "password" value below this one.
    |
    */

    'username' => env('MAIL_USERNAME'),

    'password' => env('MAIL_PASSWORD'),

    /*
    |--------------------------------------------------------------------------
    | Sendmail System Path
    |--------------------------------------------------------------------------
    |
    | When using the "sendmail" driver to send e-mails, we will need to know
    | the path to where Sendmail lives on this server. A default path has
    | been provided here, which will work well on most of your systems.
    |
    */

    'sendmail' => '/usr/sbin/sendmail -bs',

    /*
    |--------------------------------------------------------------------------
    | 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

如果要使用smtp驱动程序发送邮件,则还需要设置其他相关设置,例如MAIL_HOSTMAIL_PORTMAIL_ENCRYPTIONMAIL_USERNAMEMAIL_PASSWORD

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

您还可以设置from而下发送邮件将被使用的地址from关键。 最后,如果要使用基于Markdown的电子邮件呈现,则可以在markdown键下设置这些设置。

最重要的是,您还可以使用第三方电子邮件服务提供商,例如Mailgun,Mandrill,SES和SparkPost。 如果使用的是这些服务之一,则需要确保在config/services.php文件中设置了相应的设置。

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

创建可邮寄类

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

php artisan make:mail DemoEmail

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

<?php

namespace App\Mail;

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

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\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

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方法用于初始化更多电子邮件特定的值,例如from,视图模板,附件等。

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

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

  • from被用于设置将从地址被用作电子邮件地址。
  • 使用view方法,您可以设置使用此可发送邮件发送电子邮件时将使用的电子邮件模板。 在本例中,我们将其设置为mails.demo ,这意味着您需要在resources/views/mails/demo.blade.php上创建一个视图模板文件。
  • 接下来,使用text方法设置电子邮件模板的纯文本版本。
  • 正如我们刚刚讨论的那样, __construct方法用于设置将在电子邮件模板中使用的对象,您还可以使用with方法,该方法允许您设置邮件的查看数据。
  • 接下来,我们使用了attach方法将图像attach到消息中。

当然,我们需要创建在发送电子邮件时应该使用的电子邮件模板。 继续并创建一个文件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类,我们还没有完成,因为我们需要使用Mail Facade实际发送邮件。 在下一节中,我们将探讨如何使用Mail外观通过本节中刚刚创建的DemoEmail Mailable类发送电子邮件。

包起来

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

让我们在app/Http/Controllers/MailController.php创建一个具有以下内容的控制器文件。

<?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。 在send方法中,以下语句首先通过初始化App\Mail\DemoEmail Mailable来发送电子邮件。

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

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

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

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

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

有了这个,您可以运行http://your-laravel-site.com/mail/send URL来查看它是否按预期工作。

另一方面,如果您想在不发送实际电子邮件的情况下快速测试电子邮件模板,Laravel中有一项条款允许您记录所有外发电子邮件。

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

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

就Laravel中的邮件功能而言,就差不多了,这也是本文的总结。

结论

今天,我们介绍了Laravel内置的邮件API,它还支持各种驱动程序。

从基本概念开始,我们在继续进行开发时,在Laravel中实现了mailable类,它是mail API中的基本元素。 最后,我们还通过创建自定义控制器来测试mailable类,以查看其是否真正起作用。

如果您只是开始使用Laravel或希望通过扩展来扩展您的知识,网站或应用程序,我们可以在Envato Market中提供多种学习方法

我很想通过以下供稿以查询和评论的形式了解您的反馈!

翻译自: https://code.tutsplus.com/tutorials/how-to-send-emails-in-laravel--cms-30046

Laravel 发送邮件非常简单,可以使用内置的邮件服务提供者 Mail,以及支持多种邮件驱动程序(如SMTP、Sendmail、Amazon SES等)。 下面是一个简单的示例,展示如何在 Laravel 发送电子邮件: ```php use Illuminate\Support\Facades\Mail; use App\Mail\DemoEmail; class DemoController extends Controller { public function sendEmail() { $details = [ 'title' => 'Demo Email', 'body' => 'This is a demo email from Laravel.' ]; Mail::to('example@example.com')->send(new DemoEmail($details)); return "Email sent"; } } ``` 在上面的示例,我们使用 `Mail` 门面调用 `to()` 方法指定收件人,然后使用 `send()` 方法发送邮件。在 `send()` 方法,我们传递了一个 `DemoEmail` 类实例,该类是我们定义的一个电子邮件类,它负责构建邮件内容。 以下是一个示例 `DemoEmail` 类: ```php namespace App\Mail; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; use Illuminate\Contracts\Queue\ShouldQueue; class DemoEmail extends Mailable { use Queueable, SerializesModels; public $details; public function __construct($details) { $this->details = $details; } public function build() { return $this->subject('Demo Email') ->view('emails.demo'); } } ``` 在上面的示例,我们定义了一个 `$details` 属性,它持有电子邮件内容的详细信息。然后,我们定义了一个构造函数,它接受 `$details` 并将其赋值给 `$this->details`。最后,我们定义了一个 `build()` 方法,它返回一个邮件视图,并指定了邮件主题。 在 Laravel ,邮件视图通常存储在 `resources/views/emails` 目录。例如,在上面的示例,我们可以创建一个名为 `demo.blade.php` 的视图文件,其包含电子邮件的内容。 此外,我们还可以通过链式调用方法来添加其他邮件内容,例如添加附件、Carbon副本等。 以上是一个简单的 Laravel 发送邮件的示例。您可以根据自己的需求进行更改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值