Sling Academy
Home/PHP/How to use MailGun to send email in Laravel

How to use MailGun to send email in Laravel

Last updated: January 16, 2024

Introduction

Laravel, a powerful MVC PHP framework, offers multiple ways to send emails. One convenient service for sending emails is Mailgun, a reliable email service provider. This tutorial shows how to set up and use MailGun alongside Laravel to send a variety of email messages, with implementation examples ranging from basic to advanced scenarios.

Setting Up MailGun

Before we jump into Laravel, you’ll need to sign up for a Mailgun account, verify your domain, and obtain your API keys. For the sake of brevity, we’ll assume that these steps have been completed.

Install Mailgun PHP SDK

Start with requiring the Mailgun PHP SDK through Composer:

composer require mailgun/mailgun-php kriswallsmith/buzz nyholm/psr7

Once the installation is completed, the Mailgun API can be used within Laravel.

Configure Laravel

Edit the .env file to include your Mailgun domain and secret:

MAIL_MAILER=mailgun
MAILGUN_DOMAIN=your-domain.com
MAILGUN_SECRET=your-keyfo1@mailgun_neffb73n

Update the config/mail.php configuration file to use Mailgun as the mail service provider:

'mailers' => [
  'mailgun' => [
    'transport' => 'mailgun',
  ],
],
// ...

Basic Email Sending

Sending a Simple Email

To send a basic email with Laravel, simply use the Mail facade along with a mailable class:

use Illuminate\Support\Facades\Mail;
use App\Mail\WelcomeEmail;

Mail::to('[email protected]')->send(new WelcomeEmail());

The WelcomeEmail mailable class contains the structure of the email being sent. You can generate a new mailable using Artisan:

php artisan make:mail WelcomeEmail

Configuring the Mailable

In the newly created mailable (app/Mail/WelcomeEmail.php), you can specify the view and data to be used:

namespace App\Mail;

use Illuminate\Mail\Mailable;

class WelcomeEmail extends Mailable
{
  public function build()
  {
    return $this->view('emails.welcome');
  }
}

Advanced Email Features

Using Templates

To make use of Mailgun templates, you can add the following to your mailable:

public function build()
{
  return $this->view('emails.blank')
             ->with([ 'message' => 'Your template data here.' ])
             ->text('emails.blank_plain');
}

Attachments

Including attachments can be done as follows:

public function build()
{
  return $this->view('emails.welcome')
              ->attach('/path/to/file.pdf', [
                  'as' => 'Filename.pdf',
                  'mime' => 'application/pdf',
              ]);
}

Sending HTML Content

If you desire to send HTML content in your emails, structure the mailable like this:

public function build()
{
  return $this->view('emails.html-content')
              ->text('emails.text-content');
}

Sending Emails Asynchronously

For better performance, you can queue emails to be sent in the background:

use Illuminate\Support\Facades\Mail;
use App\Mail\WelcomeEmail;

Mail::to('[email protected]')->queue(new WelcomeEmail());

Handling Failed Jobs

Laravel allows you to define a failed job callback directly in the mailable:

public function failed($exception)
{
  // Handle the failure scenario
}

Conclusion

Adopting Mailgun for your Laravel application brings flexibility and robustness in sending emails. The above guide indicates the practical steps to set up and customize your email services. Remember, it’s important to respect user privacy and comply with email sending regulations.

Next Article: Laravel 403 Forbidden Error: You don’t have permission to access ‘/’ on this server

Previous Article: How to use SendGrid to send email in Laravel

Series: Laravel & Eloquent Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array