将电子邮件附件保存到指定存储桶

时间:2019-03-06 00:41:34

标签: python google-app-engine google-cloud-storage

App Engine允许人们收听传入的电子邮件。然后,我想阅读附件并将其写入GCS存储桶。 google.cloud.storage在标准环境中不可用,而cloudstorage(在可用环境中)不允许在其他存储桶中进行写入,但默认存储桶除外。

我也在灵活的环境中尝试过,但是在那种情况下InboundMailHandler不可用:“ App Engine Mail服务在标准环境之外不可用” https://cloud.google.com/appengine/docs/flexible/python/migrating

在标准环境中,是否可以将这些文件写入指定的存储桶?

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

class LogSenderHandler(InboundMailHandler):
    def receive(self, mail_message):
        logging.info("Received a message from: " + mail_message.sender)
        plaintext_bodies = mail_message.bodies('text/plain')
        html_bodies = mail_message.bodies('text/html')

        if hasattr(mail_message, 'attachments'):
            for filename, filecontent in mail_message.attachments:
                # write filecontent to a bucket


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

1 个答案:

答案 0 :(得分:3)

您可以在写入cloud storage时指定存储桶。

from google.appengine.api import app_identity
bucket_name = os.environ.get('BUCKET_NAME',app_identity.get_default_gcs_bucket_name())

您可以通过以上代码获取特定的存储桶。然后,您可以使用此存储桶在cloud storage中进行写入。 编写文件时请记住,如下指定文件名:

file_name = '/' + 'BUCKET_NAME' + '/' + 'FILE_NAME'

有关读写的更详细的代码,您可以参考
Cloud Read/Write Documentation.

详细的读/写代码:Github Google Cloud

希望这能回答您的问题!