【发布时间】:2017-07-31 05:01:30
【问题描述】:
我有一个应用引擎应用,它接收电子邮件并将其元数据发送到脚本进行处理。它运作良好。代码如下,由 Google 通过 Github 示例提供。
但是,问题是,我如何将通过此脚本(或一般的 App Engine)收到的电子邮件转发到另一个电子邮件地址?
特别是,对于使用 Gmail 向我转发电子邮件的客户,我希望收到他们的转发请求,以便我作为人类管理员批准他们。
import webapp2
import logging
import urllib
import json
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler
from google.appengine.api import urlfetch
class HandleEmail(InboundMailHandler):
def receive(self, message):
# parse out fields
to = message.to
sender = message.sender
cc = getattr(message, 'cc', '')
date = message.date
subject = message.subject
# Original message, as a python email.message.Message
original = str(message.original)
html_body = ''
for _, body in message.bodies('text/html'):
html_body = body.decode()
plain_body = ''
for _, plain in message.bodies('text/plain'):
plain_body = plain.decode()
# Attachements are EncodedPayload objects, see
# https://code.google.com/p/googleappengine/source/browse/trunk/
# python/google/appengine/api/mail.py#536
attachments = [{
'filename': attachment[0],
'encoding': attachment[1].encoding,
'payload': attachment[1].payload
}
for attachment
in getattr(message, 'attachments', [])]
# logging, remove what you find to be excessive
logging.info('sender: %s', sender)
logging.info('to: %s', to)
logging.info('cc: %s', cc)
logging.info('date: %s', date)
logging.info('subject: %s', subject)
logging.info('html_body: %s', html_body)
logging.info('plain_body: %s', plain_body)
logging.info('attachments: %s', [a['filename'] for a in attachments])
# POST (change to your endpoint, httpbin is cool for testing though)
# url = 'http://httpbin.org/post'
url = 'https://myapp.appspot.com/receiver.php'
form_fields = urllib.urlencode({
'sender': sender.encode('utf8'),
'to': to.encode('utf8'),
'cc': cc.encode('utf8'),
'date': date.encode('utf8'),
'subject': subject.encode('utf8'),
'html_body': html_body.encode('utf8'),
'plain_body': plain_body.encode('utf8'),
'original': original.encode('utf8'),
'attachments': json.dumps(attachments)
})
headers = {
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
}
result = urlfetch.fetch(url=url,
method=urlfetch.POST,
payload=form_fields,
headers=headers)
# log more
logging.info('POST to %s returned: %s', url, result.status_code)
logging.info('Returned content: %s', result.content)
application = webapp2.WSGIApplication([HandleEmail.mapping()], debug=True)
【问题讨论】:
-
我是吗?我想我是。 “转发”是最终用户所指的。但我猜后端正在接收消息然后发送它。我对电子邮件了解不多,所以如果在协议级别没有“转发”之类的东西,那就是它。
-
我相信你已经回答了你自己的问题 :) 因为只有你可以根据你的命令“转发/发送”一封电子邮件
-
确实如此。如果您发表评论作为答案,我会接受。谢谢。
标签: python email google-app-engine