SendGridで配信したメールの開封率/クリック率を取得する(Golang)

SendGridで開封率を取得出来るAPI

開封率は統計情報に含まれるのでStats APIで取得することができます。
Stats APIの中でも開封率を取得するには以下の3つのAPIが使えます。
Global Statsで全メールの開封率/クリック率を取得するか、サブユーザを予め用意してサブユーザ単位で開封率/クリック率を取得するか、メール配信時にカテゴリを付与してカテゴリ単位で開封率/クリック率を取得する事になります。
全てのメールの統計情報を取得したいケースは多くないと思いますし、サブユーザは有料プランのみ利用可能なので、ここではCategory Statsを取得してみます。

API 取得できる統計情報
Global Stats 全てのメール関連の統計情報
Category Stats カテゴリ毎の統計情報
Subuser Stats サブユーザ毎の統計情報

メール配信時にカテゴリを指定する

カテゴリの統計情報を取得する為にメール配信時にカテゴリを指定(message.AddCategories("example_category"))します。

package main

import (
    "log"
    "os"

    "github.com/sendgrid/sendgrid-go"
    "github.com/sendgrid/sendgrid-go/helpers/mail"
)

func main() {
    message := mail.NewV3Mail()
    message.SetFrom(mail.NewEmail("FromName", "from@example.com"))
    message.Subject = "Example"
    message.AddContent(mail.NewContent("text/plain", "hello world!"))
    message.AddCategories("example_category")

    personalization := mail.NewPersonalization()
    personalization.AddTos(mail.NewEmail("user1", "user1@example.com"))
    message.AddPersonalizations(personalization)

    client = sendgrid.NewSendClient(os.Getenv("SENDGRID_API_KEY"))
    response, err := client.Send(message)
    if err != nil {
        log.Println(err)
    } else {
        log.Println(response.StatusCode)
        log.Println(response.Body)
        log.Println(response.Headers)
    }
}

配信したメールの情報を取得する

配信時に指定したカテゴリ(example_category)を利用して統計情報を取得します。
responseをparseしてmetricsopensが開封数(ユニークユーザ数はunique_opens)、clicksがクリック数(ユニークユーザ数はunique_clicks)、deliveredが配信されたメール数を取得できます。 パラメータやレスポンスの形式等のAPI仕様はこちらに記載されています。
また、レスポンスの内容はこちらに記載されています。

package main

import (
    "fmt"
    "log"
    "os"

    "github.com/sendgrid/rest"
    "github.com/sendgrid/sendgrid-go"
)

var ApiKey string

const (
    Host = "https://api.sendgrid.com"
)

func init() {
    ApiKey = os.Getenv("SENDGRID_API_KEY")
}

func NewRequest(method rest.Method, path string) rest.Request {
    request := sendgrid.GetRequest(ApiKey, path, Host)
    request.Method = method
    return request
}

func main() {
    request := NewRequest("GET", "/v3/categories/stats")
    queryParams := make(map[string]string)
    queryParams["categories"] = "example_category"
    queryParams["start_date"] = "2023-03-15"
    queryParams["end_date"] = "2023-03-17"
    queryParams["aggregated_by"] = "day"
    queryParams["limit"] = "1"
    queryParams["offset"] = "1"
    request.QueryParams = queryParams
    response, err := sendgrid.API(request)
    if err != nil {
        log.Println(err)
    } else {
        fmt.Println(response.StatusCode)
        fmt.Println(response.Body)
        fmt.Println(response.Headers)
    }
}