Laravel Email Notifications for Sending Emails: Mastering Mail Integration
Working with mail is very common nowadays in most of the business applications. Email works as the primary communication channel with the users and customers most of the times. So it is needless to say how important it is to learn about an efficient mail management in any framework or environment you work in. Laravel provides a strong platform and beautiful structures to manage mail functionality. In the framework, it doesnt take much time to integrate this for your application. Lets see a quick some examples, how we can integrate email functionality in different ways.
Laravel Mail Magic: Sending Effortless Email Notifications in Minutes
Lets install a fresh new application:
composer create-project --prefer-dist laravel/laravel laravel-mail-example
Now you need configure the .env, with proper smtp informations:
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=your_mailtrap_username
MAIL_PASSWORD=your_mailtrap_password
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=example@example.com
MAIL_FROM_NAME="${APP_NAME}"
You need to collect these data from your mail provider. You can also test mail first with some popular mail service provider like Mailtrap. After creating a account, if you go to your dummy inbox, you will find these details under laravel settings.
- Lets setup controller
Lets imagine a scenario, we have customers in our application and we want to give a mail notification when a user pays and invoice is generated.
Now to do this, we can create our controller method like this:
<?php
namespace App\Http\Controllers;
use App\Models\User;
use App\Models\Invoice;
use App\Notifications\InvoicePaid;
use Illuminate\Http\Request;
class InvoiceController extends Controller
{
public function pay($invoiceId)
{
$invoice = Invoice::findOrFail($invoiceId);
// Logic to pay the invoice
// ...
// Notify the user
$user = User::findOrFail($invoice->user_id);
$user->notify(new InvoicePaid($invoice));
return response()->json(['message' => 'Invoice paid and notification sent!']);
}
}
You see, after building all the logics, we are giving user a notification with InvoicePaid. We havent created the class yet. Lets do this.
- Create the notification class
Lets create a new notification class with this command:
php artisan make:notification InvoicePaid
And define the notification logic like below:
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class InvoicePaid extends Notification
{
use Queueable;
protected $invoice;
/**
* Create a new notification instance.
*
* @return void
*/
public function __construct($invoice)
{
$this->invoice = $invoice;
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
* @return array
*/
public function via($notifiable)
{
return ['mail'];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->subject('Your Invoice Has Been Paid') // Set the subject here
->line('Your invoice has been paid.')
->action('View Invoice', url('/invoices/'.$this->invoice->id))
->line('Thank you for using our application!');
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
* @return array
*/
public function toArray($notifiable)
{
return [
'invoice_id' => $this->invoice->id,
];
}
}
First, in the construct method, we are receiving and assigning the required value of $invoice.
With the via method, we are assigning the notification channel. You can also provide multiple channels like ['mail', ‘database’].
The toMail method is working the real job here. With the subject, we are setting the subject for the mail.
Then in the body, we are giving first a text line, then the action will generate a button and it’s text is in first parameter and link is provided with url in second parameter. Then another text line for wrapping up the mail.
- Now test the notification
Now run the application and trigger the controller method by using a route. This should send a notification email to user’s email address
php artisan serve
Email Integrations in Laravel: Alternative Methods
For mail integration, Laravel has provided various ways that we can use according to our convenience. For example, we can use notification class, or the mailable class, or raw email etc. We have seen how to integrate a notification for users to send as email, now we will explore more other ways to enrich our options.
- Using raw email
Among all the ways, this one is simplest to start and integrate. Here is an example:
use Illuminate\Support\Facades\Mail;
Route::get('/send-raw-mail', function () {
$data = 'This is a raw email body.';
Mail::raw($data, function ($message) {
$message->to('recipient@example.com')
->subject('Raw Email Example');
});
return 'Raw email sent successfully!';
});
You can see, the Mail facade has raw method, which takes two arguments. First one is data or the message body, and second one is a callback function, where we can set mail recipient and subject.
- Using Mailable Classes
This one is a recommended approach in laravel framework because we have to follow a structured approach to integrate in this way.
Lets start with adding the route first in web.php:
use App\Mail\WelcomeMail;
use Illuminate\Support\Facades\Mail;
Route::get('/send-welcome-mail', function () {
$details = [
'title' => 'Welcome to My Application',
'body' => 'This is a welcome email.'
];
Mail::to('recipient@example.com')->send(new WelcomeMail($details));
return 'Welcome email sent successfully!';
});
So here you can see, we are providing title and body or message of email in $details array, which is passed to a mailable class WelcomeMail. Of course this is a custom class we are going to create now. You will have to pass this class in the send method of Mail facade and in to method we are defining the recipient.
Now lets create the WelcomeMail class:
php artisan make:mail WelcomeMail
This command will create a new class under app/Mail/WelcomeMail.php. Lets modify the file as our requirement:
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class WelcomeMail extends Mailable
{
use Queueable, SerializesModels;
public $details;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct($details)
{
$this->details = $details;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->subject('Welcome to My Application')
->view('emails.welcome');
}
}
Here the build function is responsible for building the architecture of mail
We are defining subject with the subject method and in view method, we have to pass a view containing the message body of email.
Let create the view under resources/views/emails/welcome.blade.php:
<!DOCTYPE html>
<html>
<head>
<title>Welcome Email</title>
</head>
<body>
<h1>{{ $details['title'] }}</h1>
<p>{{ $details['body'] }}</p>
</body>
</html>
- Test now
Done, now you can test the mail functionality by triggering the corresponding route "/send-welcome-mail".
Php artisan serve
Beyond Mail! Sending Attachments With Mails
Alongside sending mails, you also need work with sending pdfs or attachments to you mails. In such case, you dont have to worry about doing something complex or make custom logic to send those attachments. Laravel also provides support for this too. Lets see a quick guide, how we can send mails with attachments with Laravel.
- Sending attachments using raw email
We have seen how to send raw emails very quick with no view or classes required. Just Mail facade can help to send quick email. Now, to send attachment, we can use attach method in the callback function like this:
use Illuminate\Support\Facades\Mail;
Mail::raw('This is the email body', function ($message) {
$message->to('recipient@example.com')
->subject('Subject of the Email')
->attach(public_path('path/to/your.pdf'));
});
- Using mailable class
We have already seen, you can use mailable class to send email. Here, you can also use attach method too for sending files with email:
php artisan make:mail YourMailable
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class YourMailable extends Mailable
{
use Queueable, SerializesModels;
public $data;
public function __construct($data)
{
$this->data = $data;
}
public function build()
{
return $this->view('emails.your_template')
->attach(public_path('path/to/your.pdf'))
->with([
'data' => $this->data,
]);
}
}
- Using a notification
Yes, the notifications are also can be used to attach files with emails. Here is the example with the same attach method:
php artisan make:notification YourNotification
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class YourNotification extends Notification
{
use Queueable;
public $data;
public function __construct($data)
{
$this->data = $data;
}
public function via($notifiable)
{
return ['mail'];
}
public function toMail($notifiable)
{
return (new MailMessage)
->subject('Subject of the Email')
->view('emails.your_template', ['data' => $this->data])
->attach(public_path('path/to/your.pdf'));
}
}
Note: You need to define the correct path of you file location in public directory. Also you have to keep the file in that location otherwise it cant send the attachment correctly.
Summary
Nowadays, almost all web applications use sending automatic mail and attachments more often. Email has become the primary channel for most of the business communication. Understanding efficient mail management is crucial and Laravel provides a robust platform for the purpose. As we embark on our journey with laravel's email capabilities, these are some easy steps that we can follow to produce a quick notification or email. We have learnt about how to create a basic notification using laravel's available commands and notify users. Then we have also learnt about Mail class or using Mailable class to send emails. Also, Sending attachments with email is very quick and easy for all of these approaches.
You can see Laravel already provides a strong foundation for building a quick template and writing least amount of code possible. Learning alternative approaches for mail functionalities will help you work under different conditions. You can go for any option which works best for your requirement and circumstance.
I hope this article helped you. Let me know your thoughts in the comments.
Wish you a happy day.
Comments