Back

Step by Step Guide to Building a Mailgun API Integration in PHP

Aug 14, 20247 minute read

Introduction

Hey there, fellow developer! Ready to supercharge your PHP application with some email-sending goodness? Look no further than Mailgun, the email service provider that's got your back. In this guide, we'll walk through integrating Mailgun into your PHP project using their official mailgun/mailgun-php package. Buckle up, it's going to be a smooth ride!

Prerequisites

Before we dive in, make sure you've got:

  • A PHP environment (you're a PHP dev, so I'm sure you've got this covered)
  • Composer installed (because who doesn't love dependency management?)
  • A Mailgun account with API credentials (if you don't have one, go grab it – it's free to start!)

Installation

Let's kick things off by installing the Mailgun PHP package. Fire up your terminal and run:

composer require mailgun/mailgun-php php-http/guzzle6-adapter php-http/message

This command will pull in the Mailgun package and its dependencies. Easy peasy!

Configuration

Now, let's set up our Mailgun client. Grab your API key and domain from your Mailgun dashboard, and let's get configuring:

use Mailgun\Mailgun; $mg = Mailgun::create('your-api-key'); $domain = "your-domain.com";

Just like that, we're ready to start sending emails!

Sending a Simple Email

Let's send our first email. It's as simple as:

$mg->messages()->send($domain, [ 'from' => 'Excited User <[email protected]>', 'to' => '[email protected]', 'subject' => 'Hello', 'text' => 'Testing some Mailgun awesomeness!' ]);

Boom! You've just sent your first email through Mailgun. How's that for a quick win?

Advanced Features

Attachments

Got files to send? No problem! Here's how you add attachments:

$mg->messages()->send($domain, [ 'from' => 'Excited User <[email protected]>', 'to' => '[email protected]', 'subject' => 'Hello', 'text' => 'Testing some Mailgun awesomeness!', 'attachment' => [ ['filePath' => '/path/to/file.jpg', 'filename' => 'photo.jpg'] ] ]);

Templates

Mailgun supports templates, making your emails look slick and professional:

$mg->messages()->send($domain, [ 'from' => 'Excited User <[email protected]>', 'to' => '[email protected]', 'subject' => 'Hello', 'template' => 'your-template-name', 'h:X-Mailgun-Variables' => json_encode(['name' => 'Bob']) ]);

Scheduling

Want to send emails in the future? Mailgun's got you covered:

$mg->messages()->send($domain, [ 'from' => 'Excited User <[email protected]>', 'to' => '[email protected]', 'subject' => 'Hello', 'text' => 'This email was scheduled!', 'o:deliverytime' => 'Fri, 14 Oct 2022 23:10:10 -0000' ]);

Handling Responses and Errors

Mailgun returns responses for all API calls. Here's how to handle them:

try { $result = $mg->messages()->send($domain, [...]); echo "Message sent: " . $result->getId(); } catch (\Exception $e) { echo "Error sending message: " . $e->getMessage(); }

Always wrap your API calls in try-catch blocks. Trust me, your future self will thank you!

Webhooks Integration

Mailgun can notify your app about email events via webhooks. Here's a simple webhook handler:

$payload = json_decode(file_get_contents('php://input'), true); if ($payload['event'] === 'delivered') { // Handle successful delivery } elseif ($payload['event'] === 'bounced') { // Handle bounce }

Remember to verify the webhook signature for security!

Testing

Mailgun provides a sandbox domain for testing. Use it like this:

$mg = Mailgun::create('your-test-api-key'); $domain = "your-test-domain.mailgun.org";

For unit tests, consider mocking the Mailgun client to avoid hitting the API during tests.

Best Practices and Optimization

  • Respect Mailgun's rate limits (they're generous, but they exist)
  • Use batch sending for large volumes of emails
  • Keep an eye on your analytics to optimize delivery rates

Conclusion

And there you have it! You're now equipped to send emails like a pro using Mailgun and PHP. Remember, the Mailgun documentation is your friend for diving deeper into specific features.

Now go forth and send those emails! Your users are waiting to hear from you. Happy coding!