Laravel provides a clean API over the popular SwiftMailer library with drivers for SMTP, PHP's mail
, sendmail
and more. For this example, we'll be sending a Laravel email with SendGrid using the SMTP Driver. For more information, check out the docs for Laravel's Mail interface.
Laravel 5.5 LTS uses Mailable classes. Mailables in Laravel abstracts building emails with a mailable class. Mailables are responsible for collating data and passing them to views.
Check your .env
file and configure these variables:
_10MAIL_MAILER=smtp_10# MAIL_DRIVER=smtp # for laravel < 7_10MAIL_HOST=smtp.sendgrid.net_10MAIL_PORT=587_10MAIL_USERNAME=apikey_10MAIL_PASSWORD=sendgrid_api_key_10MAIL_ENCRYPTION=tls_10MAIL_FROM_NAME="John Smith"_10MAIL_FROM_ADDRESS=from@example.com
Set the MAIL_USERNAME
field to "apikey" to inform SendGrid that you're using an API key.
The MAIL_FROM_NAME
field requires double quotes because there is a space in the string.
You can send 100 messages per SMTP connection
at a time, and open up to 10 concurrent connections
from a single server at a time.
Categories and Unique Arguments will be stored as a "Not PII" field and may be used for counting or other operations as SendGrid runs its systems. These fields generally cannot be redacted or removed. You should take care not to place PII in this field. SendGrid does not treat this data as PII, and its value may be visible to SendGrid employees, stored long-term, and may continue to be stored after you've left SendGrid's platform.
Next you need to create a Mailable class, Laravel's CLI tool called Artisan makes that a simple feat. Open CLI, go to the project directory and type:
php artisan make:mail TestEmail
This command will create a new file under app/Mail/TestEmail.php
and it should look something like this:
_35<?php_35_35namespace App\Mail;_35_35use Illuminate\Bus\Queueable;_35use Illuminate\Mail\Mailable;_35use Illuminate\Queue\SerializesModels;_35use Illuminate\Contracts\Queue\ShouldQueue;_35_35class TestEmail extends Mailable_35{_35 use Queueable, SerializesModels;_35_35 public $data;_35_35 public function __construct($data)_35 {_35 $this->data = $data;_35 }_35_35 public function build()_35 {_35 $address = 'janeexampexample@example.com';_35 $subject = 'This is a demo!';_35 $name = 'Jane Doe';_35_35 return $this->view('emails.test')_35 ->from($address, $name)_35 ->cc($address, $name)_35 ->bcc($address, $name)_35 ->replyTo($address, $name)_35 ->subject($subject)_35 ->with([ 'test_message' => $this->data['message'] ]);_35 }_35}
In Laravel Views
are used as 'templates' when sending an email. Let's create a file under app/resources/views/emails/test.blade.php
and insert this code:
_10<!DOCTYPE html>_10<html lang="en-US">_10 <head>_10 <meta charset="utf-8" />_10 </head>_10 <body>_10 <h2>Test Email</h2>_10 <p>{{ $test_message }}</p>_10 </body>_10</html>
Now that we have our Mailable Class created, all we need to do is run this code to use Laravel to send email:
_10<?php_10 use App\Mail\TestEmail;_10_10 $data = ['message' => 'This is a test!'];_10_10 Mail::to('john@example.com')->send(new TestEmail($data));
Categories in SendGrid allow you to split your statistics into sections.
Another useful tool is event notifications. If you want to complete the feedback loop for your product you can pass identifiers as a header which relate to a record in your database which you can then parse the notifications against that record to track deliveries/opens/clicks/bounces.
The withSwiftMessage
method of the Mailable
base class allows you to register the callback that is invoked with the raw SwiftMailer message instance before sending the message. This knowledge allows you to customize the message before delivery. To customize your message, use something similar to this:
_65<?php_65_65namespace App\Mail;_65_65use Illuminate\Bus\Queueable;_65use Illuminate\Mail\Mailable;_65use Illuminate\Queue\SerializesModels;_65use Illuminate\Contracts\Queue\ShouldQueue;_65_65class TestEmail extends Mailable_65{_65 use Queueable, SerializesModels;_65_65 public $data;_65_65 public function __construct($data)_65 {_65 $this->data = $data;_65 }_65_65 public function build()_65 {_65 $address = 'janeexampexample@example.com';_65 $subject = 'This is a demo!';_65 $name = 'Jane Doe';_65_65 $headerData = [_65 'category' => 'category',_65 'unique_args' => [_65 'variable_1' => 'abc'_65 ]_65 ];_65_65 $header = $this->asString($headerData);_65_65 $this->withSwiftMessage(function ($message) use ($header) {_65 $message->getHeaders()_65 ->addTextHeader('X-SMTPAPI', $header);_65 });_65_65 return $this->view('emails.test')_65 ->from($address, $name)_65 ->cc($address, $name)_65 ->bcc($address, $name)_65 ->replyTo($address, $name)_65 ->subject($subject)_65 ->with([ 'data' => $this->data ]);_65 }_65_65 private function asJSON($data)_65 {_65 $json = json_encode($data);_65 $json = preg_replace('/(["\]}])([,:])(["\[{])/', '$1$2 $3', $json);_65_65 return $json;_65 }_65_65_65 private function asString($data)_65 {_65 $json = $this->asJSON($data);_65_65 return wordwrap($json, 76, "\n ");_65 }_65}