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 回答