How to Send Email using Mailgun PHP API

1. Create an account at Mailgun.com, you would get API Key and a sandbox domain for testing. You shall later add your custom domain too.


2. Create a sample project folder and install Composer. mailguntest is out project name, you can change as per your requirement.
>mkdir mailguntest
>cd mailguntest
>curl -sS https://getcomposer.org/installer | php
Once Composer is installed, add Mailgun PHP API / library too.
>php composer.phar require mailgun/mailgun-php:~1.7.1
I have used version 1.7.1, you can use any. see https://packagist.org/packages/mailgun/mailgun-php for details.

3. In mailguntest folder, create mailer.php file with below contents:
Update the code as per your mailgun code settings:
<?php 
require 'vendor/autoload.php';
use Mailgun\Mailgun;
$mg = new Mailgun("write your API key here");
$domain = "write-your-sandbox-domain for testing";
$mg->sendMessage($domain, array( 'from' => 'postmaster@write-your-sandbox-domain for testing', 'to' => 'write valid email address here', 'subject' => 'The PHP SDK is awesome!', 'text' => 'It is so simple to send a message.' )); ?>

4. Download cacert.pem from https://curl.haxx.se/ca/cacert.pem and place in wamp folder (or anywhere else, but note the path to enter in php.ini later)
Open php.ini file and replace #curl.cainfo to below line:
curl.cainfo = "C:\wamp\php\cacert.pem"
Place cacert.pem in mailguntest\vendor\guzzle\guzzle\src\Guzzle\Http\Resources too. Its required for SSL.


5. By default Mailgun do not allow to send emails from sandbox domain name, to use this address, you must add a recipient in your Mailgun account. For it, go to Account Settings > Authorized Recipients and add the email address where you want to send the email. As you add, an Mailgun send email to given address, open that email and click the link given in email. Now you can write this email address in 'to' parameter of sendMessage method used in above code.


6. Update the above code as per your Mailgun account settings and fetch the mailer.php file from your browser. It shall send the test email at your given address, if you have setup everything properly.

Comments

Post a Comment