DRYな備忘録

Don't Repeat Yourself.

【GCP】AppEngine Goからメールを送りたい

前回のエントリでは、GAE/GoがWebサーバとしてちゃんと動くことが確認できたので、今回はGAEからmailを送る。

参考

送信元のメールアドレスに制限がある

For security purposes, the sender address of a message must be one of the following:

・The Gmail or Google Apps Account of the user who is currently signed in

・Any email address of the form anything@appname.appspotmail.com or anything@appalias.appspotmail.com

・Any email address listed in the Cloud Platform Console under Email API Authorized Senders

今回は3番目のやつでやる。プロジェクトごとにAuthorized Sendersが設定できるので、まず

  1. ここ Google Cloud Platform を訪問して
  2. プロジェクトを選択し
  3. アプリケーション設定の[編集]を押し
  4. [Email API の承認済み送信者]の欄に、送信元にしたいアドレスを追加する

こんな感じ f:id:otiai10:20160402042257p:plain

GAE/Goのアプリケーションを書く

package gae_go_mail_example_oppai

import (
    "fmt"
    "net/http"

    "github.com/otiai10/marmoset"
    "google.golang.org/appengine"
    "google.golang.org/appengine/mail"
)

func init() {

    router := marmoset.NewRouter()

    router.GET("/", func(w http.ResponseWriter, r *http.Request) {
        ctx := appengine.NewContext(r)
        msg := &mail.Message{
            Sender:   "設定済みの送信元アドレス",
            To:       []string{"送信先アドレス"},
            Subject:  "やっはろー",
            Body:     "律っちゃんぺろぺろ",
            HTMLBody: "<h1>律っちゃんぺろぺろ</h1>",
        }
        err := mail.Send(ctx, msg)
        fmt.Fprint(w, fmt.Sprintf("ERROR? %v", err))
    })

    http.Handle("/", router)
}

送信するだけならこれでおしまい。

デプロイ

% appcfg.py -A {アプリケーションID} -V v1 update ./ # このディレクトリは、app.yamlとmain.goが入ってるところ
09:12 PM Application: {アプリケーションID} (was: None); version: v1 (was: None)
09:12 PM Host: appengine.google.com
09:12 PM
Starting update of app: {アプリケーションID}, version: v1
09:12 PM Getting current resource limits.
09:12 PM Scanning files on local disk.
09:12 PM Cloning 38 application files.
09:12 PM Compilation starting.
09:12 PM Compilation: 37 files left.
09:12 PM Compilation completed.
09:12 PM Starting deployment.
09:12 PM Checking if deployment succeeded.
09:12 PM Deployment successful.
09:12 PM Checking if updated app version is serving.
09:12 PM Completed update of app: {アプリケーションID}, version: v1

で、

http://{アプリケーションID}.appspot.com/ にGETでアクセスしたら、メールが来た

f:id:otiai10:20160402042758p:plain

雑感

DRY