Campaigns

Unlike other email platforms Mailgun analytics is not limited to campaigns sent to the mailing lists. You can generate powerful reports and analytize data for any subset of your email traffic: just create an email campaign and specify that campaign’s ID when sending a message.

Below is the list of API calls for managing your campaigns and retreiving reports programmatically.

GET /<domain>/campaigns

Returns the list of the campaigns created for a given domain.

Parameter Description
limit Maximum number of records to return (100 by default). (optional)
skip Number of records to skip (0 by default). (optional)
GET /<domain>/campaigns/<id>

Returns a single campaign for a given domain.

POST /<domain>/campaigns

Creates a new campaign under a given domain. Note, that it will not create a new campaign, if the limit for account is reached - old campaigns must be deleted first.

Parameter Description
name Name of the new campaign
id Identifier to assign to this campaign. Will be autogenerated, if not provided. (optional)

Note

Supplied id must be pure ASCII and unique across all campaigns for a particular domain. Campaign name and campaign ID should not exceed the maximum length of 64 characters.

PUT /<domain>/campaigns/<id>

Updates existing campaign with a new name and/or new id.

Parameter Description
name New name to assign to the campaign. (optional)
id New identifier to assign to the campaign. (optional)

Note

Supplied id must be pure ASCII and unique across all campaigns for a particular domain. Campaign name and campaign ID should not exceed the maximum length of 64 characters.

DELETE /<domain>/campaigns/<id>

Deletes the given campaign with all its data.

Events

Campaign events include clicks, opens, unsubscribes, bounces and complaints for all receipients of the messages along with their region, country, etc.

The Campaign Events API allows you to retrieve the raw list of all message events for a given campaign to generate custom reports.

GET /<domain>/campaigns/<id>/events

Fetches the list of recently happened events for a given campaign.

Parameter Description
event Name of event to filter by - clicked, opened, unsubscribed, bounced, complained. (optional)
recipient Address of recipient to filter by. (optional)
country Two-letters country code to filter by. For example: US, RU. (optional)
region Name or code of region to filter by. For example, US states: CA, OH. (optional)
limit Maximum number of records to return (100 at most). (optional)
page Number of page to retrieve. (optional)
count Toggles whether to return actual data or just count of records. (optional)

Note

Filters can be chained. For example, if you want to retrieve events data for clicks and opens for a particular recipient, you can pass event=clicked&event=opened&recipient=user@domain.com.

Note

‘Delivered’ events are stored for 2 weeks only.

Stats

Campaign Stats API allows you to retrieve a campaign performance reports similar to what you can see in the control panel.

GET /<domain>/campaigns/<id>/stats

Fetches a summary of the results for a given campaign, like numbers of clicks, opens, etc. Includes unique numbers (for example, number of unique recipients who clicked) as well.

Parameter Description
groupby Grouping parameter - domain or daily_hour. (optional)

Note

Parameter daily_hour means that grouping performed only by hours, excluding day info.

Clicks

Aggregated clicks statistics for a campaign.

GET /<domain>/campaigns/<id>/clicks

Fetches clicks data aggregated by one or more parameters (ordered by totals).

Parameter Description
groupby Grouping parameter - link, recipient, domain, country, region, city, month, day, hour, minute, daily_hour.
country Two-digit country code to filter by. (optional)
region Name or code of region to filter by. For example, US states: CA, OH. (optional)
city Name of the city to filter by. For example, Chicago. (optional)
limit Maximum number of records to return (100 at most). (optional)
page Number of page to retrieve. (optional)
count Toggles whether to return actual data or just count of records. (optional)

Opens

Aggregated opens statistics for a campaign.

GET /<domain>/campaigns/<id>/opens

Fetches opens data aggregated by one or more parameters (ordered by totals).

Parameter Description
groupby Grouping parameter - recipient, domain, country, region, city, month, day, hour, minute, daily_hour.
country Two-digit country code to filter by. (optional)
region Name or code of region to filter by. For example, US states: CA, OH. (optional)
city Name of the city to filter by. For example, Chicago. (optional)
limit Maximum number of records to return (100 at most). (optional)
page Number of page to retrieve. (optional)
count Toggles whether to return actual data or just count of records. (optional)

Unsubscribes

Aggregated unsubscribes statistics for a campaign.

GET /<domain>/campaigns/<id>/unsubscribes

Fetches unsubscribes data aggregated by one or more parameters (ordered by totals).

