タダです.
前回 SendGrid API を叩いてバウンスが発生したメールと原因を NodeJS で取得したのを記事に書きました.今回は Golang で同様のことをやってみたのでその模様を備忘録としてまとめます.
バウンスが発生したの取得のコード
バウンスを発生の取得するコードは次のような物を作りました.クエリパラメータでバウンスが発生期間の開始と終了を使えるので,start_time
が10分前の UNIXTIME で end_time
がコード実行時間の UNIXTIME を取得して渡しています.SendGrid の API を叩くライブラリとして sendgrid-go があるのでこれを使って取得します.
package main import ( "encoding/json" "fmt" "strconv" "time" sendgrid "github.com/sendgrid/sendgrid-go" ) type bounceDetail struct { Created int `json:"created"` Email string `json:"email"` Reason string `json:"reason"` Status string `json:"status"` } func getBounceMail(apiKey string) ([]bounceDetail, error) { var bounceDetail []bounceDetail startTime := time.Now().Add(-10 * time.Minute).Unix() endTime := time.Now().Unix() req := sendgrid.GetRequest(apiKey, "/v3/suppression/bounces", "https://api.sendgrid.com") req.Method = "GET" queryParams := make(map[string]string) queryParams["start_time"] = strconv.FormatInt(startTime, 10) queryParams["end_time"] = strconv.FormatInt(endTime, 10) req.QueryParams = queryParams res, err := sendgrid.API(req) if err != nil { fmt.Println(err.Error()) return nil, err } if err := json.Unmarshal([]byte(res.Body), &bounceDetail); err != nil { fmt.Println(err) return nil, err } return bounceDetail, nil }
SendGrid の API を叩いた時にレスポンスが下記のように返ってくるので bounceDetail
という構造体でレスポンスを定義して呼び出し元に返すことをしています.あとは呼び出し元で必要な情報を取得して処理する事が可能です.
[ { "created": 1443651125, "email": "testemail1@test.com", "reason": "550 5.1.1 The email account that you tried to reach does not exist. Please try double-checking the recipient's email address for typos or unnecessary spaces. Learn more at https://support.google.com/mail/answer/6596 o186si2389584ioe.63 - gsmtp ", "status": "5.1.1" }, { "created": 1433800303, "email": "testemail2@testing.com", "reason": "550 5.1.1 <testemail2@testing.com>: Recipient address rejected: User unknown in virtual alias table ", "status": "5.1.1" } ]
まとめ
SendGrid の API を Golang で利用したのがはじめてだったのでその模様をまとめました.Golang を使うこと自体転職してからになるため,表現や書きっぷりに慣れていきたいし,学びをこのブログに投稿していければと思います.