LoginSignup
7
5

More than 5 years have passed since last update.

GAEでメールを受信する

Last updated at Posted at 2016-12-22

Google Cloud Platform(2) Advent Calendar 2016の18日目の記事です。

使っていて便利だと思っているGAEのメール受信機能を紹介します。

Receiving Email

この機能は、[任意の文字列]@appid.appspotmail.comにメールを送ることで、HTTPリクエストとしてメールをGAEで受けることができます

これでクレジットカード会社からの請求メールを受信して請求額などをDatastoreやBigQueryに入れたり、広告メールの中に自分が必要なキーワードがあれば通知するようにしています

使い方

GAE/Pyです

メール受信を有効化

設定をapp.yamlに追加します

app.yaml
inbound_services:
- mail

ルーティングの設定

通常のルーティングの設定と同じですが、urlの部分が多少異なります

app.yaml
- url: /_ah/mail/.+
  script: receive_email.app
  login: admin

この場合メールを全てreceive_email.pyで処理します

送信先ごとに処理内容を変える場合

- url: /_ah/mail/owner@.*your_app_id\.appspotmail\.com
  script: handle_owner.app
  login: admin
- url: /_ah/mail/support@.*your_app_id\.appspotmail\.com
  script: handle_support.app
  login: admin
- url: /_ah/mail/.+
  script: handle_catchall.app
  login: admin

メールの受信処理

InboundMailHandlerクラスを継承してreceiveメソッドをオーバーライドします

# coding: utf-8

import logging

from google.appengine.ext.webapp.mail_handlers import InboundMailHandler
import webapp2


class MailReceiveHandler(InboundMailHandler):
    def receive(self, mail_message):
        text_body = mail_message.bodies('text/plain')
        # text_body = mail_message.bodies('text/html') #HTMLメール

        for content_type, body in text_body:
            logging.info(body.decode())

        logging.info(mail_message.sender)

app = webapp2.WSGIApplication([
    MailReceiveHandler.mapping()
], debug=True)

その他以下のようなものが取得できます

  • subject
  • sender
  • to
  • cc
  • date
  • attachments
  • original

デバッグ

admin serverからメールを送信してローカルでデバッグすることができます

receive_email.jpg

以上、こんな感じに使って、こんなことをしているという紹介でした

7
5
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
7
5