• What's new

The PHP SDK: The First Of Many Official Mailgun SDKs

Mailgun Team
5 min read

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:

1 function send_simple_message() {
2 $ch = curl_init();
4 curl_setopt($ch, CURLOPT_USERPWD, 'api:key-example');
5 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
6 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
7 curl_setopt($ch, CURLOPT_URL,
8 'https://api.mailgun.net/v2/samples.mailgun.org/messages');
9 curl_setopt($ch, CURLOPT_POSTFIELDS,
10 array('from' => 'Dwight Schrute <dwight@example.com>',
11 'to' => 'Michael Scott <michael@example.com>',
12 'subject' => 'The Printer Caught Fire',
13 'text' => 'We have a problem.'));
14 $result = curl_exec($ch);
15 curl_close($ch);
16 return $result;
17 }
18 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:

1 # First, instantiate the SDK with your API credentials and define your domain.
2 $mgClient = new Mailgun("key-example");
3 $domain = "example.com";
5 # Now, compose and send your message.
6 $mgClient->sendMessage($domain,
7 array('from' => 'Dwight Schrute <dwight@example.com>',
8 'to' => 'Michael Scott <michael@example.com>',
9 'subject' => 'The Printer Caught Fire',
10 'text' => 'We have a problem.'));

Obtaining Logs with the Mailgun PHP SDK:

1 # First, instantiate the SDK with your API credentials and
2 define your domain.
3 $mgClient = new Mailgun('key-3ax6xnjp29jd6fds4gc373sgvjxteol0');
4 $domain = 'samples.mailgun.org';
6 # Now, issue a get against the "log" resource URL.
7 $result = $mgClient->get("$domain/log", array('limit' => 5, 'skip' => 0));

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

1 # Obtain the HTTP response code. (e.g. 200)
2 $responseCode = $result->http_response_code;
4 # Obtain the total count of results provided by the query.
5 $responseBody = $result->http_response_body->total_count;
7 # Iterate through the results and echo the message IDs.
8 $logItems = $result->http_response_body->items;
9 for($logItems as $logItem){
10echo $logItem->message_id . "n";
11 }

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:

1 # First, instantiate the SDK with your API credentials and define
2 your domain.
3 $mgClient = new Mailgun("key-example");
4 $domain = "example.com";
6 # Next, instantiate a Message Builder object from the SDK.
7 $msgBldr = $mgClient->MessageBuilder();
9 # Define the from address.
10 $msgBldr->setFromAddress("dwight@example.com",
11 array("first"=>"Dwight", "last" => "Schrute"));
12 # Define a to recipient.
13 $msgBldr->addToRecipient("michael@example.com",
14 array("first" => "Michael", "last" => "Scott"));
15 # Define a cc recipient.
16 $msgBldr->addCcRecipient("pam@example.com",
17 array("first" => "Pam", "last" => "Beesly"));
18 # Define the subject.
19 $msgBldr->setSubject("Help!");
20 # Define the body of the message.
21 $msgBldr->setTextBody("The printer is on fire.");
23 # Other Optional Parameters.
24 $msgBldr->addCampaignId("Sabre-Printer-Fire");
25 $msgBldr->addCustomHeader("Customer-Id", "12345");
26 $msgBldr->addAttachment("@/sabre.jpg");
27 $msgBldr->setDeliveryTime("tomorrow 8:00AM", "PST");
29 # Finally, send the message.
30 $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:

1 # First, instantiate the SDK with your API credentials and define
2 your domain.
3 $mgClient = new Mailgun("key-example");
4 $domain = "example.com";
6 # Next, instantiate a Message Builder object from the SDK, pass in your
7 sending domain.
8 $batchMsg = $mgClient->BatchMessage($domain);
10 # Define the from address.
11 $batchMsg->setFromAddress("dwight@example.com",
12 array("first"=>"Dwight", "last" => "Schrute"));
13 # Define the subject.
14 $batchMsg->setSubject("Help!");
15 # Define the body of the message.
16 $batchMsg->setTextBody("The printer is on fire!");
18 # Next, let's add a few recipients to the batch job.
19 $batchMsg->addToRecipient("pam@example.com",
20 array("first" => "pam", "last" => "Beesly"));
21 $batchMsg->addToRecipient("jim@example.com",
22 array("first" => "Jim", "last" => "Halpert"));
23 $batchMsg->addToRecipient("andy@example.com",
24 array("first" => "Andy", "last" => "Bernard"));
25 ...etc...etc...
26 // After 1,000 recipeints, Batch Message will automatically post your message
27 to the messages endpoint.
29 // Call finalize() to send any remaining recipients still in the buffer.
30 $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.

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 sending,

The Mailgunners


Learn about our Deliverability Services

Looking to send a high volume of emails? Our email experts can supercharge your email performance. See how we've helped companies like Lyft, Shopify, Github increase their email delivery rates to an average of 97%.

Learn More

Last updated on October 09, 2020

  • Related posts
  • Recent posts
  • Top posts
View all

Always be in the know and grab free email resources!

No spam, ever. Only musings and writings from the Mailgun team.

By sending this form, I agree that Mailgun may contact me and process my data in accordance with its Privacy Policy.

sign up
It's easy to get started. And it's free.
See what you can accomplish with the world's best email delivery platform.
Sign up for Free