laravel 邮件发送_在Laravel中发送电子邮件的最终指南

laravel 邮件发送

Sending emails in web applications has become so essential. Marketing, notifications, newsletters, adverts, etc are some of the reasons why we send emails to our clients. I'd say the majority of websites send automated emails at least via a "Contact us" form.

在Web应用程序中发送电子邮件变得非常重要。 市场营销,通知,新闻通讯,广告等是我们向客户发送电子邮件的一些原因。 我想大多数网站至少会通过“与我们联系”表格发送自动电子邮件。

Let's explore the many possible ways to send emails in a Laravel application.

让我们探索在Laravel应用程序中发送电子邮件的多种可能方式。

选择电子邮件服务提供商 ( Choosing An Email Service Provider )

Although your first thought when you see "Email Service Provider" may be service providers in Laravel, that is not what I am referring to here. I am referring to online services that provide email sending functionalities via APIs.

尽管当您看到“电子邮件服务提供商”时最初想到的可能是Laravel中的服务提供商,但这不是我在这里指的。 我指的是通过API提供电子邮件发送功能的在线服务。

You might be wondering why you need to make use of a service when you can just go hardcore with SMTP. The old way works fine, no doubt, but if you really want something awesome, robust, scalable and economic, then a service provider is better as it does all the hard jobs and just gives you an endpoint for your program to talk to,

您可能想知道为什么仅通过SMTP进行硬核时为什么需要使用服务。 毫无疑问,旧方法可以很好地工作,但是如果您真的想要一些很棒,强大,可扩展且经济的东西 ,那么服务提供商会更好,因为它可以完成所有艰苦的工作,并为您提供程序可以与之对话的端点,

We are going to review several possible providers and how to set them up in a Laravel application. Speaking of which, install a new Laravel application and leave config/services.php open in your favorite editor.

我们将审查几种可能的提供程序,以及如何在Laravel应用程序中进行设置。 说到这, 安装一个新的Laravel应用程序,并在您喜欢的编辑器中将config/services.php打开状态。

Mailgun (Mailgun)

  1. Sign up for an account if you have not.

    如果尚未注册,请注册一个帐户。

  2. Verify your email and phone number.

    验证您的电子邮件和电话号码。

  3. You will be redirected to your Dashboard.

    您将被重定向到仪表板。

  4. Locate your API Key and domain

    找到您的API密钥和域

邮件陷阱 (Mailtrap)

Mailtrap is awesome for development and testing. It was not built with sending emails in production in mind.

Mailtrap非常适合开发和测试。 它并不是在生产时就发送电子邮件的。

  1. Registier via https://mailtrap.io/register/signup

    通过https://mailtrap.io/register/signup注册
  2. Verify if necessary

    必要时验证
  3. Access your inboxes via https://mailtrap.io/inboxes

    通过https://mailtrap.io/inboxes访问您的收件箱
  4. Store the SMTP credentials somewhere safe

    将SMTP凭据存储在安全的地方

山d (Mandrill)

  1. Sign up

    注册

  2. Setup a domain name

    设置域名

  3. Go to settings from the left menu

    从左侧菜单转到设置

  4. Click Add API key

    点击添加API密钥

  5. Add Mandrill option in the config/services.php file

    config/services.php文件中添加Mandrill选项

'mandrill' => [
        'secret' => env('MANDRILL_KEY'),
    ],

There are several more options, including Amazon SES, but we will just focus on a few. They are all very similar to setup so let us just stick with learning with what we have.

还有更多选项,包括Amazon SES,但我们仅关注其中几个。 它们都与设置非常相似,因此让我们坚持学习已有的东西。

配置我们的服务 ( Configuring Our Services )

Our config/services.php has all the configuration for major external services that are required for our application. It is also recommended that if Laravel does not provide any service, you should stick to the design pattern of using the services config file to configure your application.

我们的config/services.php具有应用程序所需的主要外部服务的所有配置。 还建议如果Laravel不提供任何服务,则应坚持使用services config文件配置应用程序的设计模式。

