How to fetch campaign statistics using Mailgun API?

I’m trying to get campaign stats like click and open counts from Mailgun. I sent a test email with PHP and CodeIgniter. The email headers in Mailgun’s GUI show:

X-Mailgun-Tag: 3511
X-Mailgun-Campaign-Id: test-campaign-3511

Searching for “3511” works but “test-campaign-3511” doesn’t find the email. When I try to get campaign stats with PHP:

$result = $mgClient->get("$domain/campaigns/test-campaign-3511");

I get a 404 error saying “Campaign not found.” Trying without a campaign ID:

$result = $mgClient->get("$domain/campaigns");

This returns an empty result with a total_count of 0. Am I missing a configuration or a setting other than X-Mailgun-Campaign-Id?

I’ve encountered similar challenges when moving from Mailgun’s legacy campaign system to their current tag-based tracking mechanism. One important step is ensuring that you properly set the tag when sending your emails. Using the ‘o:tag’ parameter correctly is crucial. For example:

$result = $mgClient->post(“$domain/messages”, [
‘from’ => ‘Your Name [email protected]’,
‘to’ => ‘[email protected]’,
‘subject’ => ‘Test Email’,
‘text’ => ‘This is a test’,
‘o:tag’ => ‘test-campaign-3511’
]);

Then, to retrieve your stats, call the /stats/total endpoint with your tag filter:

$result = $mgClient->get(“$domain/stats/total”, [
‘event’ => ‘opened,clicked’,
‘duration’ => ‘30d’,
‘filter’ => ‘tag:test-campaign-3511’
]);

This approach should provide you with the desired open and click metrics. Just remember to also enable tracking in your Mailgun dashboard.

hey, i had a similar problem. mailgun changed stuff and now uses tags instead of campaigns. try this:

$result = $mgClient->get(“$domain/stats/total”, [
‘event’ => ‘opened,clicked’,
‘duration’ => ‘1m’,
‘filter’ => ‘tag:test-campaign-3511’
]);

make sure u add the tag when sending emails too. good luck!

It looks like you’re running into issues because Mailgun has moved away from campaigns to tags for tracking. Instead of using the campaigns endpoint, you should focus on tags.

Try using the Stats API with your tag. Something like this should work:

$result = $mgClient->get(\"$domain/stats/total\", [
    'event' => 'opened,clicked',
    'duration' => '1m',
    'tag' => 'test-campaign-3511'
]);

This will give you open and click stats for emails tagged with ‘test-campaign-3511’ over the last month. Make sure you’re actually setting the tag when sending emails using the ‘o:tag’ parameter. If you’re still not seeing results, double-check that tracking is enabled for your domain in the Mailgun dashboard.