From 724454ca725478f7891794639e36ffc1f38ff740 Mon Sep 17 00:00:00 2001 From: Jeremy Jung Date: Mon, 30 Oct 2017 20:10:26 -0700 Subject: [PATCH] Add Email Statistics helper example --- USE_CASES.md | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/USE_CASES.md b/USE_CASES.md index 6d97bc28..42277590 100644 --- a/USE_CASES.md +++ b/USE_CASES.md @@ -141,3 +141,51 @@ Find more information about all of SendGrid's whitelabeling related documentatio You can find documentation for how to view your email statistics via the UI [here](https://app.sendgrid.com/statistics) and via API [here](https://github.com/sendgrid/sendgrid-ruby/blob/master/USAGE.md#stats). Alternatively, we can post events to a URL of your choice via our [Event Webhook](https://sendgrid.com/docs/API_Reference/Webhooks/event.html) about events that occur as SendGrid processes your email. + +You can also use the email statistics helper to make it easier to interact with the API. + +```ruby +require 'sendgrid-ruby' +require 'date' + +include SendGrid + +sg_client = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY']).client +stats = SendGrid::EmailStats.new(sendgrid_client: sg_client) + +# Fetch stats by day, between 2 dates +from = Date.new(2017, 10, 01) +to = Date.new(2017, 10, 12) + +email_stats = stats.by_day(from, to) + +email_stats.metrics + +if !email_stats.error? + email_stats.metrics.each do |metric| + puts "Date - #{metric.date}" + puts "Number of Requests - #{metric.requests}" + puts "Bounces - #{metric.bounces}" + puts "Opens - #{metric.opens}" + puts "Clicks - #{metric.clicks}" + end +end + +# Fetch stats by week, between 2 dates for a category +from = Date.new(2017, 10, 01) +to = Date.new(2017, 10, 12) +category = 'abcd' + +email_stats = stats.by_week(from, to, category) + +if !email_stats.error? + email_stats.metrics.each do |metric| + puts "Date - #{metric.date}" + puts "Number of Requests - #{metric.requests}" + puts "Bounces - #{metric.bounces}" + puts "Opens - #{metric.opens}" + puts "Clicks - #{metric.clicks}" + end +end + +```