'mailgun' => [
        'domain' => env('MAILGUN_DOMAIN'),
        'secret' => env('MAILGUN_SECRET'),
    ],

    'mandrill' => [
        'secret' => env('MANDRILL_KEY'),
    ],

    'ses' => [
        'key' => env('SES_KEY'),
        'secret' => env('SES_SECRET'),
        'region' => 'us-east-1',
    ],

    'sparkpost' => [
        'secret' => env('SPARKPOST_SECRET'),
    ],

    'stripe' => [
        'model' => App\User::class,
        'key' => env('STRIPE_KEY'),
        'secret' => env('STRIPE_SECRET'),
    ],

Notice that Mailtrap is missing here. It uses SMTP and is provided as default in every Laravel installation because it is made for testing purposes.

请注意,这里没有Mailtrap。 它使用SMTP,并且在每个Laravel安装中默认提供,因为它是出于测试目的而制作的。

A practice really frowned upon is storing credentials in codes as they may leak to the wrong hands, especially while moving a code base around in a VCS. For this reason, Laravel uses a .env file for storing it's credentials and environmental variables:

真正不习惯的做法是将凭据存储在代码中,因为它们可能会泄漏给错误的人,尤其是在VCS中移动代码库时。 因此,Laravel使用.env文件存储其凭据和环境变量:

APP_ENV=local
APP_DEBUG=true
APP_KEY=[APPLICATION_KEY]
APP_URL=http://localhost

DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp

MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=[MAILTRAP_USERNAME]
MAIL_PASSWORD=[MAILTRAP_PASSWORD]
MAIL_ENCRYPTION=null

MAILGUN_DOMAIN=[MAILGUN_DOMAIN]
MAILGUN_SECRET=[MAILGUN_SECRET]

MANDRILL_KEY=[MANDRILL_KEY]

You can go ahead to replace the usernames, passwords, keys, domains and secrets you got while registering for the email services.

您可以继续替换在注册电子邮件服务时获得的用户名,密码,密钥,域和机密。

设置默认选项 (Setting a Default Option)

As I already mentioned, we cannot use all the services at the same time. In that case, even after setting up multiple providers, we still need to tell Laravel which one to use:

正如我已经提到的,我们不能同时使用所有服务。 在那种情况下,即使设置了多个提供程序,我们仍然需要告诉Laravel使用哪个提供程序:

//SMTP/Mailtrap
MAIL_DRIVER=smtp

//Mailgun
MAIL_DRIVER=mailgun

//Mandrill
MAIL_DRIVER=mandrill

//etc

发送邮件 ( Sending Emails )

Setting up the services and configuring them does not actually send the emails, but it is an amazing step we have taken together. We can do better. Let us send an email.

设置服务并对其进行配置实际上并不会发送电子邮件,但这是我们一起迈出的了不起的一步。 我们可以做得更好。 让我们发送电子邮件。

基本方法 (A Basic Approach)

We will use RESTful approach to send the emails because it is the standard. So get your Postman ready to do some jobs.

因为它是标准的,所以我们将使用RESTful方法发送电子邮件。 因此,请让您的邮递员做好一些工作。

We do not need a Model or a View with where we are headed. Instead we just need a controller and a route. Create a controller named EmailController:

我们不需要朝向的模型或视图。 相反,我们只需要一个控制器和一条路线。 创建一个名为EmailController的控制器:

php artisan make:controller EmailController

Now add a simple route to app/Http/routes.php:

现在将简单的路由添加到app/Http/routes.php

Route::post('/send', 'EmailController@send');

Our controller is pointing to the controller we created and is asking the send action method to process the request. Let us go ahead and create the send action method:

我们的控制器指向我们创建的控制器,并要求send action方法处理请求。 让我们继续创建send操作方法:

Note: Action methods are methods in a controller that handle a request.

注意:操作方法是控制器中处理请求的方法。

public function send(Request $request){
    //Logic will go here        
}

That is a basic method waiting and ready to be fleshed out. We have also type-hinted Request if we need anything to do with the request object.

这是等待并准备充实的基本方法。 我们还TYPE-暗示Request ,如果我们需要什么做的请求对象。

