Laravel – Mailing

Sometimes applications needs functionality to send users a message in the form of an e-mail. Most often, this happens when the user is registering or when password must be reseted. However, the sending of emails is not limited to certain behaviors. In code you can prepare a trigger when various actions are performed. For example, when an error occurs in the application, administrators will be notified. The user will be assigned to a resource and will be notified by email. As you can see, the communication needs between the system and the user can be adapted according to your business needs.

Customizing layout

Laravel allows you to completely customize the look and content of your email. An email can consist of simple text content. But there’s nothing stopping you from preparing an e-mail layout that will be reused in all messages, so that you can include all the necessary information about the application, such as which application the e-mail is coming from or which company is responsible for it. Layouts are prepared using another Laravel feature known as Blade Templates. In the Blade view, we can use HTML and CSS elements. Alternatively, Markdown elements and predefined Laravel layouts can be used. 

php artisan vendor:publish --tag=laravel-notifications

Customizing message properties

The content of an email is only one part of it. Laravel also allows you to customize the time at which an email will be sent using a delay or job function to send it at a specific time.

$delay = now()->addMinutes(15);
 
$user->notify((new WishlistNotification($product))->delay($delay));

Multiple recipients can be assigned to an email, or in the case of multiple emails to different recipients, we can further divide them into chunks that will be sent at equal intervals so as not to overload the email system.

Notification::send(
    $users, new WishlistNotification($product)
);

It is also possible to attach attachments to e-mails, even those that are already in the application’s storage folder.

/**
 * Get the mail representation of the notification.
 */
public function toMail(object $notifiable): MailMessage
{
    return (new WishlistNotification)
                ->attach('coupon.pdf');
}

Automatic tests

Laravel provides a set of functions that allow us to perform unit tests on emails. We can use them to check various meta data, header data, content and even attachments. For manual testing, Laravel Sail provides a mailpit implementation or we can use external services such as mailtrap or sendgrid.