The PHP SDK: the first of many official Mailgun SDKs

Today, we're happy to announce that for PHP developers, it's even easier to send messages with Mailgun! Over the past few weeks, we've been busy working on SDKs for the Mailgun API.  The SDK allows you to easily interact with our API by yanking all the boiler plate code necessary to interact with an HTTP web service. Today, we're releasing the PHP version of the SDK. Additional languages will follow soon.

For those not familiar with an SDK, let's first review what's required to send a message using the standard HTTP CURL library for PHP.

Sending a message with CURL:

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' => 'Dwight Schrute <dwight@example.com>',
                      'to' => 'Michael Scott <michael@example.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 will send a message using the Mailgun API, however, there's a lot of code there that, while important, is complicated, and unless you're a CURL expert, could be rather confusing.

Using our new SDK, we've managed to reduce the amount of code required to just a few lines.

Sending a message 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' => 'Dwight Schrute <dwight@example.com>', 
                             'to' => 'Michael Scott <michael@example.com>', 
                             'subject' => 'The Printer Caught Fire', 
                             'text' => 'We have a problem.'));

Obtaining Logs with the Mailgun PHP SDK:

# First, instantiate the SDK with your API credentials and  
define your domain.  
$mgClient = new Mailgun('key-3ax6xnjp29jd6fds4gc373sgvjxteol0');
$domain = 'samples.mailgun.org';

# Now, issue a get against the "log" resource URL. 
$result = $mgClient->get("$domain/log", array('limit' => 5, 'skip' => 0));

All HTTP actions return a response object which you can easily interact with.

# Obtain the HTTP response code. (e.g. 200)  
$responseCode = $result->http_response_code;

# Obtain the total count of results provided by the query. 
$responseBody = $result->http_response_body->total_count;

# Iterate through the results and echo the message IDs.
$logItems = $result->http_response_body->items;
for($logItems as $logItem){  
    echo $logItem->message_id . "\n";
}

If you'd like to get started using the SDK today, the code is available as a public repo on Github (mailgun-php).  You'll find ways to do everything you can do with the Mailgun API.  For additional usage examples, check out the README within the repository. We didn't stop there though... We've created a few utilities within the SDK.

Message Builder

Creating an array of parameters can be difficult for some code implementations, so we've included a class that allows you to make method calls that automatically build a properly formed array of message parameters.

Sending a message with Mailgun PHP SDK + Message Builder:

# First, instantiate the SDK with your API credentials and define  
your domain.  
$mgClient = new Mailgun("key-example");
$domain = "example.com";

# Next, instantiate a Message Builder object from the SDK.
$msgBldr = $mgClient->MessageBuilder();

# Define the from address.
$msgBldr->setFromAddress("dwight@example.com", 
                         array("first"=>"Dwight", "last" => "Schrute")); 
# Define a to recipient. 
$msgBldr->addToRecipient("michael@example.com", 
                         array("first" => "Michael", "last" => "Scott")); 
# Define a cc recipient. 
$msgBldr->addCcRecipient("pam@example.com", 
                         array("first" => "Pam", "last" => "Beesly")); 
# Define the subject. 
$msgBldr->setSubject("Help!"); 
# Define the body of the message. 
$msgBldr->setTextBody("The printer is on fire."); 

# Other Optional Parameters. 
$msgBldr->addCampaignId("Sabre-Printer-Fire"); 
$msgBldr->addCustomHeader("Customer-Id", "12345"); 
$msgBldr->addAttachment("@/sabre.jpg"); 
$msgBldr->setDeliveryTime("tomorrow 8:00AM", "PST"); 

# Finally, send the message. 
$mgClient->post('{$domain}/messages', $msgBldr->getMessage());

For a list of all available functions, check out the list on Github.

Batch Message

In addition to Message Builder, we have Batch Message. This class allows you to build a message and submit a template message in batches, up to 1,000 recipients per post. The benefit of using this class is that the recipients tally is monitored and will automatically submit the message to the endpoint when you've added the 1,000th recipient. This means you can build your message and begin iterating through your database. Forget about sending the message, the SDK will keep track of posting to the API when necessary.

Sending a message with Mailgun PHP SDK + Batch Message:

# First, instantiate the SDK with your API credentials and define  
your domain.  
$mgClient = new Mailgun("key-example");
$domain = "example.com";

# Next, instantiate a Message Builder object from the SDK, pass in your 
sending domain.  
$batchMsg = $mgClient->BatchMessage($domain);

# Define the from address.
$batchMsg->setFromAddress("dwight@example.com", 
                          array("first"=>"Dwight", "last" => "Schrute"));
# Define the subject. 
$batchMsg->setSubject("Help!");
# Define the body of the message.
$batchMsg->setTextBody("The printer is on fire!");

# Next, let's add a few recipients to the batch job.
$batchMsg->addToRecipient("pam@example.com", 
                          array("first" => "pam", "last" => "Beesly"));
$batchMsg->addToRecipient("jim@example.com", 
                          array("first" => "Jim", "last" => "Halpert"));
$batchMsg->addToRecipient("andy@example.com", 
                          array("first" => "Andy", "last" => "Bernard"));
...etc...etc...
// After 1,000 recipeints, Batch Message will automatically post your message 
to the messages endpoint. 

// Call finalize() to send any remaining recipients still in the buffer.
$batchMsg->finalize();

As you can see, Batch Message actually extends Message Builder. All functions available in Message Builder are available in Batch Message. Check out the full documentation on Github.

Opt-In Handler

Finally, we have built a simple double opt-in handler to help you generate unique opt-in links. The opt-in handler also uses our free address validation service to validate the accuracy of the email addresses.

The typical flow for using this class would be as follows:
Recipient Requests Subscribe -> [Validate Recipient Address] -> [Generate Opt In Link] -> [Email Recipient Opt In Link]
Recipient Clicks Opt In Link -> [Validate Opt In Link] -> [Subscribe User] -> [Send final confirmation]

It is best to use this class for your website subscription forms, so you'll need a web server accessible to the internet to handle the validation link click.

Since each implementation will be rather unique, see the Github documentation for usage examples of this class.

Let us know what you think.  Is there something else you'd like to see in the SDK?  Or something you love. We'd appreciate your feedback!

Happy emailing,

The Mailgunners

 

comments powered by Disqus

Mailgun Get posts by email

Like what you're reading? Get these posts delivered to your inbox.

No spam, ever.