To send HTML emails, we need to create a template for that. Create a send.blade.php file in resources/views/emails with the following:

要发送HTML电子邮件,我们需要为此创建一个模板。 在resources/views/emails使用以下命令创建send.blade.php文件:

<html>
<head></head>
<body style="background: black; color: white">
<h1>{{$title}}</h1>
<p>{{$content}}</p>
</body>
</html>

Back to the action method. It is time to actually add the mail sending logic which can be done using the Mail facade:

回到动作方法。 现在是时候实际添加可以使用Mail Facade完成的邮件发送逻辑了:

public function send(Request $request)
    {
        $title = $request->input('title');
        $content = $request->input('content');

        Mail::send('emails.send', ['title' => $title, 'content' => $content], function ($message)
        {

            $message->from('me@gmail.com', 'Christian Nwamba');

            $message->to('chrisn@scotch.io');

        });


        return response()->json(['message' => 'Request completed']);
    }

The Mail Facade which is used to handle emails in Laravel provides several methods including send(). The send() method takes 3 parameters: a blade view, data to be bound to the view, and a closure. You can configure the mail how ever you want in the closure.

在Laravel中用于处理电子邮件的Mail Facade提供了几种方法,包括send()send()方法采用3个参数:刀片视图,要绑定到该视图的数据和一个闭包。 您可以在封尾中随意配置邮件。

Head to Postman and make a Post request to /send with title and content as seen below:

前往邮递员,并/send带有titlecontent的邮寄请求,如下所示:

Below is an image of this mail as it arrives in Mailtrap

下面是此邮件到达Mailtrap时的图像

We can configure all the properties of an email right inside the closure. Below are the available options as provided by Taylor:

我们可以在闭包内部配置电子邮件的所有属性。 以下是泰勒提供的可用选项:

$message->from($address, $name = null);
$message->sender($address, $name = null);
$message->to($address, $name = null);
$message->cc($address, $name = null);
$message->bcc($address, $name = null);
$message->replyTo($address, $name = null);
$message->subject($subject);
$message->priority($level);
$message->attach($pathToFile, array $options = []);

Let us experiment with one more of the features which is $message->attach()

让我们尝试一下$message->attach()一项功能

附加档案 (Attaching Files)

Attaching files is very simple. We just use the attach() method and supply a file path.

附加文件非常简单。 我们只使用attach()方法并提供文件路径。

