- What's new
Mailpets: For The Love Of Animals
When I started coding, I remember debating whether I would want to learn ASP.NET vs PHP. I read thousands of bulletin boards on threads about each language to help me make my decision.
I chose PHP mainly for the community, the availability of examples and for the fact that it was open source. I’m sure these are similar reasons why you’ve chosen to adventure yourself in the world of PHP.
PHP is one of the most widely used languages, yet there is a lot of confusing or outdated material on the we.
The aim of this particular post is to provide you with a detailed overview on how to use Mailgun in your PHP environment with simple copy paste examples
A very straightforward way to use Mailgun and leverage its outstanding API to deliver emails is to install the official PHP library in your development environment, written and maintained as an open source project by our Mailgunner Travis.
Open your terminal and navigate to your server’s public folder. This is where you store your website and varies depending on installation and web-server used - cd /var/www/html
Create an empty directory for this project - mkdir mailgun-php
Enter the directory and execute the following commands - cd mailgun-php
(changes directory)
Now execute the following command to download and install Composer. - curl -sS https://getcomposer.org/installer | php
Composer used this way allows us to download PHP libraries with ease locally within the folder, now let’s use composer to install the Mailgun library itself.
Let’s run this to tell composer we’re going to use (and therefore we need it downloaded) the mailgun library (here we use 1.7.1) and its dependencies. - php composer.phar require mailgun/mailgun-php:~1.7.1
Congratulations, you’ve installed the mailgun official library and you are now ready to write some code!
Open a file and include the vendor/autoload.php
file to get started.
1<?php 2require 'vendor/autoload.php';3use Mailgun\Mailgun;4//Your credentials5$mg = new Mailgun("key-example");6$domain = "example.com";78//Customise the email - self explanatory9$mg->sendMessage($domain, array(10'from'=>'bob@example.com',11'to'=> 'sally@example.com',12'subject' => 'The PHP SDK is awesome!',13'text' => 'It is so simple to send a message.'14 )15)16?>
Using Mailgun with Swift Mailer is a breeze.
Make sure you have your domain’s SMTP credentials to hand! You can find these here they’re named:
Default SMTP Login
Default Password
Create a folder called Swiftmailer - mkdir swiftmailer, cd swiftmailer
Download Composer to install swiftmailer and its dependencies
curl -sS https://getcomposer.org/installer | php
Install Swiftmailer
php composer.phar require swiftmailer/swiftmailer @stable
Files will be downloaded, once finished simply create your own empty file to test that phpmailer works. Within your terminal you can achieve that by doing:
touch mailgun_with_swiftmailer.php
vim mailgun_with_swiftmailer.php
Here we’re using vim but you can edit the file mailgun_with_swiftmailer.php
in whichever editor you feel most comfortable with.
1require 'vendor/autoload.php';23// Create the Transport4$transport = Swift_SmtpTransport::newInstance('smtp.mailgun.org', 25)5 ->setUsername('your SMTP username')6 ->setPassword('your SMTP password')7 ;89// Create the Mailer using your created Transport10$mailer = Swift_Mailer::newInstance($transport);1112// Create a message13$message = Swift_Message::newInstance('Hello from Mailgun')14 ->setFrom(array('someone@domain.com' => 'John Doe'))15 ->setTo(array('someone_else@domain.org', 'third_contact@domain.org' => 'A third name'))16 ->setBody("And that's another ace in the hole for the Mailgun dev!")17 ;1819// Send the message20$result = $mailer->send($message);
Further information on sending much more complicated emails can be found in the official Swiftmailer documentation available online over here
Mailgun can also be used in conjunction with one of the most famous PHP emailing libraries: PHP Mailer.
PHP Mailer is a very valid alternative to the in-built php mail()
function, as it speeds up and allows you to heavily customise the way you send emails with PHP. Linux distributions and Mac OS X have an in-built function to send emails although unreliable. By the way, it is worth mentioning that Windows hasn’t got anything at all to send emails thus I suggest you keep reading.
Create a folder called phpmailer
mkdir phpmailer
cd phpmailer
Download composer to install phpmailer
and its dependencies
curl -sS https://getcomposer.org/installer | php
Composer is ready, let’s install Phpmailer(5.2.8) now:
php composer.phar require phpmailer/phpmailer:5.2.8
Files will be downloaded, once finished simply create a your own empty file to test that phpmailer works
touch mailgun_with_phpmailer.php
vim mailgun_with_phpmailer.php
Here we’re using vim but you can edit the file mailgun_with_phpmailer.php
in whichever editor you feel most comfortable with.
1<?php 2//Composer's autoload file loads all necessary files3require 'vendor/autoload.php';45$mail = new PHPMailer;67$mail->isSMTP(); // Set mailer to use SMTP8$mail->Host = 'smtp.mailgun.org'; // Specify mailgun SMTP servers9$mail->SMTPAuth = true; // Enable SMTP authentication10$mail->Username = 'username@domain.com'; // SMTP username from https://mailgun.com/cp/domains11$mail->Password = 'myp@55w0rd'; // SMTP password from https://mailgun.com/cp/domains12$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl'1314$mail->From = 'sender@domain.com'; // The FROM field, the address sending the email 15$mail->FromName = 'Orlie'; // The NAME field which will be displayed on arrival by the email client16$mail->addAddress('recipient@domain.net', 'BOB'); // Recipient's email address and optionally a name to identify him17$mail->isHTML(true); // Set email to be sent as HTML, if you are planning on sending plain text email just set it to false1819// The following is self explanatory20$mail->Subject = 'Email sent with Mailgun';21$mail->Body = '<span style="color: red">Mailgun rocks</span>, thank you <em>phpmailer</em> for making emailing easy using this <b>tool!</b>';22$mail->AltBody = 'Mailgun rocks, shame you can't see the html sent with phpmailer so you're seeing this instead';2324if(!$mail->send()) { 25 echo "Message hasn't been sent.";26 echo 'Mailer Error: ' . $mail->ErrorInfo . "n";27} else {28 echo "Message has been sent n";2930}31?>
The settings for authenticating with Mailgun’s SMTP server can be found over here, just like with Swiftmailer.
Log into your Mailgun control panel, pick a domain (or the sandbox domain that comes with every fresh account if you have not configured a custom domain), and copy paste these details (Default SMTP Login, Default Password) in the code snippet above in the smtp username and password fields.
Do you use other libraries in conjunction with Mailgun? If so we’d be happy to feature it in our next PHP blog post with full coverage and examples!
Happy Sending!
It's easy to get started. And it's free.
See what you can accomplish with the world’s best email delivery platform.
Last updated on August 28, 2020
Mailpets: For The Love Of Animals
The Mailgun Maverick Program Is Here!
Force for Change: It's Time to Speak Out
Which SMTP Port Should I Use? Understanding Ports 25, 465, & 587
Preparing Your Email Infrastructure Correctly
When Should You Use An Email API?
4 Tips To Improve Your Email Deliverability In 2020
Mailgun’s COVID-19 Plan of Action
What we've been up to: Mailgun's 2019 Year in Review
How Do Users on G2 Rate Mailgun?
Mailpets: For The Love Of Animals
Make Email Accessibility Your New Year’s Resolution
Sunset Policies: Allowing Unengaged Recipients to Ride Off into the Sunset
Email's Best of 2020
Catch-All Domain Support Is Now Available In Email Validations
The Best Time To Send Emails: Cracking The Code
Tips for Building Better Holiday Email Templates
Happy Festivus: Email Deliverability For The Holiday Season
The Basics of Email Subdomains
A Word of Caution For Laravel Developers
Make Email Accessibility Your New Year’s Resolution
Sunset Policies: Allowing Unengaged Recipients to Ride Off into the Sunset
Email's Best of 2020
How To Improve Email Open Rates
Preparing Your Email Infrastructure Correctly
4 Tips To Improve Your Email Deliverability In 2020
COVID-19 Email Communications Dos and Don’ts
How To Use Parallel Programming
Mailgun’s COVID-19 Plan of Action
Password Meters Are Not For Humans
Always be in the know and grab free email resources!
Mailgun is committed to protecting your privacy. Please read ourPrivacy Policybefore providing us with your details.