Laravel
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 an email to Aritic Mail using the SMTP Driver. For more information, check out the docs for Laravel’s Mail interface.
Laravel 5.5 LTS uses Mailable classes. Mailable in Laravel abstracts building emails with a mailable class. Mailable are responsible for collating data and passing them to views.
Before you begin
If .env
you need to find and configure these variables:
1 2 3 4 5 6 7 8 |
|
The
MAIL_FROM_NAME
field requires double quotes because there is a space in the string.
Creating a Mailable
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 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:
1 2 3 4 5 6 7 8 9 10 |
|
Sending an email
Now that we have our Mailable Class created, all we need to do is run this code:
1 2 3 4 5 6 |
|
Adding a category or custom field
Categories in Aritic Mail allow you to split your statistics into sections. For example, if you have a Whitelabeled service, you can split your statistics by the user login.
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
|