Setup & Send Email Using Mailgun in 10 Min with 2023 PHP Examples

Last Updated on

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

Send Email using Mailgun in PHP Code Example

We recommend using the Mailgun PHP SDK to send emails in PHP. You can quickly install it through composer. Once you include Mailgun in your file, you can create a new Mailgun instance and pass the sendMessage to send a new email.

  1. Require the composer mailgun/mailgun-php package.
  2. Include the composer autoload file in your application
  3. Create a new Mailgun instance inside of your file.
  4. Pass in your mailgun api key into the constructor for Mailgun.
  5. Set up your email content.
  6. Use the Mailgun sendMessage function to send the email.
# First, instantiate the SDK with your API credentials and define your domain.  
    $mgClient = new Mailgun("key-example");
    $domain = "example.com";
 
    # Now, compose and send your message.
    $mgClient->sendMessage($domain,
                   array('from' => 'Sender <sender@gmail.com>',
                         'to' => 'Receiver <receiver.com>',
                         'subject' => 'The Printer Caught Fire',
                         'text' => 'We have a problem.'));

how to send an email using mailgun in PHP

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.

In this PHP article, we will learn how to send an email using Mailgun API in PHP. We will learn how to send bulk emails and attachments with emails using Mailgun API in PHP.

  1. Create Mailgun Account
  2. Send an Email using Mail API
  3. Send an Email with HTML using Mailgun API
  4. Send bulk emails using Mailgun API

What is the Mailgun API?

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.

First, we need to create a free Mailgun account. After successful registration, we will get 5000 free emails to send. 

Let’s look at how to create a Mailgun account for free.

How to Setup a Mailgun Free Account

Visit the official Mailgun website to register for free.

Mailgun Website

Click on the Get Started button displayed on the website’s banner, and you will be redirected to the signup page.

You will see a similar form on the signup page, as shown in the following screenshot. Again, fill in all the required fields and create an account.

Sign Up for Mailgun

After successful registration, you will get redirected to Mailgun’s dashboard page. Now lick on the Overview link from the left sidebar under the section labelled Sending. 

On this page, you will see two ways to send emails, i.e., API and SMTP.

API and SMTP box

When we click on the API box and press the PHP. A new section will appear where the following details are available for you:

a) API Key

b) API base URL

We will get a similar section as presented in the following screenshot.

API Box

When we click on the SMTP box, a new section will appear where the following details are displayed:

a) SMTP hostname

b) Port

c) Username

d) Default password

You will see a similar section as presented in the following screenshot.

SMTP Box

How to Send a CURL Request to Mailgun API in PHP

We can send an email using Mailgun API in PHP without installing dependencies. As we know, Mailgun’s API allows basic authentication, so it provides us with the Private API key in our Mailgun account. We can use this private key to avoid installing dependencies to send an email.

Just log into your Mailgun account, go to Settings > API keys, and copy your private API.

API Private key

Now, we need the domain name to send an email from our PHP script. The following PHP script sends an email using Mailgun API.

<?php
 
 $mailgun = [
     'apiKey' => 'YOUR_PRIVATE_API_KEY',
     'domain' => 'YOUR_EMAIL_DOMAIN',
 ];
 
 $ch = curl_init();
 
 curl_setopt( $ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC );
 curl_setopt( $ch, CURLOPT_USERPWD, "api:{$mailgun['apiKey']}" );
 curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
 
 curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'POST' );
 curl_setopt( $ch, CURLOPT_URL, "http://api.mailgun.net/v3/{$mailgun['domain']}/messages" );
 curl_setopt( $ch, CURLOPT_POSTFIELDS,
     [
         'from' => "Automation Script <cron@{$mailgun['domain']}>",
         'to' => 'youreamil@gmail.com',
         'subject' => 'Testing Mailgun\'s API',
         'text' => "This is a new line\nThe next line.\r\nLine after CRLF.\n<strong>This won't work unless you use the 'html' param.</strong>",
     ]
 );
 
 $result = curl_exec( $ch );
 curl_close( $ch );
 
 print_r( $result );
 /*
 Success response is like:
     {
         "id": "youreamil@gmail.com",
         "message": "Thank you."
     }
 */

In the above code we used Mailgun API where we provided our Private key and Domain name like this.

 $mailgun = [
     'apiKey' => 'YOUR_PRIVATE_API_KEY',
     'domain' => 'YOUR_EMAIL_DOMAIN',
 ];

We used the curl functions to send an email in the above PHP script.

