Stats

Mailgun collects many different events and generates event statistics which are available in your Control Panel. This data is also available via an API.

The statistics are calculated in hourly, daily and monthly resolution in UTC timezone.

The following retention policy is applied to the statistics:

  • Hourly stats are preserved for a month.
  • Daily stats are preserved for a year.
  • Monthly stats are stored throughout the lifespan of the domain.
GET /<domain>/stats/total

Returns total stats for a given domain.

Parameter Description
event The type of the event. For a complete list of all events written to the log see the Event Types table below. (Required)
start The starting time. Should be in RFC 2822#page-14 or unix epoch format. Default: 7 days from the current time.
end The ending date. Should be in RFC 2822#page-14 or unix epoch format. Default: current time.
resolution Can be either hour, day or month. Default: day
duration Period of time with resoluton encoded. See Duration for more info. If provided, overwrites the start date.
GET /<domain>/stats

Returns a list of event stats items. Each record represents counts for one event per one day.

Warning

This is the legacy API that should not be used.

Parameter Description
limit Maximum number of records to return. (100 by default)
skip Number of records to skip. (0 by default)
event Name of the event to receive the stats for. Note that you can specify this parameter multiple times to fetch stats for several events at the same time (see example below)
start-date The date to receive the stats starting from. Should have ISO8601 format (YYYY-MM-DD).

Duration

Duration is a string that represents a period of time with some resolution. It has a format [0-9]+[m,d,h] where

  • h - an hour
  • d - a day
  • m - a month

Examples:

  • 24h - a period of 24 hours (a day) with hourly resolution
  • 1d - a period of 1 day with daily resolution
  • 2m - a period of 2 months with monthly resolution

Event Types

Mailgun tracks all of the events that occur throughout the system. Below are listed the events that you can retrieve using this API.

Event Type Description
accepted Mailgun accepted the request to send/forward the email and the message has been placed in queue.
delivered Mailgun sent the email and it was accepted by the recipient email server.
failed Mailgun could not deliver the email to the recipient email server.
opened The email recipient opened the email and enabled image viewing. Open tracking must be enabled in the Mailgun control panel, and the CNAME record must be pointing to mailgun.org.
clicked The email recipient clicked on a link in the email. Click tracking must be enabled in the Mailgun control panel, and the CNAME record must be pointing to mailgun.org.
unsubscribed The email recipient clicked on the unsubscribe link. Unsubscribe tracking must be enabled in the Mailgun control panel.
complained The email recipient clicked on the spam complaint button within their email client. Feedback loops enable the notification to be received by Mailgun.
stored Mailgun has stored an incoming message

Examples

Get stats for ‘accepted’ and ‘delivered’ and ‘failed’ events for the past month:

curl -s --user 'api:YOUR_API_KEY' -G \
   https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/stats/total \
   -d event='accepted' \
   -d event='delivered' \
   -d event='failed' \
   -d duration='1m'
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;

public class MGSample {

    // ...

    public static JsonNode getStats() throws UnirestException {

        HttpResponse<JsonNode> request = Unirest.get("https://api.mailgun.net/v3/" + YOUR_DOMAIN_NAME + "/stats/total")
            .basicAuth("api", API_KEY)
            .queryString("event", "accepted")
            .queryString("event", "delivered")
            .queryString("event", "failed")
            .queryString("duration","1m")
            .asJson();

        return request.getBody();
    }
}
# 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/stats/total", array(
    'event' => array('accepted', 'delivered', 'failed'),
    'duration' => '1m'
));
def get_stats():
    return requests.get(
        "https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/stats/total",
        auth=("api", "YOUR_API_KEY"),
        params={"event": ["accepted", "delivered", "failed"],
                "duration": "1m"})
def get_stats
  url_params = {}
  url_params[:duration] = "1m"
  url_params[:event] = []
  url_params[:event] << "accepted"
  url_params[:event] << "delivered"
  url_params[:event] << "failed"
  query_string = url_params.collect {|k, v| "#{k.to_s}=#{CGI::escape(v.to_s)}"}.
    join("&")
  RestClient.get "https://api:YOUR_API_KEY"\
  "@api.mailgun.net/v3/YOUR_DOMAIN_NAME/stats/total?#{query_string}"
end
using System;
using System.IO;
using RestSharp;
using RestSharp.Authenticators;

public class GetStatsChunk
{

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

    public static IRestResponse GetStats ()
    {
        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}/stats/total";
        request.AddParameter ("event", "accepted");
        request.AddParameter ("event", "delivered");
        request.AddParameter ("event", "failed");
        request.AddParameter ("duration", "1m");
        return client.Execute (request);
    }

}
// Not supported yet.
var DOMAIN = 'YOUR_DOMAIN_NAME';
var mailgun = require('mailgun-js')({ apiKey: "YOUR_API_KEY", domain: DOMAIN });

mailgun.get(`/${DOMAIN}/stats/total`, {"event": 'accepted', "event": 'delivered', "event": 'failed', "duration": '1m'}, function (error, body) {
  console.log(body);
});

Sample response:

{
  "end": "Fri, 01 Apr 2012 00:00:00 UTC",
  "resolution": "month",
  "start": "Tue, 14 Feb 2012 00:00:00 UTC",
  "stats": [
    {
      "time": "Tue, 14 Feb 2012 00:00:00 UTC",
      "accepted": {
        "total": "15",
        "outgoing": 10,  // authenticated
        "incoming": 5    // unauthenticated
      },
      "delivered": {
          "total": 20,
          "smtp": 15,  // delivered over SMTP
          "http": 5    // delivered over HTTP
      },
      "failed": {
        "permanent": {
          "suppress-bounce": 1,       // recipients addresses previously bounced
          "suppress-unsubscribe": 2,  // recipients previously unsubscribed
          "suppress-complaint": 3,    // recipients previously complained
          "bounce": 7,
          "total": 10                 // failed permanently and dropped
        },
        "temporary": {
          "espblock": 1   // failed temporary due to ESP block, will be retried
        }
      },
    }
  ]
}