Mailgun makes sending email from code dead simple. In this post, I’ll run through the basics of sending email using Python and the Mailgun API. I’ll also explore email tracking, one of the extras that you get from using Mailgun. To get started, you’ll need a Mailgun account - sign up here if you don’t already have an account. You’ll need a few pieces of information from the Mailgun control panel before moving forward:
- API Key
- Sandbox Domain URL
Both of these pieces of information can be found on the landing page of the Mailgun control panel. You’ll also need the following software installed on your system:
- Python 2.6 or higher
Sending Your First Email
Now that you have all the necessary prerequisites, let’s dive straight into the code:
If you run the Python script from your terminal, you’ll receive an email in just a few minutes. This only scratches the surface of what the Mailgun API provides. For more information, check out the Messages section of the Mailgun API.
Tracking Email Delivery
We’re successfully sending emails, so let’s see if they are actually being delivered. Mailgun provides the Events API for exactly this purpose.
Run the Python script from your terminal, and you’ll see the last five events that your emails have generated as they move through the system. In addition to exploring events through the API, visit the Tracking section of the control panel. To learn more about events, check out the section on Tracking Messages in Mailgun’s documentation.
As you’ve seen, Mailgun makes sending email programmatically easy. If you are interested in learning more, I encourage you to check out the rest of the Mailgun documentation. They offer many other useful features such as handling unsubscribe requests, scheduling delivery, and much more.