Implementing Mailgun in Laravel

In today’s digital age, sending email is crucial for businesses. Laravel, one of the most popular PHP frameworks, provides robust support for email functionality. With Laravel, we can easily integrate any mail service providers like Mailtrap, Mailgun, or Gmail.

In this post, we will implement Mailgun in Laravel with a practical example. By integrating Mailgun, a powerful email service provider, with Laravel, you can easily manage and send emails from your applications.

Sign up for Mailgun

Before getting started, visit the Mailgun website and sign up for an account. Mailgun offers a free plan that allows you to send up to 10,000 emails a month.

If you haven’t already, install Laravel on your local machine. You can do this by following the Laravel documentation or using Composer, the PHP package manager. Ensure that your Laravel installation is up to date. However, you can use any existing application.

Set up Mailgun Credentials in Laravel

Once your Laravel application is ready, open the .env file located at the root of your project. Add the following Mailgun-related configuration variables:

MAIL_MAILER=mailgun
MAIL_HOST=smtp.mailgun.org
MAIL_PORT=587
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=your-email@example.com
MAIL_FROM_NAME="${APP_NAME}"
MAILGUN_DOMAIN=your-mailgun-domain
MAILGUN_SECRET=your-mailgun-secret

Make sure to replace your-email@example.com with your preferred email address and provide the correct values for MAILGUN_DOMAIN and MAILGUN_SECRET, obtained from your Mailgun account.

Configure Laravel Mail settings

The next thing you need to do is configure mail. To do that, open the config/mail.php file in your Laravel project. Locate the mailers array and add the following configuration for the Mailgun driver:

'mailgun' => [
    'transport' => 'smtp',
    'host' => env('MAIL_HOST', 'DEFAULT_VALUE'),
    'port' => env('MAIL_PORT', 'DEFAULT_VALUE'),
    'username' => env('MAIL_USERNAME', 'DEFAULT_VALUE'),
    'password' => env('MAIL_PASSWORD', 'DEFAULT_VALUE'),
    'encryption' => env('MAIL_ENCRYPTION', 'DEFAULT_VALUE'),
    'timeout' => null,
    'auth_mode' => null,
],

Here, we have added a configuration form .env file using its helper. The DEFAULT_VALUE is optional but while working with teams or multiple domains it’s good practice to add a default value. So whenever some variables are missing in your environment file then it will load default values and work without throwing errors.

Create a Mailable Class

To process further and send emails using Mailgun, you need to create a Mailable class in Laravel. Run the following command in your terminal to generate a new Mailable class:

php artisan make:mail WelcomeEmail

This will create a new WelcomeEmail.php file in the app/Mail directory. Open the file and customize the build() method according to your email content and design. Let’s modify it:

<?php

namespace App\Mail;

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

class WelcomeEmail extends Mailable
{
    use Queueable, SerializesModels;

    public $user;

    public function __construct($user)
    {
        $this->user = $user;
    }

    public function build()
    {
        return $this->view('emails.welcome')
          ->subject('Welcome to Our Application')
          ->with([
              'userName' => $this->user->name,
          ]);
    }
}

Here, it has been designed to get a user model while sending mail and also configured view, subject and other data for the view.

Sending Emails with Mailgun

To send an email using Mailgun in Laravel, you can leverage the Mailable class created in the previous step. In a controller or wherever you want to trigger the email, add the following code:

<?php
use App\Mail\WelcomeEmail;
use Illuminate\Support\Facades\Mail;

public function sendWelcomeEmail()
{
    $user = User::first();
    Mail::to($user->email)->send(new WelcomeEmail($user));

    return "Welcome email sent successfully!";
}

Here, we have selected the first user statically. and send welcome mail using the Mail facade. While sending this mail Laravel will use Mailgun in the background automatically. You can adjust the code as per your application’s requirements.

Conclusion

By following these steps, you can easily implement Mailgun in your Laravel application. Remember to customize the email templates or logic for sending mail or even using different drivers with different types of mail.

With Mailgun and Laravel working together, you can enhance your email communication and provide a seamless user experience. For more mail information please refer to the official Laravel documentation on Mail.