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

Perl
use strict;
use warnings;
use Chilkat2;

# Assumes Chilkat is unlocked. See Global Unlock Sample.
my $success = 0;
my $http = Chilkat2::Http->new;
$http->RequireSslCertVerify(1);
# Supply your API key from protected configuration; AuthToken adds the Bearer prefix.
$http->AuthToken('SENDGRID_API_KEY');
my $resp = Chilkat2::HttpResponse->new;

my $day = Chilkat2::DateTime->new;
$day->SetFromCurrentSystemTime();
$day->AddDays(-1);
$http->SetUrlVar('end', $day->GetAsIso8601('YYYY-MM-DD', 0));
$day->AddDays(-6);
$http->SetUrlVar('start', $day->GetAsIso8601('YYYY-MM-DD', 0));

$success = $http->HttpNoBody('GET', 'https://api.sendgrid.com/v3/stats?start_date={$start}&end_date={$end}&aggregated_by=day', $resp);
if (!$success) {
    if ($resp->StatusCode == 0) {
        print $http->LastErrorText, "\n";
    } else {
        print 'HTTP ', $resp->StatusCode, ': ', $resp->BodyStr, "\n";
    }

    exit;
}

if ($resp->StatusCode != 200) {
    print 'HTTP ', $resp->StatusCode, ': ', $resp->BodyStr, "\n";
    exit;
}

my $days = Chilkat2::JsonArray->new;
$success = $days->Load($resp->BodyStr);
if (!$success) {
    print "Unexpected response: expected JSON.\n";
    exit;
}

print "Date,Requests,Delivered,Bounces,Blocks\n";
my $row = Chilkat2::JsonObject->new;
my $i = 0;
while ($i < $days->Size) {
    $days->ObjectAt2($i, $row);
    print $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'), "\n";
    $i = $i + 1;
}