public function send(Request $request)
    {
        $title = $request->input('title');
        $content = $request->input('content');
        //Grab uploaded file
        $attach = $request->file('file');

        Mail::send('emails.send', ['title' => $title, 'content' => $content], function ($message) use ($attach)
        {

            $message->from('me@gmail.com', 'Christian Nwamba');

            $message->to('chrisn@scotch.io');

            //Attach file
            $message->attach($attach);

            //Add a subject
            $message->subject("Hello from Scotch");

        });

We requested a file uploaded via a form and attached it to the mail. Notice that we also added a subject to the email.

我们要求通过表单上传文件,并将其附加到邮件中。 请注意,我们还在电子邮件中添加了一个主题。

队列优化 (Optimizing with Queues)

You can now use queues to optimize sending emails. It is dead simple. Instead of sending with the send() method, we send with the queue() method:

现在,您可以使用队列来优化发送电子邮件。 很简单。 我们不使用send()方法发送,而是使用queue()方法发送:

public function send(Request $request)
    {
        //Using queues is better
        Mail::queue('emails.send', ['title' => $title, 'content' => $content], function ($message) use ($attach)
        {


        });
    }

Remember that we have to run the listen command on the queues before they can be dispatched:

请记住,必须先在队列上运行listen命令,然后才能分派它们:

php artisan queue:listen

In production, it is not advisable to use listen because of it's high CPU usage. It is better we use work and pass the --daemon option:

在生产中,不建议使用listen因为它占用大量CPU。 最好使用work并传递--daemon选项:

sudenohup php artisan queue:work --daemon --tries=3

奖励:使用MailChimp的批量电子邮件通知 ( Bonus: Bulk Email Notifications with MailChimp )

As this article is one about sending emails, it would be nice to consider sending bulk emails. The popular tool that handles this is Mailchimp so lets try that out.

由于本文是有关发送电子邮件的文章,因此考虑发送批量电子邮件会很好。 Mailchimp是处理此问题的流行工具,因此让我们尝试一下。

设置MailChimp (Setup MailChimp)

Setting up Mailchimp invovles two steps - account creation and Laravel project setup. To create a MailChimp account, head straight to the Sign up page, sign up, and verify your account if required.

设置Mailchimp涉及两个步骤-帐户创建和Laravel项目设置。 要创建MailChimp帐户,请直接转到“ 注册”页面,注册并根据需要验证您的帐户。

Next create a list of your subscribers. In a real project, you would be adding users to the list programatically using the API, but we can just go ahead and create some via the dashboard as seen below.

接下来,创建您的订户列表。 在真实的项目中,您将使用API​​以编程方式将用户添加到列表中,但是我们可以继续通过仪表板创建一些用户,如下所示。

Now grab the List Id by going to Settings > List name and defaults. Also create and get your API key from User > Accounts > Extras > API Keys. "User" stands for your username, which is on the navigation bar.

现在,转到“设置”>“列表名称和默认值”以获取“列表ID”。 另外,还可以从用户>帐户>附加> API密钥创建并获取您的API密钥。 “用户”代表您的用户名,该用户名位于导航栏上。

Head back to the Laravel project and store the key and Id in .env:

回到Laravel项目并将密钥和ID存储在.env中:

MAILCHIMP_KEY=[KEY]
MAILCHIMP_LIST_ID=[ID]

Then pull Mandrill's PHP SDK from composer:

然后从作曲家那里提取MandrillPHP SDK:

composer require mailchimp/mailchimp

发送活动 (Sending Campaigns)

Mailchimp's bulk emails are identified as campaigns. Let us create another simple action method to handle sending bulk message to our list of subscribers:

Mailchimp的批量电子邮件被标识为活动。 让我们创建另一个简单的操作方法来处理向我们的订户列表发送批量消息:

public function notify(Request $request){

        //List ID from .env
        $listId = env('MAILCHIMP_LIST_ID');

        //Mailchimp instantiation with Key
        $mailchimp = new \Mailchimp(env('MAILCHIMP_KEY'));

        //Create a Campaign $mailchimp->campaigns->create($type, $options, $content)
        $campaign = $mailchimp->campaigns->create('regular', [
            'list_id' => $listId,
            'subject' => 'New Article from Scotch',
            'from_email' => 'pub@gmail.com',
            'from_name' => 'Scotch Pub',
            'to_name' => 'Scotch Subscriber'

        ], [
            'html' => $request->input('content'),
            'text' => strip_tags($request->input('content'))
        ]);

        //Send campaign
        $mailchimp->campaigns->send($campaign['id']);

        return response()->json(['status' => 'Success']);
    }

We are using two campaign methods: create() and send(). The create() method provisions a campaign and returns an array which contains the id of our campaign. We then pass this id to the send() method to dispatch the emails. That's all!

我们使用两种广告活动方法: create()send()create()方法提供一个广告系列,并返回一个包含广告系列id的数组。 然后,我们将此id传递给send()方法以分派电子邮件。 就这样!

Go ahead and add the extra route:

继续并添加额外的路线:

Route::post('/notify', 'EmailController@notify');

结论 ( Conclusion )

If your web application sends emails, it is recommended you take the extra mile and use useful services to optimize the whole process. Test your emails with Mailtrap, send with Mandrill/Mailgun/SES or anything that suites you, and optimize with Queues.

如果您的Web应用程序发送电子邮件,建议您多花一些功夫,并使用有用的服务来优化整个过程。 使用Mailtrap测试您的电子邮件,使用Mandrill / Mailgun / SES或适合您的任何内容进行发送,并使用队列进行优化。

翻译自: https://scotch.io/tutorials/ultimate-guide-on-sending-email-in-laravel

laravel 邮件发送

  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
©️2021 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值