Laravel basic tutorial-email overview
Laravel builds a clean and concise mail API based on the popular SwiftMailer class library. Laravel provides drivers to support SMTP, Mandrill, SparkPost, Amazon SES, and PHP mail and sendmail methods. This allows you to quickly start building the function of sending emails through local or cloud services.
Driver prerequisites
API-based drivers such as Mailgun and Mandrill are generally simpler and faster than SMTP services. All the API drivers must introduce the Guzzle HTTP class library. you can install it by adding the following content to the composer. json file:
"guzzlehttp/guzzle": "~5.3|~6.0"
Mailgun driver
If you use the Mailgun driver, first install Guzzle, and then set the driver option of the config/mail. php configuration file to mailgun. Then, make sure that your config/services. php configuration file contains the following options:
'mailgun' => [ 'domain' => 'your-mailgun-domain', 'secret' => 'your-mailgun-key',],
Mandrill driver
If you use the Mandrill driver, first install Guzzle, and then set the driver option of the config/mail. php configuration file to mandrill. Then, make sure that your config/services. php configuration file contains the following options:
'mandrill' => [ 'secret' => 'your-mandrill-key',],
SparkPost driver
If you use the SparkPost driver, first install Guzzle and set the driver option in your config/mail. php configuration file to sparkpost. Then, make sure that your config/services. php configuration file contains the following options:
'sparkpost' => [ 'secret' => 'your-sparkpost-key',],
SES Driver
If you use the Amazon SES driver, you need to introduce the Amazon aws sdk in PHP. You can introduce and install it in the composer. json file:
"aws/aws-sdk-php": "~3.0"
Set the driver option of your config/mail. php configuration file to ses. Then, make sure that your config/services. php configuration file contains the following options:
'ses' => [ 'key' => 'your-ses-key', 'secret' => 'your-ses-secret', 'region' => 'ses-region', //e.g. us-east-1],
Send email
Laravel allows you to use views to store your mail information. For example, you can create an emails directory under the resources/views directory to manage your mail view:
You need to use the send method of the Mail mask to send an email. The send method receives three parameters. The first parameter should be the view name. The second parameter should be an array consisting of data transmitted to the view. Finally, it is a Closure callback function, which will receive a message instance, which allows you to freely configure the recipient, subject, and other mail information:
$user], function ($m) use ($user) { $m->from('hello@app.com', 'Your Application'); $m->to($user->email, $user->name)->subject('Your Reminder!'); }); }}
Because the user key is passed to the array in the preceding example, we can use the user name in our mail view:
name; ?>
Note: A $ message variable is automatically passed to the Mail view and allows inline attachments. Therefore, you should avoid manually passing the message variable to the view.
Construct a Message
As we mentioned above, the third parameter passed to the send method is a Closure, which allows you to set various options for mail information. With closures, you can specify other attributes of information, such as rewrite and password copy:
Mail::send('emails.welcome', $data, function ($message) { $message->from('us@example.com', 'Laravel'); $message->to('foo@example.com')->cc('bar@example.com');});
All available methods for constructing an instance with $ message are listed here:
$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 = []);// Attach a file from a raw $data string...$message->attachData($data, $name, array $options = []);// Get the underlying SwiftMailer message instance...$message->getSwiftMessage();
Note: The message instance inherits from the SwiftMailer information class and is passed to the Mail: send closure. This allows you to access all methods of the SwiftMailer information class.
Plain text mail
By default, the send method assumes that the view passed to it contains HTML. However, you can pass an array to the first parameter of the send method. you can specify a plain text view to merge the HTML view:
Mail::send(['html.view', 'text.view'], $data, $callback);
Or you can pass only one plain text mail, you need to specify the array key as text:
Mail::send(['text' => 'view'], $data, $callback);
Original string email
You can use the raw method to directly send the original string mail:
Mail::raw('Text to e-mail', function ($message){ //});
Attachment
You can use the attach method of the $ message object passed to the closure to add attachments to the email. The attach method receives a complete file path as the first parameter:
Mail::send('emails.welcome', $data, function ($message) { // $message->attach($pathToFile); });
When you add an email attachment, you may also need to specify the name or MIME type displayed in the attachment. You can pass an array to the attach method as the second parameter:
$message->attach($pathToFile, ['as' => $display, 'mime' => $mime]);
The attachData method can be used to add an original byte string as an attachment. For example, you may need to use this method to directly add the PDF generated in the memory to the attachment, instead of storing it on the disk:
$message->attachData($pdf, 'invoice.pdf');$message->attachData($pdf, 'invoice.pdf', ['mime' => $mime]);
Inline attachment
Embed an image in the mail View
Inline images in emails are often cumbersome. However, laravel provides a convenient way to append an image to your email and retrieve the appropriate CID. You need to use the embed method of the $ message variable in the mail view. You should remember that Laravel will automatically create a $ message variable and pass it to your mail view:
Here is an image: embed($pathToFile); ?>"
Embed original data into the view
If you want to embed a raw data into the mail information, you can use the embedData method of the $ message variable:
Here is an image from raw data: embedData($data, $name); ?>"
Email queue
Message Queue
Because sending emails consumes a lot of resources, this will affect the application response time. Therefore, many developers choose to use queues for asynchronous mail sending. Laravel uses a unified queue interface to make these operations very simple. You need to use the queue method of the Mail mask to queue the Mail:
Mail::queue('emails.welcome', $data, function ($message) { // });
This method automatically adds the task for sending emails to the queue, and the task is automatically executed in the background. Of course, you need to configure the queue first.
Delayed Message Queue
If you want to delay the sending queue of the executed mail. You need to use the later method. You need to transmit the number of seconds that you want to delay execution in the first parameter of the method:
Mail::later(5, 'emails.welcome', $data, function ($message) { //});
Add to specified queue
If you want to add a mail task to a specified queue, you need to use the queueOn and lateon methods:
Mail::queueOn('queue-name', 'emails.welcome', $data, function ($message) { // });Mail::laterOn('queue-name', 5, 'emails.welcome', $data, function ($message) { // });
Email & Local Development
When developing an email sending service, you may not want to actually send an email. You only need to simulate the test. Laravel provides multiple ways to disable real email sending.
Log Driver
One solution is to use the log Mail driver during local development. This driver will write all the mail information into the log file.
Common emails
Another solution is to set up a common mail to receive mails sent by all applications. This method will send all emails generated by the application to this address. You can configure the to option of the config/mail. php file:
'to' => [ 'address' => 'dev@domain.com', 'name' => 'Dev Example'],
Mailtrap
Finally, you can use services like Mailtrap and smtp driver to send your emails to a virtual mailbox. you can also view the emails through the real mail client. This allows you to see the display effect of real emails in Mailtrap.
Event
Laravel triggers an event before sending an email. You should note that it triggers an event before the mail is sent, rather than when it is added to the queue. You can register an event listener in EventServiceProvider:
/** * The event listener mappings for the application. * * @var array */ protected $listen = [ 'Illuminate\Mail\Events\MessageSending' => [ 'App\Listeners\LogSentMessage', ], ];