$ch = curl_init();
 curl_setopt( $ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC );
 curl_setopt( $ch, CURLOPT_USERPWD, "api:{$mailgun['apiKey']}" );
 curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );

Note: The example hardcodes API key. It is just for demonstration purposes. You should never hardcode secrets; rather, use a .env file or a secret manager service. Learn more.

How to Send an Email with HTML using Mailgun API in PHP

Sending an email is very time-consuming, and using Mailgun API can save us time. So, we use the Mailgun API to send an email with HTML.

To use the Mailgun API, we need to embed it in our project. Follow the steps given below.

  • Download Composer and install it from this link. click here.
  • Open the cmd prompt as administrator.
  • Use cd command go to your project folder.
C:> cd  C:xampphtdocsyour-project-folder
  •  Now run this command:
c:xampphtdocsyour-project-folder> composer require mailgun/mailgun-php:~1.7.2 

We are now ready to use the Mailgun API.

Steps to send an email with HTML

We need to follow the following steps to send an email with HTML.

Create the index.php File

We need to create a Mail.php file where we save the PHP script that sends an email with HTML. Now, at the top of the index.php file, add the following script.

require 'vendor/autoload.php';
use MailgunMailgun;

Create Mailgun object using API Key

To create the Mailgun object we use the following script.

 $mgClient = new Mailgun('<-- API KEY -->');

We send an email by calling the sendMessage() method of the Mailgun object with parameters such as domain, sender, receiver, subject, text, HTML, etc.

PHP Code Snippet to send an HTML Email through Mailgun

<?php
//composer require mailgun/mailgun-php:~1.7.2
# We include the Autoloader
require 'vendor/mailgun.php';
use MailgunMailgun;
?>
<html>
<head>
<title>
Send Email via Mailgun API Using PHP
</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="js/jquery-1.11.3.min.js" type="text/javascript"></script>
<script src="js/bootstrap.js" type="text/javascript"></script>
<link href="css/bootstrap.css" rel="stylesheet" type="text/css"/>
<link href="css/style.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<div id="main">
<h1>Send Email via Mailgun API Using PHP</h1>
</div>
</div>
<div class="col-md-12">
<div class="matter">
<div id="login">
<h2>Send Email</h2>
<form action="index.php" method="post">
<label class="lab">Sender's Name :</label>
<input type="text" name="sname" id="to" placeholder="Senders Name"/>
<label class="lab">Receiver's Email Address :</label>
<input type="email" name="to" id="to" placeholder="Receiver's email address" />
<label class="lab">Email type:</label><div class="clr"></div>
<div class="lab">
<input type="radio" value="def" name="etype" checked>Default
<input type="radio" value="cc" name="etype" >cc
<input type="radio" value="bcc" name="etype" >bcc </div>
<div class="clr"></div>
<label class="lab">Subject :</label>
<input type="text" name="subject" id="subject" placeholder="subject" required />
<label class="lab">Message body :</label><div class="clr"></div>
<div class="lab">
<input type="radio" value="text" name="msgtype" checked>Text
<input type="radio" value="html" name="msgtype" >HTML</div>
<textarea type="text" name="msg" id="msg" placeholder="Enter your message here.." required ></textarea>
<input type="submit" value=" Send " name="submit"/>
</form>
</div>
</div>
</div>
</div>
<!-- Right side div -->
</div>
</body>
</html>
<?php
if (isset($_POST['sname'])) {
$sname=$_POST['sname'];
$to = $_POST['to'];
$subject = $_POST['subject'];
$msg = $_POST['msg'];
$msgtype = $_POST['msgtype'];
if($msgtype=='text'){
$html='';
}
else{
$msg = htmlentities($msg);
$html=$msg;
$msg='';
}
$mgClient = new Mailgun('<-- API KEY -->');
// Enter domain which you find in Default Password
$domain = "<-- DEFAULT SMTP LOGIN DOMAIN -->";
 
# Make the call to the client.
$result = $mgClient->sendMessage($domain, array(
"from" => "$sname <mailgun@<--DEFAULT SMTP LOGIN DOMAIN-->>",
"to" => "Baz <$to>",
"subject" => "$subject",
"text" => "$msg!",
'html' => "$html"
));
echo "<script>alert('Email Sent Successfully.. !!');</script>";
}
?>

This is our main index.php file that sends an email using Mailgun API. In the above code, we created a Mailgun object and sent an email using the sendMessage() method.

To make it the HTML page nicer, use the following CSS code as well.

CSS code:

