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 web.
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.
cd /var/www/html
mkdir mailgun-php
cd mailgun-php
(changes directory)curl -sS https://getcomposer.org/installer | php
Composer, when 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.
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. All the examples below assume you’ve already included this in your file:
<?php
require 'vendor/autoload.php';
use Mailgun\Mailgun;
?>
Then, follow these instructions from the official documentation to send a message using the SDK:
<?php
// First, instantiate the SDK with your API credentials
$mg = Mailgun::create('key-example'); // For US servers
$mg = Mailgun::create('key-example', 'https://api.eu.mailgun.net'); // For EU servers
// Now, compose and send your message.
// $mg->messages()->send($domain, $params);
$mg->messages()->send('example.com', [
'from' => 'bob@example.com',
'to' => 'sally@example.com',
'subject' => 'The PHP SDK is awesome!',
'text' => 'It is so simple to send a message.'
]);
?>
Remember: $domain
must match to the domain you have configured on app.mailgun.com.
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:
mkdir swiftmailer, cd swiftmailer
curl -sS https://getcomposer.org/installer | php
php composer.phar require swiftmailer/swiftmailer @stable
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.
<?php
require 'vendor/autoload.php';
// Create the Transport
$transport = Swift_SmtpTransport::newInstance('smtp.mailgun.org', 25)
->setUsername('your SMTP username')
->setPassword('your SMTP password')
;
// Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
// Create a message
$message = Swift_Message::newInstance('Hello from Mailgun')
->setFrom(array('someone@domain.com' => 'John Doe'))
->setTo(array('someone_else@domain.org', 'third_contact@domain.org' => 'A third name'))
->setBody("And that's another ace in the hole for the Mailgun dev!")
;
// Send the message
$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.
phpmailer
mkdir phpmailer
cd phpmailer
phpmailer
and its dependencies
curl -sS https://getcomposer.org/installer | php
php composer.phar require phpmailer/phpmailer:5.2.8
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.
<?php
//Composer's autoload file loads all necessary files
require 'vendor/autoload.php';
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.mailgun.org'; // Specify mailgun SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'username@domain.com'; // SMTP username from https://mailgun.com/cp/domains
$mail->Password = 'myp@55w0rd'; // SMTP password from https://mailgun.com/cp/domains
$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl'
$mail->From = 'sender@domain.com'; // The FROM field, the address sending the email
$mail->FromName = 'Orlie'; // The NAME field which will be displayed on arrival by the email client
$mail->addAddress('recipient@domain.net', 'BOB'); // Recipient's email address and optionally a name to identify him
$mail->isHTML(true); // Set email to be sent as HTML, if you are planning on sending plain text email just set it to false
// The following is self explanatory
$mail->Subject = 'Email sent with Mailgun';
$mail->Body = '<span style="color: red">Mailgun rocks</span>, thank you <em>phpmailer</em> for making emailing easy using this <b>tool!</b>';
$mail->AltBody = 'Mailgun rocks, shame you can't see the html sent with phpmailer so you're seeing this instead';
if(!$mail->send()) {
echo "Message hasn't been sent.";
echo 'Mailer Error: ' . $mail->ErrorInfo . "n";
} else {
echo "Message has been sent n";
}
?>
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!