Sending an email is one of the most important additions to any system; be it Transactional emails or sending newsletter emails. In recent surveys, 64% of small businesses use emails to reach customers. This makes it necessary to send emails to customers in order to engage your customers and also build a loyal customer base.
Laravel provides a clean and easy way to send emails without any hassle and difficulties using the Mailable Class.
In this article, I am going to show you how to easily send emails in Laravel and how to create email templates using markdown
What you need to know about Laravel Mail
If you want to send emails from your Laravel application, you need to know about the Laravel Mail API. This simple API is built on top of the popular Swiftmailer library. You can configure it to use SMTP , Mailgun , Postmark , Amazon SES , or Sendmail. You can also use the simple API to send emails directly from your PHP code. Laravel provides multiple mail drivers for sending emails making it easy to send emails using any integration of your liking.
The Laravel Mail API makes it easy to send beautiful email templates. You can create a Mailable class and a public function build() that returns your email template.
It’s easy to get started with Laravel Mail. Just configure your SMTP settings and you’re ready to go!
How do you send Emails in Laravel?
To send an email message in Laravel, you can follow the following steps
Step 1: Install Laravel
You can create a new Laravel project using the laravel new command
laravel new test
Step 2: Create a Mailable Class
You can use the make:mail artisan command in Laravel. This will scaffold a Mailable class which has a build() function where your mail logic will be added.
You can specify the email subject , and the content of the email such as images , attachments, and reply to address among others.
php artisan make:mail OrderMail
This command will create a Mailable Class in the app/Mail Folder
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class OrderMail extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->markdown('emails.orders');
}
}
Mail Example using Markdown Template
One of the key benefits of laravel is that it has markdown support. You can create an email template using markdown. This allows you to have a boilerplate view of the email which you can customise to your liking or use as is.
You can modify the make:mail command and add a flag to specify which markdown will be used by your Mailable Class. The markdown template is a blade file that is placed in the “emails” directory.
php artisan make:mail OrderMail --markdown=emails.orders
This creates a default markdown blade file in the resources/views/emails folder
@component('mail::message')
# Introduction
The body of your message.
@component('mail::button', ['url' => ''])
Button Text
@endcomponent
Thanks,<br>
{{ config('app.name') }}
@endcomponent
Using a simple scenario of an order mail, you can pass some default data to the markdown through the with() command in the Mailable Class. You could use the constructor to receive data from other classes.
You can update the logic of the Mailable class
<?php
namespace App\Mail;
use App\Models\Orders;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\URL;
class OrderMail extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* @return void
*/
public $order, $user;
public function __construct(Orders $order, User $user)
{
$this->user = $user;
$this->order = $order;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->markdown('emails.orders')
->subject('Your Order is being Processed')
->with([
'order' => $this->order,
'customer' => $this->user,
'order_url' => URL::route('orders.show', $this->order->id)
]);
}
}
The next step is to add content to the markdown blade template
@component('mail::message')
Hello {{$customer->name}},
Your Order No.{{$order->id}} has been placed successfully and is now being processed
You can view your order details using the link below.
@component('mail::button', ['url' => $order_url])
View Order
@endcomponent
Regards,<br>
{{ config('app.name') }}
@endcomponent
If you want to customize the Laravel Mail Components, you can publish the assets and change them to your liking using this command
php artisan vendor:publish --tag=laravel-mail
Step 3: Sending email in Laravel
Once you have the email template set, it is now time to send an email. You can use the Mail Facade to send an email. It comes with a lot of methods but the most important is the to() method. This method defines where the email will be sent. You can pass a user’s email as a parameter and Laravel will send the email to the email specified.
The next important method is the send() method. This method allows us to specify a Mailable message Instance. This is where you specify the Mailable class you had created earlier.
use Illuminate\Support\Facades\Mail;
Mail::to(request()->user())->send(new MailableClass);
You can update the Facade to include your Mailable Class
use Illuminate\Support\Facades\Mail;
$user = User::find($id)?? auth()->user();
$order = Orders::find($id);
Mail::to($user->email)->send(new OrderMail($order, $user));
Emails can be queued and sent in the background making your application even faster.
Before sending an email,you first need to update the mail configurations.
You can set the default details in the env file.
MAIL_MAILER=smtp
MAIL_HOST=mailhog
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"
Once you have set the mail configurations, you can now start sending emails from your Laravel Application.
Step 4: Testing emails in Laravel
Laravel makes it easy to test emails using either the laravel log file ,mailhog or Mailtrap as third-party integration. These services provide a fake SMTP server from where you can test and verify that your emails are correctly formatted.
All you need to do is change the mail configurations in the env file and use the credentials of any fake SMTP server.
Using Mailtrap for instance, you can visually see how the email is formatted
Which third-party email sending providers are supported in Laravel?
Laravel supports several third-party email sending providers, including Mailgun, Postmark, Amazon SES, and SendGrid. Each provider has its own strengths and weaknesses, so it’s important to choose the one that best suits your needs.
If you prefer using your own SMTP server , ensure that your server’s SMTP port is not blocked. Most VPS services such as Digital Ocean block port 25(SMTP) making it hard to send and receive emails on your server.
Other services such as Contabo and Kamatera, however, do not block port 25 making it easy to host your own mail server.
If you prefer hosting your own mail server as opposed to using third-party email service providers, then you can read this article.
It is good to note that hosting your own mail server comes with its fair share of cons such as emails may be delivered to the spam folder. This is because your mail server IP is still new among other email SMTP servers and it will require you to warm up your IP so that it gains a good reputation among other servers.
This is why most people prefer using third-party email service providers so that you concentrate more on what matters.
Why Use Laravel to Send Emails?
One of the great features of Laravel is its inbuilt mail system. This makes it easy to send emails from your application without having to set up a separate mail server. Through its robust Mail API, you can connect to any Email service provider and have your emails sent with ease.
Send Emails in Laravel using Gmail’s SMTP Server
Most people prefer using their default Gmail account as an SMTP server for their Laravel Application because it is free. In this part, I will show you how to use Gmail as an SMTP server for sending your Laravel Emails.
Configure Google Account
You first need to configure some security settings in your Gmail account. To do so, log in to your Gmail account and select “Manage your Google Account” from your profile.
You then need to activate 2 step verification
Before 2-step Verification is turned on
Once you have activated 2 step verification , you will have access to the App password section
After 2-step Verification is turned on
Click on the App passwords section and create a new password for your Laravel Mail Application
Choose the Mail App and the device Custom
Update Mail Configurations
Once you have generated your app password, you can update your mail configurations in the env file to use Gmail’s SMTP configurations
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_USERNAME=youremail@gmail.com
MAIL_PASSWORD=generated password
MAIL_ENCRYPTION=ssl
MAIL_FROM_ADDRESS=youremail@gmail.com
MAIL_FROM_NAME="${APP_NAME}"
Once you have set the configurations you are set to send emails using Gmail for free. Do bear in mind that Gmail allows only 500 emails per day so if your application will be sending a lot of emails, you might consider other services.
Conclusion
Sending Emails in Laravel is easy and is essential in any production-ready application. Through emails, you can engage customers and also automate some of the tasks that are necessary for a fully functioning application. In this article, we have covered how to set up a Simple Mail Implementation in Laravel and how to configure Gmail’s SMTP server so that we can use it with our Laravel application.
There are multiple ways you can further send emails in Laravel. One way is scheduling them using Laravel Scheduler. I hope this article was informative and I hope you enjoyed reading it.
If you enjoyed this article, you'd love the Free Laravel Guide I prepared for you. Be sure to get your guide today.
Thank you for reading.
The post Laravel Mail: How to Send Emails Easily in Laravel appeared first on Ian Kumu's Blog.
Top comments (0)