Sample code for 30+ languages & platforms
CkJava Requires Chilkat v11.0.0+

SendGrid: Report daily requests, deliveries, bounces, and blocks

See more SendGrid Examples

Retrieve seven completed UTC dates and print one row per date. The counts are account-level aggregates; a day’s delivered count does not identify which messages sent that day were delivered.

Global email statistics

Chilkat CkJava Downloads

CkJava
import com.chilkatsoft.*;

public class ChilkatExample {

  static {
    try {
        System.loadLibrary("chilkat");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load.\n" + e);
      System.exit(1);
    }
  }

  public static void main(String argv[])
  {
    boolean success = false;

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    success = false;
    CkHttp http = new CkHttp();
    http.put_RequireSslCertVerify(true);
    //  Supply your API key from protected configuration; AuthToken adds the Bearer prefix.
    http.put_AuthToken("SENDGRID_API_KEY");
    CkHttpResponse resp = new CkHttpResponse();

    CkDateTime day = new CkDateTime();
    day.SetFromCurrentSystemTime();
    day.AddDays(-1);
    http.SetUrlVar("end",day.getAsIso8601("YYYY-MM-DD",false));
    day.AddDays(-6);
    http.SetUrlVar("start",day.getAsIso8601("YYYY-MM-DD",false));

    success = http.HttpNoBody("GET","https://api.sendgrid.com/v3/stats?start_date={$start}&end_date={$end}&aggregated_by=day",resp);
    if (success != true) {
        if (resp.get_StatusCode() == 0) {
            System.out.println(http.lastErrorText());
            }
        else {
            System.out.println("HTTP " + resp.get_StatusCode() + ": " + resp.bodyStr());
            }

        return;
        }

    if (resp.get_StatusCode() != 200) {
        System.out.println("HTTP " + resp.get_StatusCode() + ": " + resp.bodyStr());
        return;
        }

    CkJsonArray days = new CkJsonArray();
    success = days.Load(resp.bodyStr());
    if (success != true) {
        System.out.println("Unexpected response: expected JSON.");
        return;
        }

    System.out.println("Date,Requests,Delivered,Bounces,Blocks");
    CkJsonObject row = new CkJsonObject();
    int i = 0;
    while ((i < days.get_Size())) {
        days.ObjectAt2(i,row);
        System.out.println(row.stringOf("date") + "," + row.IntOf("stats[0].metrics.requests") + "," + row.IntOf("stats[0].metrics.delivered") + "," + row.IntOf("stats[0].metrics.bounces")
             + "," + row.IntOf("stats[0].metrics.blocks"));
        i = i+1;
        }
  }
}