Sample code for 30+ languages & platforms
Ruby 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 Ruby Downloads

Ruby
require 'chilkat'

success = false

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

day = Chilkat::CkDateTime.new()
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)
        print http.lastErrorText() + "\n";
    else
        print "HTTP " + resp.get_StatusCode().to_s() + ": " + resp.bodyStr() + "\n";
    end

    exit
end

if (resp.get_StatusCode() != 200)
    print "HTTP " + resp.get_StatusCode().to_s() + ": " + resp.bodyStr() + "\n";
    exit
end

days = Chilkat::CkJsonArray.new()
success = days.Load(resp.bodyStr())
if (success != true)
    print "Unexpected response: expected JSON." + "\n";
    exit
end

print "Date,Requests,Delivered,Bounces,Blocks" + "\n";
row = Chilkat::CkJsonObject.new()
i = 0
while (i < days.get_Size())
    days.ObjectAt2(i,row)
    print row.stringOf("date") + "," + row.IntOf("stats[0].metrics.requests").to_s() + "," + row.IntOf("stats[0].metrics.delivered").to_s() + "," + row.IntOf("stats[0].metrics.bounces").to_s() + 
        "," + row.IntOf("stats[0].metrics.blocks").to_s() + "\n";
    i = i + 1
end