
Sending an email is one of the most common features that each and every web application offers. Some websites use their emailing feature to send newsletters, and some use it to collect feedback responses.
The PHP-powered websites use the Mail() php method to send emails. However, in this case, security is often compromised as it is not the most secure way to send/receive emails on the website.
To send emails in Laravel, the framework provides several advanced features to work with. It has different packages available in the market that makes the integration of emailing functionality effortlessly.
Why Use Laravel to Send Emails?
Laravel offers various tools to configure email in websites. You can check out some options below. :
- Laravel proposes using drivers for SMTP, Mailgun, SparkPost, Amazon SES, and sendmail
- Laravel provides options for queueing emails
- In Laravel, you can use Markdown support which is available in a few frameworks. It helps to create awesome templates like buttons or panels and much more
- You can attach files of different formats (JPEG, PDF), etc, using Laravel Templating system, which lets you use various templates and configure the view
Localization Methods to set desired languages for specific users.
Stop Wasting Time on Servers
Cloudways handle server management for you so you can focus on creating great apps and keeping your clients happy.
Installation of Laravel
For the purpose of this tutorial, I assume that you have a Laravel application installed on a web server.
To make sure that I don’t get distracted by server level issues, I have decided to install Laravel to a server using Cloudways managed platform because it takes care of server-level issues and offers a great stack of caches and database technology. You can try out Cloudways for free by signing up for an account.
What you need to know about Laravel Mail
There are many guides, tutorials available online related to Laravel Mail. You can also find some detailed examples on the official Laravel website.
Building Email in Laravel
Laravel provides a simple API for the popular SwiftMailer library with drivers for SMTP, Mailgun, Postmark, Amazon SES, and sendmail, allowing you to send emails quickly with your choice of structure.
Creating Mailable
In Laravel, each type of email sent by your application is represented as a “mailable” class. First, you need to create a mailable class with any name. Let’s paste the following command on the SSH terminal of Cloudways.
php artisan make:mail CloudHostingProduct
Once you execute the above-mentioned command, your mail class will be created with the name of CloudHostingProduct. So, it will create this file inside App\Mail\CloudHostingProduct.php.
The From Method
In the Form Method method, you will define the email address which you want to use.
*/ public function build() { return $this->from('[email protected]') ->view('emails.CloudHosting.Product); }
Global Mail Address
If your mail is the same across all our web applications so you can config first in config/mail.php file in Laravel by using the following code.
If you are using the same email address across the whole application, then you have to first configure it in the config/mail.php file. Just copy and paste the following code.
'from' => ['address' => '[email protected]', 'name' => 'App Name'],
Setup View for Laravel Mail
Within a mailable class’ build method, you may use the view method to specify which template should be used for mailing when rendering the email’s contents.
public function build() { return $this->view('emails.CloudHosting.Product); }
View Data
Want to pass some data to the view function that you can utilize when rendering the email’s HTML? There are two ways to make data available to your view.
First, any public property defined in your mailable class will automatically be available to the view. For example, you may pass data into your mailable class’ constructor and set that data to public properties defined on the class:
<?php namespace App\Mail; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; use Illuminate\Contracts\Queue\ShouldQueue; class SendMailable extends Mailable { use Queueable, SerializesModels; public $name; public function __construct($name) { $this->name = $name; } public function build() { return $this->view('emails.name'); } }
Once the data has been set to public property, it will automatically be available in your view.
Creating the Laravel Email Template
<div> Name: {{ $name }} </div>
Configuring the Routes
Create a route by pasting the following code in the web.php file.
Route::get('/send/email', '[email protected]');
Controller File
Now, create a controller file with any of your preferred name. For this tutorial, I will paste the following code in HomeController.
public function mail() { $name = 'Cloudways'; Mail::to('[email protected]')->send(new SendMailable($name)); return 'Email sent Successfully'; }
Configurations for Laravel Gmail SMTP
Setting up email in Laravel with Gmail SMTP is quite easy.. First of all, you need to configure basic settings. To carry out this step, Paste the following code in the .env file according to your settings.
MAIL_DRIVER=smtp MAIL_HOST=smtp.googlemail.com MAIL_PORT=465 MAIL_USERNAME=ENTER_YOUR_EMAIL_ADDRESS(GMAIL) MAIL_PASSWORD=ENTER_YOUR_GMAIL_PASSWORD MAIL_ENCRYPTION=ssl
In the above-mentioned settings, you can configure MAIL_DRIVER as SMTP, MAIL_HOST for Gmail as smtp.googlemail.com, MAIL_ PORT for Gmail as 465 and MAIL_ENCRYPTION method as SSL.
Since we are using Gmail SMTP with Laravel, we need to change some security settings on our Google account, to give access to less secure applications.
Setup Gmail Account
After successfully configuring the settings to your Laravel application, go to your Gmail account.
Once you are logged in your Gmail account, click on the Google account settings and check your security setting, as you have to use SMTP.
Now, write the following code to send an email in Laravel.
In Controller
Create a controller with any name you like and paste the following code in it.
public function mail() { $to_name = ‘RECEIVER_NAME’; $to_email = ‘RECEIVER_EMAIL_ADDRESS’; $data = array(‘name’=>”Cloudways (sender_name)”, “body” => “A test mail”); Mail::send(‘mail’, $data, function($message) use ($to_name, $to_email) { $message->to($to_email, $to_name) ->subject(Laravel Test Mail’); $message->from(‘SENDER_EMAIL_ADDRESS’,’Test Mail’); }); return 'Email sent Successfully'; }
View File
Now, create a Blade file with the name of mail.blade.php and paste the following code.
Hello <b>{{ $name }}</b>, <p>{{body}}</p>
Top 6 Emailing Tools for Laravel
There are a variety of email packages and sources available for Laravel. Let’s check out some of the most commonly used tools in Laravel to send emails.
- Mailtrap
- Mailgun
- Sendgrid
- Mandrill
- Swiftmailer
- Mailchimp
Integrate Mailtrap with Laravel
Mailtrap has a default server in Laravel, so you just have to type in your credentials there. Just install Laravel by using Cloudways Managed Hosting Platform and paste the following configurations in the .env file.
MAIL_DRIVER=smtp MAIL_HOST=smtp.mailtrap.io MAIL_PORT=2525 MAIL_USERNAME= //your username generated by Mailtrap MAIL_PASSWORD= // your password generated by Mailtrap [email protected] MAIL_FROM_NAME=Example
In most cases, the .env file configuration is enough. Alternatively, you can set your config/mail.php file to the following content (it is also available in the list of integrations in Mailtrap):
<?php return [ "driver" => "smtp", "host" => "smtp.mailtrap.io", "port" => 2525, "from" => array( "address" => "[email protected]", "name" => "Example" ), "username" => "1a2b3c4d5e6f7g" // your username, "password" => "1a2b3c4d5e6f7g" // your password, "sendmail" => "/usr/sbin/sendmail -bs" ];
Create Mailable Class For Mailtrap
Now, create a Mailable class by pasting the following command on SSH Terminal.
php artisan make:mail MailtrapExample
Next, you have to find it in the Mail directory in the app/Mail. You have a template, which contains basic functions so you can modify that template with the following code:
<?php namespace App\Mail; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; use Illuminate\Contracts\Queue\ShouldQueue; class MailtrapExample 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->from('[email protected]', 'Mailtrap') ->subject('Mailtrap Confirmation') ->markdown('mails.exmpl') ->with([ 'name' => 'New Mailtrap User', 'link' => 'https://mailtrap.io/inboxes' ]); }
Next, you have to create a message for this in the blade.php file. In this example, I have specified the mailable class in the mails.exmpl. Now you have to create a ‘mails’ directory with a blade template file ‘emailexample.blade.php’.
Routes
To create a route for mail, just paste the following code.
<?php use App\Mail\MailtrapExample; use Illuminate\Support\Facades\Mail; Route::get('/send-mail', function () { Mail::to('[email protected]')->send(new MailtrapExample()); return 'A message has been sent to Mailtrap!'; })
Integrate SendGrid with Laravel
Another popular tool for Laravel’s email is SendGrid. Let’s check out the following guidelines for sending an email with SendGrid in Laravel.
Mailables are responsible for collating data and passing them to ‘views’, just like Mailtrap. You can first check your application .env file for sending email configuration related to SendGrid.
MAIL_DRIVER=smtp MAIL_HOST=smtp.sendgrid.net MAIL_PORT=587 MAIL_USERNAME=sendgrid_username MAIL_PASSWORD=sendgrid_password MAIL_ENCRYPTION=tls MAIL_FROM_NAME="Pardeep Kumar" [email protected]
Create Mailable
Just like in Mailtrap, you can create a mailable class by pasting the following command on the SSH terminal.
php artisan make:mail TestEmail
This command will create a new file under app/Mail/TestEmail.php and it should look like this:
public function build() { $address = '[email protected]'; $subject = 'This is a demo!'; $name = 'Jane Doe'; return $this->view('emails.test') ->from($address, $name) ->cc($address, $name) ->bcc($address, $name) ->replyTo($address, $name) ->subject($subject) ->with([ 'test_message' => $this->data['message'] ]); }
Laravel Email View
Let’s create Laravel View for Email Templates when sending an email. Just paste the following code in your view file located in views/emails/test.blade.php.
<!DOCTYPE html> <html lang="en-US"> <head> <meta charset="utf-8"> </head> <body> <h2>Test Email</h2> <p>{{ $test_message }}</p> </body> </html>
Integrating Mailgun in Laravel
First of all, you have to sign up on Mailgun and create a free account. After creating your account, you can change your .env file settings by just changing Mail Driver to mailgun.
After successfully logging in, you will see the codes in different languages. Select the PHP code from there.
Laravel Config File
Add mailgun configuration in your application by pasting the following code in config/services.php.
'mailgun' => [ 'domain' => '', 'secret' => '', ],
Laravel Mailgun Routes
Let’s create routes for testing emails using Mailgun. Just copy the below-given code in your application web.php file.
Route::get('send_test_email', function(){ Mail::raw('Sending emails with Mailgun and Laravel !', function($message) { $message->to('[email protected]'); }); });
You may also want to include a subject line and possibly a sender email like so:
Route::get('send_test_email', function(){ Mail::raw('Sending emails with Mailgun and Laravel ', function($message) { $message->subject('Mailgun and Laravel '); $message->from('[email protected]_name.com', 'Website Name'); $message->to('[email protected]'); }); });
Integrating Mandrill in Laravel
First of all, you have to create an account on Mandrill and then have to install a guzzle for that. Just paste the following command in your application.
"guzzlehttp/guzzle": "~5.3|~6.0"
Then, you have to set up the application driver in your mail.php file. You must then copy the API key in the config/services.php.
'mandrill' => [ 'secret' => 'your-mandrill-key', ],
Sending Mandrill Email
Copy the method mentioned below for sending an email using Mandrill.
\Mail::send('welcome', [], function ($message){ $message->to('recipient_email_address')->subject('Cloudways - Testing mail'); });
Integrate Mailchimp in Laravel
To integrate Mailchimp in Laravel, you have to first create a free account on Mailchimp. After successfully logging in, create a List on the menu, then go to the Settings and copy your List ID which you will use in API. Open your .env file and paste the API key in there.
APP_ENV=local APP_DEBUG=true APP_KEY= DB_HOST=127.0.0.1 DB_DATABASE=learn DB_USERNAME=root DB_PASSWORD=root MAILCHIMP_API_KEY=API Key Here
Install Laravel Mailchimp Package
After successfully configuring the settings in the .env file, open your SSH terminal and paste the following command.
composer require skovmand/mailchimp-laravel
Laravel Config File
Now, set up your configuration file by pasting the following code in your config.php file.
return [ ...... $provides => [ Skovmand\Mailchimp\MailchimpServiceProvider::class, ], ..... ]
Laravel Routes
Now, set up your web application routes as shown below.
Route::get('manageMailC', '[email protected]'); Route::post('subs',['as'=>'sub','uses'=>'[email protected]']); Route::post('sendComp',['as'=>'sendComp','uses'=>'[email protected]']);
Laravel Controller
Now, create a controller with the name of MailchmpController.php
use Illuminate\Http\Request; use Auth; use Config; class MailChimpController extends Controller { public $mailchimp; public $listId = ''; public function __construct(\Mailchimp $mailchimp) { $this->mailchimp = $mailchimp; } public function manageMailC() { return view('mailchimp'); } public function sub(Request $request) { $this->validate($request, [ 'email' => 'required|email', ]); try { $this->mailchimp ->lists ->subscribe( $this->listId, ['email' => $request->input('email')] ); return redirect()->back()->with('success','Email Subscribed ‘); } catch (\Mailchimp_List_AlreadySubscribed $e) { return redirect()->back()->with('error',Already Subscribed'); } catch (\Mailchimp_Error $e) { return redirect()->back()->with('error','Error MailChimp'); } } public function sendComp(Request $request) { $this->validate($request, [ 'subject' => 'required', 'to_email' => 'required', 'from_email' => 'required', 'message' => 'required', ]); try { $options = [ 'list_id' => $this->listId, 'subject' => $request->input('subject'), 'from_name' => $request->input('from_email'), 'from_email' => '[email protected]', 'to_name' => $request->input('to_email') ]; $content = [ 'html' => $request->input('message'), 'text' => strip_tags($request->input('message')) ]; $campaign = $this->mailchimp->campaigns->create('regular', $options, $content); $this->mailchimp->campaigns->send($campaign['id']); return redirect()->back()->with('success','send camp successfully'); } catch (Exception $e) { return redirect()->back()->with('error','Error MailChimp'); } } }
Laravel View
After creating Controller, the next step is to create your view blade file in resources/views/ mailchimp.blade.php. Just paste the following code in the file. You can also check out MailChimp php integration On Cloudways, as it is indeed an all-in-one platform to get engage with your audiences and other stakeholders.
@extends('layouts.app') @section('content') <h2 class="text-center">MailChimp API Example</h2> <div class="container"> @if ($message = Session::get('success')) <div class="alert alert-success alert-block"> <button type="button" class="close" data-dismiss="alert">×</button> <strong>{{ $message }}</strong> </div> @endif @if ($message = Session::get('error')) <div class="alert alert-danger alert-block"> <button type="button" class="close" data-dismiss="alert">×</button> <strong>{{ $message }}</strong> </div> @endif <div class="row"> <div class="col-md-5"> <div class="well"> {!! Form::open(array('route' => 'subscribe')) !!} <div> <h3 class="text-center">Subscribe Your Email</h3> <input class="form-control" name="email" id="email" type="email" placeholder="Your Email" required> <br/> <div class="text-center"> <button class="btn btn-info btn-lg" type="submit">Subscribe</button> </div> </div> {!! Form::close() !!} </div> </div> <div class="col-md-7"> <div class="well well-sm"> {!! Form::open(array('route' => 'sendComp','class'=>'form-horizontal')) !!} <fieldset> <legend class="text-center">Send Campaign</legend> <!-- Name input--> <div class="form-group"> <label class="col-md-3 control-label" for="name">Subject</label> <div class="col-md-9"> <input id="name" name="subject" type="text" placeholder="Your Subject" class="form-control"> </div> </div> <div class="form-group"> <label class="col-md-3 control-label" for="email">To</label> <div class="col-md-9"> <input id="email" name="to_email" type="text" placeholder="To " class="form-control"> </div> </div> <div class="form-group"> <label class="col-md-3 control-label" for="email">From</label> <div class="col-md-9"> <input id="email" name="from_email" type="text" placeholder="From " class="form-control"> </div> </div> <!-- Message body --> <div class="form-group"> <label class="col-md-3 control-label" for="message">Your message</label> <div class="col-md-9"> <textarea class="form-control" id="message" name="message" placeholder="Please enter your message here..." rows="5"></textarea> </div> </div> <!-- Form actions --> <div class="form-group"> <div class="col-md-12 text-right"> <button type="submit" class="btn btn-primary btn-lg">Send Campaign</button> </div> </div> </fieldset> {!! Form::close() !!} </div> </div> </div> </div> @endsection
Q: Which third party email sending providers are supported by default in Laravel?
A: Following are supported by default in Laravel:
- Mailgun
- Sparkpost
- Amazon SES
Q: What are the common reasons why emails fail to deliver?
A: Reasons why emails may fail to be delivered:
- Technical error of your programming script
- Blocked by your hosting provider while sending
- Reached the email sending rate limit set by your hosting provider
- Blocked by recipient server because of “bad reputation” of your hosting provider server
- Went to SPAM or another automatically filtered folder
Q: How to use mail() in Laravel?
A: Laravel provides a powerful and clean API over the SwiftMailer library with drivers for Mailgun, SMTP, Amazon SES, SparkPost, and send an email. With this API, we can send emails on a local server as well as the live server.
Example:
Laravel allows us to store email messages in our views files. For example, to manage our emails, we can create an email directory within our resources/views directory.
Q: How can we check if emails have been sent in Laravel?
A: In general, Mail::failures() returns an array of failed email addresses.
Q: How do I create an email template in Laravel?
A: An email template file is a blade file that you can customize to add details and custom sections as per your email template design.
Final Words
This brings us to the end of this article which demonstrates in detail the complete integration process of various emailing tools in Laravel. Using these pre-built tools, you can easily send emails in a Laravel application – in a quick time. Moreover, as mentioned above, their integration process is quite easy, so that developers can swiftly get started with the Laravel emailing tools.
If you still have any questions regarding this article, feel free to ask them in the comments section below.
Customer Review at
“Cloudways hosting has one of the best customer service and hosting speed”
Sanjit C [Website Developer]
Saquib Rizwan
Saquib is a PHP Community Expert at Cloudways - A Managed PHP Hosting Cloud Platform. He is well versed in PHP and regularly contributes to open source projects. For fun, he enjoys gaming, movies and hanging out with friends.