Welcome to this comprehensive guide on exporting Mailgun logs using the Mailgun API. You might be wondering how you can retrieve data from Mailgun without going through the user interface. Mailgun doesn’t allow us to export logs/events using the UI, so we’ll need to do it via API. This post will walk you through a simple process to achieve this goal and automate your log export tasks.
Understanding the Mailgun API
Mailgun provides an API which allows us to interact with its services programmatically. To authenticate with the API, we set it to basic auth, set the username as api
, and use the private API key as password.
The API Endpoint
The endpoint to retrieve events is as follows:
https://api.[eu.]mailgun.net/v3/{domain}/events
The [eu.]
is for European customers, and {domain}
is your Mailgun domain, which is usually something like mail.example.com
【5†source】.
Retrieving Specific Events
What if we want to retrieve logs for specific events, such as emails that were delivered, opened, or failed? We can filter events by updating the request to:
https://api.[eu.]mailgun.net/v3/{domain}/events?event={event_type}&limit=300
Where {event_type}
can be replaced with delivered
, opened
, or failed
【6†source】.
Exporting Mailgun Logs to CSV
Now, let’s dive into how to export Mailgun logs to a CSV file using PHP. We will create a PHP script that retrieves events from Mailgun and exports them to a CSV file. Here’s how it works:
- Initialize the necessary variables. We specify the API key, the domain, and the base URL for the API. The API key and domain are unique to your Mailgun account, and you need to replace them with your own.
- Iterate over the event types. For each event type, we construct the URL for the API request.
- Set up the stream context for Basic Auth. This includes the header for Authorization which is the base64 encoded string of “api:” and your API key.
- Get the JSON response. We use
file_get_contents
to send a GET request to the API and get the JSON response. - Process the items from the response. For each item in the response, we get the email address from the headers, initialize the event statuses (delivered, opened, failed) if necessary, and set the event status for this email.
- Write the data to a CSV file. We open a CSV file for writing, write the headers, and then write the data for each email.
Here is the full PHP script:
<?php
// Replace with your own Mailgun API key and domain
$api_key = "{MAILGUN_API_KEY}";
$domain = "{MAILGUN_DOMAIN}";
$base_url = "https://api.eu.mailgun.net/v3/";
$event_types = ["delivered", "opened", "failed"];
$emails = [];
$email_ids = [];
$next_id = 1;
// Rest of the code as shown above
?>
Remember to replace {MAILGUN_API_KEY}
and {MAILGUN_DOMAIN}
with your own Mailgun API key# Quoting the final code quote(“Here is the full PHP script:”, “remember to replace “{MAILGUN_API_KEY}” and “{MAILGUN_DOMAIN}” with your own Mailgun API key and domain. You can also adjust the event types and the limit of events per request.”)
<?php
// Replace with your own Mailgun API key and domain
$api_key = "{MAILGUN_API_KEY}";
$domain = "{MAILGUN_DOMAIN}";
$base_url = "https://api.eu.mailgun.net/v3/";
$event_types = ["delivered", "opened", "failed"];
$emails = [];
$email_ids = [];
$next_id = 1;
foreach ($event_types as $event) {
$url = $base_url . $domain . "/events?event=" . $event . "&limit=300";
$auth = base64_encode("api:" . $api_key);
$context = stream_context_create(
[
"http" => [
"header" => "Authorization: Basic " . $auth
]
]
);
do {
$response_json = file_get_contents($url, false, $context);
$response = json_decode($response_json);
foreach ($response->items as $item) {
$email = $item->message->headers->from;
if (!array_key_exists($email, $emails)) {
$emails[$email] = ["id" => $next_id++, "email" => $email, "delivered" => 0, "opened" => 0, "failed" => 0];
}
$emails[$email][$event]++;
if (!array_key_exists($email, $email_ids)) {
$email_ids[$email] = $emails[$email]["id"];
}
}
$url = $response->paging->next;
} while (count($response->items) > 0);
}
$file = fopen("mailgun_logs.csv", "w");
fputcsv($file, ["id", "email", "delivered", "opened", "failed"]);
foreach ($emails as $email) {
fputcsv($file, $email);
}
fclose($file);
?>
How to Use This Script
- Get your Mailgun API key and domain: These are unique to your Mailgun account, and you need to replace
{MAILGUN_API_KEY}
and{MAILGUN_DOMAIN}
with your own. - Set your event types: The event types are currently set to
"delivered"
,"opened"
, and"failed"
. You can modify this to suit your needs. - Run the script: After replacing the API key and domain with your own and setting the event types, you can run the script. It will retrieve events from Mailgun and export them to a CSV file named
mailgun_logs.csv
.
This script provides a simple way to export Mailgun logs to a CSV file. By using the Mailgun API, we can automate the process and retrieve the data we need efficiently and easily.
The code provided here is a starting point and can be modified to suit your specific needs. If you run into any issues or have any questions, feel free to leave a comment below. Happy coding!