1

Google App Engine でメール ヘッダーを読む方法。私はグーグルで検索しようとしていますが、うまく機能する例が見つかりません。

4

1 に答える 1

2

ここで答え。
ファイル: app.yaml ( mymail@myapp.appspotmail.com
にメールを送信します)

application: myapp
version: 1
runtime: python27
api_version: 1
threadsafe: yes

handlers:    
- url: /_ah/mail/mymail@myapp\.appspotmail\.com
  script: mail.app
  login: admin

- url: .*
  script: main.app

libraries:
- name: webapp2
  version: "2.5.1"

inbound_services:
- mail

アプリが電子メールを受信すると仮定すると、これは電子メール ヘッダーの一部です。

...
MIME-Version: 1.0
Received: by 10.220.68.18 with HTTP; Tue, 30 Oct 2012 21:18:18 -0700 (PDT)
Date: Wed, 31 Oct 2012 12:18:18 +0800
Message-ID: <CA+aGk47FkztZR3jUfrG=XU-ikLNnpEVE3KOcoXHgX1ntoBs1+A@mail.gmail.com>
Subject: Butter cake receipe
From: Someone somebody <someone@somebody.com>
To: Danny Hong <danny@otherone.com>
Content-Type: multipart/alternative; boundary=bcaxec5y19610f36df7204cd5331cd
X-Gm-Message-State: ALoCoQmzPBg3OYwtkdO5pUbNI5Zk+v2Qa42P5E6lWRzCiVUPBNsHbmSOJoBir2UfsUdq7vZLYnUOsHg
...

ファイル: mail.py

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

class MailHandle(InboundMailHandler):
  def receive(self, mail_message):

    #Read headers    
    buf = mail_message.original.get('MIME-Version')
    logging.info("I get: %s" % buf)
    # output: i get: 2.0

    buf = mail_message.original.get('Message-ID')
    logging.info("I get: %s" % buf)
    # output: i get: <CA+aGk47FkztZR3jUfrG=XU-ikLNnpEVE3KOcoXHgX1ntoBs1+A@mail.gmail.com>

    buf = mail_message.original.get('X-Gm-Message-State')
    logging.info("I get: %s" % buf)
    # output: i get: ALoCoQmzPBg3OYwtkdO5pUbNI5Zk+v2Qa42P5E6lWRzCiVUPBNsHbmSOJoBir2UfsUdq7vZLYnUOsHg

    buf = mail_message.original.get('Subject', 'no subject')
    logging.info("I get: %s" % buf)
    # output: i get: Butter cake receipe

    buf = mail_message.original.get('something-else','no such header')
    logging.info("I get: %s" % buf)
    # output: i get: no such header

    # Looping and getting attachments...
    if hasattr(mail_message,'attachments'):
      for fn, att in mail_message.attachments:
        logging.info("Attachment filename is %s" % fn)
        # output: Attachment file is <filename.xxx>
        logging.info("Attactment data in blob %s" % att.decode())
        # output: Attachment data in blob <binary>
于 2012-10-31T07:14:45.347 に答える