Laravel 5.3 The use of e-mail features detailed

Source: Internet
Author: User
Tags constructor event listener require valid email address all mail sparkpost

1. Introduction
Laravel based on the Swiftmailer library provides a clean, refreshing messaging API. Laravel provides drivers for SMTP, Mailgun, Sparkpost, Amazon SES, PHP mail functions, and sendmail, allowing you to quickly send mail through local or cloud services.

Message Driver Readiness Knowledge

Drive-based APIs such as Mailgun and sparkpost are typically simpler and faster than SMTP servers, so use these services whenever possible. All API driver requirements are installed Guzzle HTTP Library, you can install it through composer Package Manager:

Composer require Guzzlehttp/guzzle
Mailgun Drive

To use the Mailgun driver (Mailgun first 10000 messages for free, subsequent charges), first install the guzzle, and then set the driver option to Mailgun in the profile config/mail.php. Next, verify that the configuration file config/services.php contains the following options:

' Mailgun ' => [
' Domain ' => ' your-mailgun-domain ',
' Secret ' => ' Your-mailgun-key ',
],
Sparkpost Drive

To use the Sparkpost driver, first install guzzle, and then set the driver option value to Sparkpost in the configuration file config/mail.php. Next, verify that the configuration file config/services.php contains the following options:

' Sparkpost ' => [
' Secret ' => ' Your-sparkpost-key ',
],
SES drive

To install Amazon AWS's PHP SDK using Amazon SES driver (surcharge), you can install the library by adding the following line to the Require section of the Composer.json file and then running the composer Update command:

"aws/aws-sdk-php": "~3.0"
Next, the driver option in the Set configuration file config/mail.php is SES. Then, verify that the configuration file config/services.php contains the following options:

' SES ' => [
' Key ' => ' Your-ses-key ',
' Secret ' => ' Your-ses-secret ',
' Region ' => ' ses-region ',//e.g. us-east-1
],
2, the generation can mail class
In Laravel, each message sent by the application can be represented as a "mail-ready" class, all of which are stored in the App/mail directory. If you don't see this directory, don't worry, it will be generated when you use the Make:mail command to create the first mailing class:

PHP Artisan Make:mail ordershipped
3, the preparation of the mailing category
All of the mailing class configurations are done in the build method, in which you can invoke multiple methods, such as from, subject, view, and attach to configure the contents of the message and send it.

Configure Sender

Using the From method

Let's take a look at the sender's configuration, or, in other words, who the message came from. There are two ways to configure the sender, the first way is to call the From method in the build method method of the mailing class:

/**
* Build the message.
*
* @return $this
*/
Public Function Build ()
{
return $this->from (' example@example.com ')
->view (' emails.orders.shipped ');
}
Use Global from address

However, if your application uses the same sending address in all messages, it is cumbersome to call the From method in each of the generated mailing classes. Instead, you can specify a global send address in the configuration file config/mail.php, which can be used in scenarios where no other sending address is specified in all the available mailing classes:

' From ' => [' Address ' => ' example@example.com ', ' name ' => ' App name '],
Configuration view

You can use the view method in the Mail class build method to specify which template to use when rendering the message content, because each message basically uses the blade template to render the content, so you can make full use of the blade template engine when building the message HTML:

/**
* Build the message.
*
* @return $this
*/
Public Function Build ()
{
return $this->view (' emails.orders.shipped ');
}
Note: You can create a resources/views/emails directory to store all mail templates, and, of course, you can put mail templates in any other location in the Resources/views directory.
Plain text messages

If you want to define a plain text version of the message, you can use the text method. As with the view method, the text method receives a template name for rendering the content of the message, and you can define either plain text messages or HTML messages:

/**
* Build the message.
*
* @return $this
*/
Public Function Build ()
{
return $this->view (' emails.orders.shipped ')
->text (' Emails.orders.shipped_plain ');
}
View data

Through public properties

Typically, we need to pass some data to the HTML view of the rendered message to be used. There are two ways to pass data to a view, the first of which is that the public property of a mailing class is automatically available in the view, for example, we pass the data to the constructor of a mailing class and set the data to the public properties of the class:

<?php

namespace App\mail;

Use App\order;
Use illuminate\bus\queueable;
Use illuminate\mail\mailable;
Use Illuminate\queue\serializesmodels;

Class OrderShipped extends Mailable
{
Use queueable, serializesmodels;

/**
* The order instance.
*
* @var Order
*/
Public $order;

/**
* Create a new message instance.
*
* @return void
*/
Public Function __construct (order $order)
{
$this->order = $order;
}

/**
* Build the message.
*
* @return $this
*/
Public Function Build ()
{
return $this->view (' emails.orders.shipped ');
}
}
After the data is set to the public properties, it will automatically take effect in the view, so you can access them as you would access other data in the blade Template:

