LoginSignup
1

More than 5 years have passed since last update.

GAE/GoでSendGrid APIv3でメールを送信する

Last updated at Posted at 2018-09-11

はじめに

AppEngineのMailAPIでもメールを送ることができますが、SendGridも利用できます。
GAEからの利用であれば、月12,000件まで無料で使えます。(2018年9月8日時点)
詳しくはドキュメントを参照してください。

以下は go1.9 で試しました。

SendGrid APIv3を使う

GAE/Goのドキュメントではv2を使うやり方が紹介されていますが、より新しいAPIであるv3を使う方法を以下で紹介します。

コードはこんな感じです。Email helperを使うと jsonベタ書きしなくてもOKです。


import (
    "context"
    "fmt"
    "os"

    "github.com/sendgrid/rest"
    sendgrid "github.com/sendgrid/sendgrid-go"
    "github.com/sendgrid/sendgrid-go/helpers/mail"
    "google.golang.org/appengine/urlfetch"
)

func sendMail(ctx context.Cotext, to, subject, plainTxt, htmlTxt string) error {
    sendgrid.DefaultClient = &rest.Client{HTTPClient: urlfetch.Client(ctx)}
    cli := sendgrid.NewSendClient("YOUR_API_KEY")

    fromM := mail.NewEmail("YOUR_NAME", "YOUR_EMAIL")
    toM := mail.NewEmail(to, to)
    msg := mail.NewSingleEmail(fromM, subject, toM, plainTxt, htmlTxt)

    res, err := cli.Send(msg)
    if err != nil {
        return err
    }

    if res.StatusCode >= 400 {
        return fmt.Errorf("send mail failed: %v", res.Body)
    }
    return nil
}

ポイント

  1. AppEngineなので以下のようにHTTPClientにurlfetchを使う必要があります。
    sendgrid.DefaultClient = &rest.Client{HTTPClient: urlfetch.Client(ctx)}

  2. errorだけじゃなくstatuscodeをチェックする必要があります。メールの内容が正しくないと400などのステータスが返ってきます。

  3. plainTextとhtmlTextの両方がないとエラーになります。APIの仕様と違う。。

感想

NewEmail()はMailを作るのではなくFromやToのアドレスを作る関数で、実際のMailを作るのは NewSingleEmail() です。わかりにくくないかな

sendgrid/sendgrid-go: The Official SendGrid Led, Community Driven Golang API Library

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1