Mailgun API Laravel Integration: Send Email Code Example | 2023

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

In this article, we will learn what Mailgun is and what it is used for. We will also discuss how to integrate Mailgun API into your Laravel. We will explain all the steps required for sending emails in Laravel using Mailgun.

Table of Contents

In this article, we will cover the following sections.

  1. How to Send Emails in Laravel Using Mailgun.
  2. What is Mailgun?
  3. What is Mailgun used for?
laravel mailgun

7 Steps To Send Emails in Laravel Using Mailgun

To send emails in Laravel via Mailgun, follow the below steps.

Step 1: Create an Account at Mailgun.

First, you need to create an account at Mailgun. Read our article to learn more about how to create a Mailgun account.

Step 2: Configure Mailgun in Laravel

After creating the Mailgin account, you now need to configure Mailgun in Laravel. To configure the Mailgun driver in your Laravel application, navigate to the .env file and update the following keys to include Mailgun SMTP details.

# The name of the email driver or mailer
MAIL_MAILER=mailgun

# Mailer Host
MAIL_HOST=smtp.mailgun.org

# Mailer Port
MAIL_PORT=587

# Username
MAIL_USERNAME=userr@1122.mailgun.org

# Password
MAIL_PASSWORD=************

# Encryption Format
MAIL_ENCRYPTION=SSL

# Sender/Application Email
MAIL_FROM_ADDRESS="user1@example.com"

# Sender/Application Name
MAIL_FROM_NAME="${APP_NAME}"

# Domain Name
MAILGUN_DOMAIN=sandbox1b0b6c203ee446178d79ac2bf92c0213.mailgun.org

# Domain Secret / API Key
MAILGUN_SECRET=53c65413085a9c2f4bd0165cc3b32ae4-90346a2d-f6713c21

Now the Mailgun service has been configured in your Laravel application.

Step 3: Create a Mail Class in Laravel

Laravel offers a mail class for working with emails. You can create an email class by running the following artisan command.

php artisan make:mail TestEmail

After running the above command, a new folder named “Mail” will be created under the “app” folder. Inside the “Mail” folder, a new file will be created with “TestEmail.php.”
Now we need to update the code in the TestEmail.php file. See the following code to update your “TestEmail.php” file.

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class TestEmail extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        /**
         * You need to replace the "from" field with your valid sender email address.
         * The "email-template" is the name of the file present inside
         * "resources/views" folder. If you don't have this file, then
         * create it.
         */
        return $this->from("supporteam@example.com")->view('email-template');
    }
}

Step 4: Create a View For Email Template

Since we added the name of the view inside the “TestEmail.php,” we need to create a view file inside the folder “resources/views” with the name “emailtempl.blade.php.” Then, use the following code to update your email template.

<div class="container" style="padding: 1rem; background: #111111;">
    <p>Good Evening!</p>
    <p>
        Welcome to Laravel. This is a demo to send emails in Laravel via Mailgun.
    </p>
</div>

Step 5: Create a Controller to Send Email

In this step, we need to create a controller for sending emails. Run the following command to create a controller.

php artisan make:controller TestEmailController

When we run the above command, a new file will be created named “TestEmailController.php” under the “app/Http/Controllers” folder. After creating the controller, we now need to add a function inside this controller. Use the following code to update your controller file.

<?php

namespace App\Http\Controllers;

use App\Mail\TestEmail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;

class TestEmailController extends Controller
{
    public function sendEmail()
    {
        /** 
         * Store a receiver email address to a variable.
         */
        $reveiverEmailAddress = "user2023@gmail.com";

        /**
         * Now, import the Mail class at the top of this page,
         * and call the to() method for passing the 
         * receiver email address.
         * 
         * Also, call the send() method to incloude the
         * TestEmail class that contains the email template.
         */
        Mail::to($reveiverEmailAddress)->send(new TestEmail);

        /**
         * Now, check if the email has been sent successfully, or not.
         * Return the appropriate message.
         */
        if (Mail::failures() != 0) {
            return "Email has been sent successfully.";
        }
        return "There was some an error sending this email.";
    }
}

Step 6: Add a Route

In this step, we need to add a route inside the file “web.php,” which is available under the “routes” folder. Use the following code for adding the routes.

<?php

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
|Here you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group.
|*/

Route::get('/', function () {
    return view('welcome');
});

/**
 * Now, add new route named "send-email". And upon accessing this URL, the "sendEmail"
 * function inside the "TestEmailController" class will be triggered.
 */
Route::get('send-email', [App\Http\Controllers\EmailController::class, 'sendEmail']);

Step 7: Send Email

To send an email, open your web browser and access the following URL “/send-email” by navigating into your web application. After accessing the above URL, you will see a success message on your screen. You can check your Mail inbox to see the new email.

What is Mailgun?

Mailgun is an email service that allows us to use the SMTP protocol or API to send emails. It also provides us with reports to track the number of emails sent and also allows us to check addresses for typos or spam problems. It has an email validation service that provides accurate validation results on the market.

Additional Articles on Email Marketing Services

Mailgun is one of the most helpful email APIs that developers use. We can easily send transactional or bulk emails using Mailgun’s SMTP and HTTP API in PHP. Mailgun gives you the option to choose how you want to send your emails through API or through SMTP.

Mailgun also allows you to create eye-catching emails in minutes. You can create a personalized email targeted at a specific audience. And the Email analytics, based on performance data of your sent emails, lets you know the best time to send your messages.

In Mailgun, you can have the option to choose how you want to send your emails using Mailgun’s API (A popular method of sending emails that can integrate with languages like Python, PHP, Ruby, and more.) or using the SMTP method (Simple Mail Transfer Protocol, which is an easy way to transfer your emails.)

To use Mailgun API, first, we need to create a free Mailgun account. After successful registration, we will get 5000 free emails to send. 

Visit the link to learn more about how to create a Mailgun account.

What is Mailgun used for?

We use MailGun as a transactional service to send emails through our APIS, web applications, and scripts. You can use it to send emails in bulk or on demand. It is recommended to use a service like Mailgun vs your web service for sending emails as it has IPs that have built trust in email clients. It also has full-featured APIs.

Digging Deeper With MailGun

This article is part of our series digging into MailGun. Check out the full list of articles below to level up your knowledge and ability in MailGun.

Sending Emails in Laravel through Mailgun API Explored

We recommend using the Mailgun Mailgun email service. It lets you choose to send email using API (The most popular method for sending emails, which can integrate easily with languages like Python, PHP, Ruby, and more.) or SMTP (Simple Mail Transfer Protocol, which is an easy way to transfer your emails.)

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.