<div>
Price: {{{$order->price}}
</div>
By using the With method

If you want to customize the format of the message data before it is sent to the template, you can manually pass the data to the view through the With method. In general, you still need to pass the data through the constructor of the Mail class, but this time you need to set the data to protected or private so that the data does not automatically take effect in the view. Then, when you call the With method, you pass the data array to the method so that the data takes effect in the view template:

<?php

namespace App\mail;

Use App\order;
Use illuminate\bus\queueable;
Use illuminate\mail\mailable;
Use Illuminate\queue\serializesmodels;

Class OrderShipped extends Mailable
{
Use queueable, serializesmodels;

/**
* The order instance.
*
* @var Order
*/
protected $order;

/**
* Create a new message instance.
*
* @return void
*/
Public Function __construct (order $order)
{
$this->order = $order;
}

/**
* Build the message.
*
* @return $this
*/
Public Function Build ()
{
return $this->view (' emails.orders.shipped ')
->with ([
' Ordername ' => $this->order->name,
' Orderprice ' => $this->order->price,
]);
}
}
After the data is passed to the view through the with method, it will automatically take effect in the view, so you can also access the data passed along as you would access other data in the blade Template:

<div>
Price: {{{$orderPrice}}}
</div>
Attachment

To add an attachment to a message, you can use the Attach method in the build method of the mailing class. The Attach method receives the full file path as the first parameter:

/**
* Build the message.
*
* @return $this
*/
Public Function Build ()
{
return $this->view (' emails.orders.shipped ')
->attach ('/path/to/file ');
}
When attaching files to a message, you can also specify a file display name or MIME type by passing an array as the second argument to the Attach method:

/**
* Build the message.
*
* @return $this
*/
Public Function Build ()
{
return $this->view (' emails.orders.shipped ')
->attach ('/path/to/file ', [
' As ' => ' name.pdf ',
' MIME ' => ' application/pdf ',
]);
}
Raw Data attachment

The Attachdata method can be used to add a native byte string as an attachment. You can use this method if you want to generate a PDF in memory and add it to the message as an attachment without saving it to disk. The Attachdata method receives the data bytes as the first argument, the file name as the second argument, and the optional array as the third argument:

/**
* Build the message.
*
* @return $this
*/
Public Function Build ()
{
return $this->view (' emails.orders.shipped ')
->attachdata ($this->pdf, ' name.pdf ', [
' MIME ' => ' application/pdf ',
]);
}
Inline attachment

Nested inline pictures are usually cumbersome in the mail, and for this reason, Laravel provides a convenient way to attach pictures to the mail and get the appropriate CID, embed inline pictures, and use the Embed method on the $message variable in the message view. Laravel inject the $message variable into all mail views and make it automatically valid, so you don't have to worry about how to manually pass the variable into the view:

<body>
This is the image:

embed ($pathToFile)}} ' >
</body>
Embed native data attachments

If you already have a raw data string that you want to embed in your mail template, you can use the Embeddata method on the $message variable:

<body>
This is the image from raw data:

embeddata ($data, $name)}}" >
</body>
4, Send mail
To send a message, you can use the to method on the mail façade. The to method receives a mailbox address, user instance, or user collection as a parameter. If you pass a collection of objects or objects, messages automatically use their email and name properties when you set up mail recipients, so make sure that they are valid on the appropriate class. After you specify a good recipient, pass an instance of the mailing class to the Send method:

<?php

namespace App\http\controllers;

Use App\order;
Use app\mail\ordershipped;
Use Illuminate\http\request;
Use Illuminate\support\facades\mail;
Use App\http\controllers\controller;

Class Ordercontroller extends Controller
{
/**
* Ship the given order.
*
* @param Request $request
* @param int $orderId
* @return Response
*/
Public Function ship (Request $request, $orderId)
{
$order = Order::findorfail ($orderId);

Ship order ...

Mail::to ($request->user ())->send (new ordershipped ($order));
}
}
When sending mail messages, you can set "to", "CC", and "Bcc" in a single method chain call, not just to the recipient:

Mail::to ($request->user ())
->CC ($moreUsers)
->BCC ($evenMoreUsers)
->send (New ordershipped ($order));
message queues

Mail message queues

Because sending mail messages can significantly extend the response time of applications, many developers choose to send mail to the queue in the background, and Laravel can use the built-in unified queuing API to do this. To put a mail message in a queue, you can use the queue method on the mail façade after the recipient of the message is specified:

Mail::to ($request->user ())
->CC ($moreUsers)
->BCC ($evenMoreUsers)
->queue (New ordershipped ($order));
This method automatically pushes the mail task to the queue for sending in the background. Of course, you need to configure the queue before using this feature.

Delay Message Queuing

You can use the later method if you want to delay sending messages that have been placed in the queue. As the first parameter, the later method receives a DateTime instance to indicate when the message was sent:

$when = Carbon\carbon::now ()->addminutes (10);

Mail::to ($request->user ())
->CC ($moreUsers)
->BCC ($evenMoreUsers)
->later ($when, New ordershipped ($order));
Push into a specified queue

Because all of the available mailing classes generated through the Make:mail command use illuminate\bus\queueabletrait, you can invoke the Onqueue and OnConnection methods on the mailing class instance. To specify the connection and queue name for the message:

$message = (new ordershipped ($order))
->onconnection (' Sqs ')
->onqueue (' emails ');

Mail::to ($request->user ())
->CC ($moreUsers)
->BCC ($evenMoreUsers)
->queue ($message);
5. Mail & Local Development
When developing a local environment to send a mail application, you may not want to actually send a message to a valid email address, but just want to do the test. To do this, Laravel provides several ways to "prohibit" the actual sending of messages.

Log Drive

One solution is to use log mail drivers for local development. The driver writes all the message information to the log file for viewing, and wants to know more about the application configuration information for each environment and view the configuration document.

General configuration

Another solution provided by Laravel is to set up common recipients for all messages sent by the framework, so that all application-generated messages will be sent to the specified address instead of the actual address specified by the message. This can be accomplished by setting the To option in the configuration file config/mail.php:

' To ' => [
' Address ' => ' example@example.com ',
' Name ' => ' Example '
],
Mailtrap

Finally, you can use the Mailtrap service and SMTP driver to send message information to the "virtual" mailbox, which allows you to view the final message in the MAILTRAP Message Viewer.

6. Events
Laravel triggers an event before sending a mail message, remembering that the event is triggered when the message is sent, rather than being pushed to the queue, and you can register the corresponding event listener in Eventserviceprovider:

/**
* The event listener mappings for the application.
*
* @var Array
*/
protected $listen = [
' Illuminate\mail\events\messagesending ' => [
' App\listeners\logsentmessage ',
],
];

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.