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

CkPhp
<?php

include("chilkat.php");

$success = false;

//  Assumes Chilkat is unlocked. See Global Unlock Sample.
$success = false;
$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');
$resp = new CkHttpResponse();

$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) {
        print $http->lastErrorText() . "\n";
    }
    else {
        print 'HTTP ' . $resp->get_StatusCode() . ': ' . $resp->bodyStr() . "\n";
    }

    exit;
}

if ($resp->get_StatusCode() != 200) {
    print 'HTTP ' . $resp->get_StatusCode() . ': ' . $resp->bodyStr() . "\n";
    exit;
}

$days = new CkJsonArray();
$success = $days->Load($resp->bodyStr());
if ($success != true) {
    print 'Unexpected response: expected JSON.' . "\n";
    exit;
}

print 'Date,Requests,Delivered,Bounces,Blocks' . "\n";
$row = new CkJsonObject();
$i = 0;
while (($i < $days->get_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;
}


?>