Parameter Description
groupby Aggregation parameter - domain, country, region, city, month, day, hour, minute, daily_hour.
country Two-digit country code to filter by. (optional)
region Name or code of region to filter by. For example, US states: CA, OH. (optional)
city Name of the city to filter by. For example, Chicago. (optional)
limit Maximum number of records to return (100 at most). (optional)
page Number of page to retrieve. (optional)
count Toggles whether to return actual data or just count of records. (optional)

Complaints

Aggregated complaints statistics for a campaign.

GET /<domain>/campaigns/<id>/complaints

Fetches complaints data aggregated by one or more parameters (ordered by totals).

Parameter Description
groupby Aggregation parameter - recipient, domain, month, day, hour, minute, daily_hour.
limit Maximum number of records to return (100 at most). (optional)
page Number of page to retrieve. (optional)
count Toggles whether to return actual data or just count of records. (optional)

Basic Examples

Retrieve all campaigns for a domain:

curl -s --user 'api:YOUR_API_KEY' -G \
    https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/campaigns
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;

import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;

import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;

public class MGSample {

    // ...

    public static ClientResponse GetCampaigns() {

        Client client = ClientBuilder.newClient();
        client.register(HttpAuthenticationFeature.basic(
            "api",
            "YOUR_API_KEY"
        ));

        WebTarget mgRoot = client.target("https://api.mailgun.net/v3");

        return mgRoot
            .path("/{domain}/campaigns")
            .resolveTemplate("domain", "YOUR_DOMAIN_NAME")
            .queryParam("limit", 2)
            .request()
            .buildGet()
            .invoke(ClientResponse.class);
    }
}
# Include the Autoloader (see "Libraries" for install instructions)
require 'vendor/autoload.php';
use Mailgun\Mailgun;

# Instantiate the client.
$mgClient = new Mailgun('YOUR_API_KEY');
$domain = 'YOUR_DOMAIN_NAME';

# Issue the call to the client.
$result = $mgClient->get("$domain/campaigns", array('limit' => 5, 'skip' => 5));
def get_campaigns():
    return requests.get(
        "https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/campaigns",
        auth=('api', 'YOUR_API_KEY'))
def get_campaigns
  RestClient.get("https://api:YOUR_API_KEY"\
                 "@api.mailgun.net/v3/YOUR_DOMAIN_NAME/campaigns")
end
using System;
using System.IO;
using RestSharp;
using RestSharp.Authenticators;

public class GetCampaignsChunk
{

    public static void Main (string[] args)
    {
        Console.WriteLine (GetCampaigns ().Content.ToString ());
    }

    public static IRestResponse GetCampaigns ()
    {
        RestClient client = new RestClient ();
        client.BaseUrl = new Uri ("https://api.mailgun.net/v3");
        client.Authenticator =
            new HttpBasicAuthenticator ("api",
                                        "YOUR_API_KEY");
        RestRequest request = new RestRequest ();
        request.AddParameter ("domain", "YOUR_DOMAIN_NAME", ParameterType.UrlSegment);
        request.Resource = "{domain}/campaigns";
        request.AddParameter ("limit", 2);
        return client.Execute (request);
    }

}
// Not supported

Sample response:

{
  "total_count": 1,
  "items": [
      {
          "delivered_count": 924,
          "name": "Sample",
          "created_at": "Wed, 15 Feb 2012 11:31:17 GMT",
          "clicked_count": 135,
          "opened_count": 301,
          "submitted_count": 998,
          "unsubscribed_count": 44,
          "bounced_count": 20,
          "complained_count": 3,
          "id": "1",
          "dropped_count": 13
      }
  ]
}

Retrieve events history for a campaign:

curl -s --user 'api:YOUR_API_KEY' -G \
    https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/campaigns/my_campaign_id/events?limit=2
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;

import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;

import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;

public class MGSample {

    // ...

    public static ClientResponse GetCampaignEvents() {

        Client client = ClientBuilder.newClient();
        client.register(HttpAuthenticationFeature.basic(
            "api",
            "YOUR_API_KEY"
        ));

        WebTarget mgRoot = client.target("https://api.mailgun.net/v3");

        return mgRoot
            .path("/{domain}/campaigns/{campaign_id}/events")
            .resolveTemplate("domain", "YOUR_DOMAIN_NAME")
            .resolveTemplate("campaign_id", "YOUR_COMPAIGN_ID")
            .queryParam("limit", 2)
            .request()
            .buildGet()
            .invoke(ClientResponse.class);
    }
}
# Include the Autoloader (see "Libraries" for install instructions)
require 'vendor/autoload.php';
use Mailgun\Mailgun;