@import url(http://fonts.googleapis.com/css?family=Raleway);
 
#main{
margin:50px auto;
font-family:raleway;
}
h2{
font-weight: 600;
background-color: #FEFFED;
text-align:center;
border-radius: 10px 10px 0 0;
margin: -10px -40px;
padding: 15px;
}
#login{
width:40%;;
margin:0 auto;
display:inline-block;border-radius: 10px;
font-family:raleway;
border: 2px solid #ccc;
padding: 10px 40px 25px;
}
textarea{
margin-top: 8px;
font-size: 16px;
font-family:raleway;
}
input[type=radio]{
margin-top: 8px;
}
input[type=text],[type=email],input[type=password]{
width:99.5%;
padding: 10px;
margin-top: 8px;
border: 1px solid #ccc;
padding-left: 5px;
font-size: 16px;
font-family:raleway;
}
input[type=submit]{
width: 100%;
background-color:#FFBC00;
color: white;
border: 2px solid #FFCB00;
padding: 10px;
font-size:20px;
cursor:pointer;
border-radius: 5px;
margin-bottom: 15px;
}
a{
text-decoration:none;
color: cornflowerblue;
}
i{
color: cornflowerblue;
}
h1{
font-weight: 600;
text-align: center;
display:inlne;
alignment-adjust: center;
margin:0 auto;
width:100%;
}
textarea[type=text]{
width:100%;
height:200px;
}
.matter{
alignment-adjust: central;
margin:0 auto;
text-align: center;
}
.clr{
clear:left;
}
.lab{
font-size: 110%;
float:left;
}
@media screen and (max-width: 800px) {
#login{
width:330px;
}
}

Sending Email in Mailgun PHP SDK Library with cURL

We prefer using the SDK because it allows us easily interact with our Mailgun API. If you are familiar with SDK, let’s first see what is required to send an email message using the HTTP CURL library for PHP.

function send_simple_message() {  
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
      curl_setopt($ch, CURLOPT_USERPWD, 'api:key-example');
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
      curl_setopt($ch, CURLOPT_URL,
          'https://api.mailgun.net/v2/samples.mailgun.org/messages');
      curl_setopt($ch, CURLOPT_POSTFIELDS,
            array('from' => 'Sender<senderemail@gmail.com>',
                  'to' => 'Receiver <receiveremail@gmail.com>',
                  'subject' => 'The Printer Caught Fire',
                  'text' => 'We have a problem.'));
      $result = curl_exec($ch);
      curl_close($ch);
      return $result;
    }
    echo send_simple_message();

The above code sends an email using the Mailgun API. However, we can see a lot of complicated and confusing code as well if you are not a CURL expert.

So we use SDK to reduce the amount of code to just a few lines.

PHP Code to Send an email with Mailgun PHP SDK:

# First, instantiate the SDK with your API credentials and define your domain.  
    $mgClient = new Mailgun("key-example");
    $domain = "example.com";
 
    # Now, compose and send your message.
    $mgClient->sendMessage($domain,
                   array('from' => 'Sender <sender@gmail.com>',
                         'to' => 'Receiver <receiver.com>',
                         'subject' => 'The Printer Caught Fire',
                         'text' => 'We have a problem.'));

Installing PHP Mailgun SDK Composer Library

To install the SDK, we need to use the Composer in our project. To install the composer, run the following command.

curl -sS https://getcomposer.org/installer | php

After running the above command, we get the result like this.

Install Composer

Use SDK PHP Library to Send an Email

To send an email using the SDK PHP library, we should always use the Composer autoloader to load dependencies automatically. Add the following script to your file.

require 'vendor/autoload.php';
use Mailgun\Mailgun;

Here’s how to send a message using the SDK:

//First we instantiate the SDK with your API credentials
$mg = Mailgun::create('key-example'); // Only for US servers
$mg = Mailgun::create('key-example', 'http://api.eu.mailgun.net'); // For EU servers
 
// Now, compose and send your message.
// $mg->messages()->send($domain, $params);
$mg->messages()->send('example.com', [
  'from'    => 'sender@gmail.com',
  'to'      => 'receiver@gmail.com',
  'subject' => 'The PHP SDK is awesome!',
  'text'    => 'It is so simple to send a message.'
]);

Note: Remember $domain must match the domain you have configured on app.mailgun.com.

How to Send Bulk Emails using Mailgun API

We can send bulk emails using the Mailgun API. Here are the 3 quick methods to send bulk emails with Mailgu API in PHP.

Option 1: Call each Recipient through a Loop

We can run a loop to call each recipient individually to send bulk emails using Mailgun API shown in the code below.

