LoginSignup
6
3

More than 5 years have passed since last update.

GAE/Goでメールを受信する

Posted at

GAE(GoogleAppEngine)ではMail APIを使ったメールの受信が行えます。
メールをキーに何かの処理を行ったり、メールのテストに使ったり、とても便利に使うことが出来たので紹介させて頂きます。

Receiving Mail with the Mail API

Sending and Receiving Mail with the Mail API

上記のドキュメントを見ていただければわかる通り、このAPIは [任意の名前]@[GAEのAppID].appspotmail.com にメールを送ることで、GAEでメールをHTTPリクエストとして受け取ることが出来ます。

動かす

サンプルコードはGitHubにあげてあります。

app.yaml

app.yaml

inbound_services:
- mail

上の設定を追加することで、Mail受信を有効にします。

メールの受信処理

package app

import (
    "github.com/nissy/bon"
    "google.golang.org/appengine"
    "google.golang.org/appengine/log"
    "io/ioutil"
    "net/http"
    "net/mail"
)

func init() {

    r := bon.NewRouter()

    r.Post("/_ah/mail/:ToAddress", func(w http.ResponseWriter, r *http.Request) {
        c := appengine.NewContext(r)
        defer r.Body.Close()

        m, err := mail.ReadMessage(r.Body)
        if err != nil {
            log.Errorf(c, "Error reading r.body: %v", err)
            return
        }

        header := m.Header
        log.Infof(c, "Date:", header.Get("Date"))
        log.Infof(c, "From:", header.Get("From"))
        log.Infof(c, "To:", header.Get("To"))
        log.Infof(c, "Subject:", header.Get("Subject"))

        body, err := ioutil.ReadAll(m.Body)
        if err != nil {
            log.Errorf(c, "Error reading m.body: %v", err)
        }
        log.Infof(c, "Body:", string(body))
    })

    http.Handle("/", r)
}

/_ah/mail/[送信先に指定されたアドレス] のpathにPOSTリクエストが来て、リクエストボディがメールの内容になるのでそれに合わせて実装します。
メールについてはnet/mailなど適当なパッケージでパースして使うことが出来ます。

ローカルでのデバッグ

admin server (http://localhost:8000) のInbound Mailからローカルで起動しているアプリに対してメールを送信することが出来ます。

admin_server_inbound_mail.png

6
3
0

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
6
3