# Instantiate the client.
$mgClient = new Mailgun('YOUR_API_KEY');
$domain = 'YOUR_DOMAIN_NAME';
$campaignId = 'myexamplecampaign';

# Make the call to the client.
$result = $mgClient->get("$domain/campaigns/$campaignId/events", array(
    'skip'  => 0,
    'limit' => 50
));
def get_events_history():
    return requests.get(
        "https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/campaigns/my_campaign_id/events?limit=2",
        auth=('api', 'YOUR_API_KEY'))
def get_events_history
  RestClient.get("https://api:YOUR_API_KEY"\
                 "@api.mailgun.net/v3/YOUR_DOMAIN_NAME/campaigns/"\
                 "my_campaign_id/events?limit=2")
end
using System;
using System.IO;
using RestSharp;
using RestSharp.Authenticators;

public class GetCampaignEventsChunk
{

    public static void Main (string[] args)
    {
        Console.WriteLine (GetCampaignEvents ().Content.ToString ());
    }

    public static IRestResponse GetCampaignEvents ()
    {
        RestClient client = new RestClient ();
        client.BaseUrl = new Uri ("https://api.mailgun.net/v3");
        client.Authenticator =
            new HttpBasicAuthenticator ("api",
                                        "YOUR_API_KEY");
        RestRequest request = new RestRequest ();
        request.AddParameter ("domain", "YOUR_DOMAIN_NAME", ParameterType.UrlSegment);
        request.Resource = "{domain}/campaigns/my_campaign_id/events";
        request.AddParameter ("limit", 2);
        return client.Execute (request);
    }

}
// Not supported

Sample response:

[
  {
      "domain": "mailgun.net",
      "tags": [],
      "timestamp": "Wed, 15 Feb 2012 12:58:21 GMT",
      "recipient": "baz@example.com",
      "event": "delivered",
      "user_vars": {}
  },
  {
      "domain": "mailgun.net",
      "tags": [],
      "timestamp": "Wed, 15 Feb 2012 12:55:15 GMT",
      "recipient": "baz@example.com",
      "event": "delivered",
      "user_vars": {}
  }
]

Retrieve general stats for your campaign:

curl -s --user 'api:YOUR_API_KEY' -G \
    https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/campaigns/my_campaign_id/stats
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;

import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;

import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;

public class MGSample {

    // ...

    public static ClientResponse GetCampaignStats() {

        Client client = ClientBuilder.newClient();
        client.register(HttpAuthenticationFeature.basic(
            "api",
            "YOUR_API_KEY"
        ));

        WebTarget mgRoot = client.target("https://api.mailgun.net/v3");

        return mgRoot
            .path("/{domain}/campaigns/{campaign_id}/stats")
            .resolveTemplate("domain", "YOUR_DOMAIN_NAME")
            .resolveTemplate("campaign_id", "YOUR_CAMPAIGN_ID")
            .request()
            .buildGet()
            .invoke(ClientResponse.class);
    }
}
# Include the Autoloader (see "Libraries" for install instructions)
require 'vendor/autoload.php';
use Mailgun\Mailgun;

# Instantiate the client.
$mgClient = new Mailgun('YOUR_API_KEY');
$domain = 'YOUR_DOMAIN_NAME';
$campaignId = 'myexamplecampaign';

# Issue the call to the client.
$result = $mgClient->get("$domain/campaings/$campaignId/stats");
def get_campaign_stats():
    return requests.get(
        "https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/campaigns/my_campaign_id/stats",
        auth=('api', 'YOUR_API_KEY'))
def get_campaign_stats
  RestClient.get("https://api:YOUR_API_KEY"\
                 "@api.mailgun.net/v3/YOUR_DOMAIN_NAME/campaigns/"\
                 "my_campaign_id/stats")
end
using System;
using System.IO;
using RestSharp;
using RestSharp.Authenticators;

public class GetCampaignStatsChunk
{

    public static void Main (string[] args)
    {
        Console.WriteLine (GetCampaignStats ().Content.ToString ());
    }

    public static IRestResponse GetCampaignStats ()
    {
        RestClient client = new RestClient ();
        client.BaseUrl = new Uri ("https://api.mailgun.net/v3");
        client.Authenticator =
            new HttpBasicAuthenticator ("api",
                                        "YOUR_API_KEY");
        RestRequest request = new RestRequest ();
        request.Resource = "{domain}/campaigns/my_campaign_id/stats";
        request.AddParameter ("domain", "YOUR_DOMAIN_NAME", ParameterType.UrlSegment);
        return client.Execute (request);
    }

}
// Not supported

Sample response:

{
  "unique": {
      "clicked": {
          "link": 3,
          "recipient": 3
      },
      "opened": {
          "recipient": 3
      }
  },
  "total": {
      "complained": 0,
      "delivered": 67,
      "clicked": 6,
      "opened": 7,
      "dropped": 0,
      "bounced": 0,
      "sent": 67,
      "unsubscribed": 5
  }
}

Retrieve list of people who clicked (recipients who clicked the most come first):

curl -s --user 'api:YOUR_API_KEY' -G \
    -d "groupby=recipient&limit=2" \
    https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/campaigns/my_campaign_id/clicks
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;

import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;

import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;

public class MGSample {

    // ...

    public static ClientResponse GetClicks() {

        Client client = ClientBuilder.newClient();
        client.register(HttpAuthenticationFeature.basic(
            "api",
            "YOUR_API_KEY"
        ));

        WebTarget mgRoot = client.target("https://api.mailgun.net/v3");

        return mgRoot
            .path("/{domain}/campaigns/{campaign_id}/clicks")
            .resolveTemplate("domain", "YOUR_DOMAIN_NAME")
            .resolveTemplate("campaign_id", "YOUR_CAMPAIGN_ID")
            .queryParam("groupby", "recipient")
            .queryParam("limit", 2)
            .request()
            .buildGet()
            .invoke(ClientResponse.class);
    }
}
# Include the Autoloader (see "Libraries" for install instructions)
require 'vendor/autoload.php';
use Mailgun\Mailgun;

# Instantiate the client.
$mgClient = new Mailgun('YOUR_API_KEY');
$domain = 'YOUR_DOMAIN_NAME';
$campaignId = 'myexamplecampaign';

# Issue the call to the client.
$result = $mgClient->get("$domain/campaigns/$campaignId/clicks", array(
    'groupby' => 'recipient',
    'limit'   => 2
));
def get_clicks():
    return requests.get(
        "https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/campaigns/my_campaign_id/clicks?groupby=recipient&limit=2",
        auth=('api', 'YOUR_API_KEY'))
def get_clicks
  RestClient.get("https://api:YOUR_API_KEY"\
                 "@api.mailgun.net/v3/YOUR_DOMAIN_NAME/campaigns/"\
                 "my_campaign_id/clicks?groupby=recipient&limit=2")
end
using System;
using System.IO;
using RestSharp;
using RestSharp.Authenticators;

public class GetCampaignRecipientsWhoClickedChunk
{

    public static void Main (string[] args)
    {
        Console.WriteLine (GetCampaignClickStats ().Content.ToString ());
    }

    public static IRestResponse GetCampaignClickStats ()
    {
        RestClient client = new RestClient ();
        client.BaseUrl = new Uri ("https://api.mailgun.net/v3");
        client.Authenticator =
            new HttpBasicAuthenticator ("api",
                                        "YOUR_API_KEY");
        RestRequest request = new RestRequest ();
        request.AddParameter ("domain", "YOUR_DOMAIN_NAME", ParameterType.UrlSegment);
        request.Resource = "{domain}/campaigns/my_campaign_id/clicks";
        request.AddParameter ("groupby", "recipient");
        request.AddParameter ("limit", 2);
        return client.Execute (request);
    }

}
// Not supported

Sample response:

[
  {
      "total": 3,
      "unique": {
          "link": 3
      },
      "recipient": "alice@example.com"
  },
  {
      "total": 2,
      "unique": {
          "link": 2
      },
      "recipient": "foo@example.com"
  }
]

Advanced Examples

See your recipients activity during daily hours:

GET /<domain>/campaigns/<id>/stats?groupby=daily_hour

If your campaign’s recipients located in various regions (cities), you can see how’re different regions (cities) performing in general:

GET /<domain>/campaigns/<id>/stats?groupby=city
GET /<domain>/campaigns/<id>/stats?groupby=region

After determining the most performant region (city) you can get detailed statistics for it. For example, see recipients who opened your email in Chicago:

GET /<domain>/campaigns/<id>/opens?groupby=recipient&city=Chicago

Retrieve top 10 countries in which your campaign has been opened the most (of course, it is perfectly fine to replace ‘country’ with ‘region’ or ‘city’):

GET /<domain>/campaigns/<id>/opens?groupby=country&limit=10

Probably you want to know what is the most popular link in your campaign. It is as easy as:

GET /<domain>/campaigns/<id>/clicks?groupby=link

You can even turn ‘spy mode’ on and see who clicked which link:

GET /<domain>/campaigns/<id>/clicks?groupby=link&groupby=recipient