use Mailgun\Mailgun;
 
$mg = Mailgun::create('key-example'); // For US servers
 
foreach ($recipients as $recipient) {
    $mg->messages()->send('domain.com', [
        'from'    => 'sender@gmail.com',
        'to'      => $receiver@gmail.com,
        'subject' => 'The PHP SDK is awesome!',
        'text'    => 'It is so simple to send a message.'
    ]);
}

Option 2: Use the Message Builder() Method

We can use the message builder() method and send emails to multiple recipients as shown below.

use Mailgun\Mailgun;
use Mailgun\Message\MessageBuilder;
 
// BUILDER
 
$builder = new MessageBuilder();
# Define the from address.
$builder->setFromAddress("sender@gmail.com", array("first"=>"PHP", "last" => "SDK"));
# Define the recipient.
$builder->addToRecipient("recipient1@gmail.com", array("first" => "Name1", "last" => "Surname1"));
$builder->addToRecipient("recipient2@gmail.com", array("first" => "Name2", "last" => "Surname2"));
# Define the subject.
$builder->setSubject("A message from the PHP SDK using Message Builder!");
# Define the body of the message.
$builder->setTextBody("This is the text body of the message!");
 
// SENDING
 
$mg = Mailgun::create('key-example'); // For US servers
$mg->messages()->send("domain.com", $builder->getMessage());

In the above code, we used a utility called MessageBuilder. The MessageBuilder allows us to build a message object by calling methods for each MIME attribute.

Option 3: Use the Batch Message Utility

Here’s how to use Batch Message to send bulk emails using Mailgun API.

require 'vendor/autoload.php';
use Mailgun\Mailgun;
 
// First, instantiate the SDK with your API credentials
$mg = Mailgun::create('key-example');
 
# Next, instantiate a Message Builder object from the SDK, pass in your sending domain.
$batchMessage = $mg->messages()->getBatchMessage("example.com");
 
# Define the from address.
$batchMessage->setFromAddress("sender@gmail.com", array("first"=>"PHP", "last" => "SDK"));
# Define the subject.
$batchMessage->setSubject("A Batch Message from the PHP SDK!");
# Define the body of the message (One is required).
$batchMessage->setTextBody("This is the text body of the message!");
$batchMessage->setHtmlBody("<html><p>This is the HTML body of the message</p></html>");
$batchMessage->setTemplate("template_name");
 
# Next, let's add a few recipients to the batch job.
$batchMessage->addToRecipient("recipient1@gmail.com", array("first" => "John", "last" => "Doe"));
$batchMessage->addToRecipient("recipient2@gmailcom", array("first" => "Sally", "last" => "Doe"));
$batchMessage->addToRecipient("recipient3@gmail.com", array("first" => "Mike", "last" => "Jones"));
...
// After 1,000 recipients, Batch Message will automatically post your message to the messages endpoint.
 
// Call finalize() to send any remaining recipients still in the buffer.
$batchMessage->finalize();
 
$messageIds = $batchMessage->getMessageIds();

In the above code, we used the Batch Message utility. The BatchMessage extends the MessageBuilder and allows us to iterate through recipients from a list. 

How Fast is the Mailgun API service to send Emails

Mailgun is a rapid-fire email delivery service that can send up to 15 million messages per hour whenever you want. It sends your emails to your inbox in record time, with 99% of your messages within the first five minutes after you send them.

Whether you want to send 15,000 messages per hour or 15 million, Mailgun can guarantee that sending rate with Rapid Fire Delivery. 

So this means that you can get your high-volume emails out to customers at the optimal time without ever worrying about delays in processing. 

Why do we use the Mailgun API service to send Emails

Mailgun supports sending emails to single recipients and a group of recipients through a single API call or SMTP session. It focuses on helping users to send out bulk emails quickly and boost the engagement of their emails.

One of the best things about using a Mailgun account is that the tool also integrates with WordPress. You can install Mailgun as a plugin on your WordPress site to send emails directly from there.

Is Mailgun Secure for sending emails in PHP?

Yes, Mailgun is a secure tool that doesn’t share customer information with unauthorized third parties. Its server infrastructure is stored at top-tier data centres.

Perfect! That’s it for this article – time to wrap it up.

Sending Emails in PHP With Mailgun

This article explains how to send an email using Mailgun API.  

I hope you’ve enjoyed the article. Stay tuned for more at FuelingPHP

Get deeper with PHP

We have many fun articles related to PHP. You can explore these to learn more about PHP.

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.