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

PowerShell
Add-Type -Path "C:\chilkat\ChilkatDotNet47-x64\ChilkatDotNet47.dll"

$success = $false

#  Assumes Chilkat is unlocked. See Global Unlock Sample.
$success = $false
$http = New-Object Chilkat.Http
$http.RequireSslCertVerify = $true
#  Supply your API key from protected configuration; AuthToken adds the Bearer prefix.
$http.AuthToken = "SENDGRID_API_KEY"
$resp = New-Object Chilkat.HttpResponse

$day = New-Object Chilkat.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 -ne $true) {
    if ($resp.StatusCode -eq 0) {
        $($http.LastErrorText)
    }
    else {
        $("HTTP " + $resp.StatusCode + ": " + $resp.BodyStr)
    }

    exit
}

if ($resp.StatusCode -ne 200) {
    $("HTTP " + $resp.StatusCode + ": " + $resp.BodyStr)
    exit
}

$days = New-Object Chilkat.JsonArray
$success = $days.Load($resp.BodyStr)
if ($success -ne $true) {
    $("Unexpected response: expected JSON.")
    exit
}

$("Date,Requests,Delivered,Bounces,Blocks")
$row = New-Object Chilkat.JsonObject
$i = 0
while (($i -lt $days.Size)) {
    $days.ObjectAt2($i,$row)
    $($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
}