Laravel comes up with the customization and integration of third-party libraries. These libraries make the applications more featured. If I will talk about the email service, then Laravel already provides the SwiftMailer library for sending emails. The best thing is this library supports lots of drivers for email configurations. You can configure it with any email service such are SMTP, Mailgun, Postmark, Amazon SES, Sendmail, etc. The API-based drivers are much faster and more proficient than the SMTP services. The delivery response of email is very high. Even if you send emails in bulk then the API-based email drivers will be a good option. So, today, in this post, I will talk about one of the powerful services named Mailgun which is used for sending emails. I will show you the Laravel Mailgun integration in this Laravel 9 post.
But before moving ahead on email, let’s know about Mailgun and what it does.
What is Mailgun
Mailgun is an email service that provides API-based email services. You can send N number of emails with a 98% delivery rate. They guarantee to send a safer email to the recipients. It allows you to send any transactional emails from their website itself. You can create an email template and use it while sending emails from their website. They provide the email editor as well. So, you can customize your email formatting as per your need.
Let’s focus on the Mailgun integration in Laravel 9.
Create UI Auth Using Vue Auth Scaffolding in Laravel 9
Prerequisites
For having a Laravel 9 project, you must need the below configurations.
- PHP >=8.0.2
- Composer
- Apache/Nginx Server
- VS Code Editor (Optional)
- MySQL (version > 5)
Once, you are ready, let’s create a project.
Create Laravel Project For Mailgun Integration
Look into the terminal and hit the below command.
composer create-project --prefer-dist laravel/laravel laravel-mailgun
After completing the project, let’s configure a database first. But before that, you need to create a database first.
CREATE DATABASE laravel_email
Once, you created the database, navigate to the project folder and look at the .env file.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_mail
DB_USERNAME={{DB_USER_NAME}}
DB_PASSWORD={{DB_PASSWORD}}
Now, you are good to go for the Mailgun Integration.
Create UI Auth Using React Auth Scaffolding in Laravel 9
How to Integrate Mailgun in Laravel
At the very first step, you will require a Mailgun account. So, if you don’t have then you will need to create it. Visit the official site of Mailgun and then do signup for a new account.
After signup, you will need to verify your account by verifying your email and mobile number. So, I recommend you to complete these steps.
Once, you are done, let’s set up a domain to send email using Mailgun.
Use Yajra Datatable in Laravel 9 with Server Side Processing
Domain Setup in Mailgun to Send Email
The domain name is required to send the email using Mailgun. By default, it will give you a random domain name for the free account. If you want to change it, you will need to pay for that.
You will see the domain option in the Dashboard, under Sending -> Domain.
Get SMTP Credentials For Laravel Mailgun Integration
For the Mailgun integration in Laravel, you will require the username, password, SMTP settings, etc. You will find these credentials in the dashboard under Sending->Domains option in the menu.
When you will click on the domain, you will have the below result. The Mailgun provides API and SMTP both options to integrate with the applications.
Here, you will have to choose the SMTP option as shown below. It will generate the credentials for the Laravel integration.
How to Upload Multiple Images Using Ajax in Laravel 9
Mailgun Integration in Laravel 9
After getting the credentials from the Mailgun, navigate to the .env file again. There you will see email settings. You will need to add the credentials as shown below.
You are required to add a domain name also. Hence, you may copy it from the Mailgun dashboard and paste it in the configuration.
MAIL_DRIVER=mailgun
MAIL_HOST=smtp.mailgun.org
MAIL_PORT=587
MAIL_USERNAME={{ USERNAME_BY_MAILGUN }}
MAIL_PASSWORD={{ PASSWORD_BY_MAILGUN }}
MAIL_ENCRYPTION=tls
MAILGUN_DOMAIN={{ DOMAIN_CREATED_IN_MAILGUN }}
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${APP_NAME}"
You can see these configurations for Mailgun in the config/services.php file inside the project.
The Mailgun integration is done, but we need to check whether we are able to send emails. So
Create Mail Class in Laravel 9 For Sending Email
You can create a mail class using the below command.
php artisan make:mail TestMail
After creating the class, let’s add the sender address along with the email template.
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class TestMail 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('sendermail@mail.com')->view('mail-template');
}
}
In the above snippet, you need to add an actual sender’s email address. Also, we will create a new email template that is included here.
How to Upload Image Using Ajax in Laravel 9 with Validation
Create an Email Template in Laravel 9
We need to create the template view with the name mail-template.blade.php. I have added a very basic template with some messages. It is just for a demo purpose.
<!doctype html>
<html lang="en">
<head>
<title>Mailgun Integration in Laravel 9 | Programming Fields</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-xl-6 col-lg-6 col-sm-12 m-auto">
<h3> Mailgun integration in Laravel 9 </h3>
<p> Hey, </p>
<p> Welcome to the Programming Fields </p>
<p> This is a basic demo for sending email in Laravel 9 using Mailgun. </p>
<p> I hope you will enjoy this post. </p>
<br/>
<br/>
<p> Best Regards</p>
<p> Team, Programming Fields </p>
</div>
</div>
</div>
</body>
</html>
Next, you need a controller for triggering the email function. Hence, create a controller for it.
Create a Controller For Sending Email in Laravel 9
You can create a controller using the below command.
php artisan make:controller MailController
Now, add the below functionality inside this controller.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Mail\TestMail;
class MailController extends Controller
{
public function sendEmail(Request $request) {
$to_email = "youremail@gmail.com";
Mail::to($to_email)->send(new TestMail);
if(!Mail::flushMacros()) {
return "<p> Success! Your E-mail has been sent.</p>";
}
else {
return "<p> Failed! Your E-mail has not sent.</p>";
}
}
}
Next, you need to add a route for the above function.
Add Route
Navigate to the routes/web.php file and add the below route.
<?php
use App\Http\Controllers\MailController;
use Illuminate\Support\Facades\Route;
Route::get('/send-email', [MailController::class, 'sendEmail']);
Now, It’s result time to check the integration.
Run the application and hit the URL as we defined in the route.
Check the inbox for the email response as well.
Conclusion
That’s it for this post, we integrated Mailgun in Laravel 9 for sending an email. It provides faster email delivery with a 98% of success response. I hope you will find helpful to this post. Thank you.
David D says
Informative post👍
Sukanya Sharma says
Nicely Explained.