首页 > 解决方案 > 将电子邮件附件保存到指定存储桶

问题描述

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)

标签: pythongoogle-app-enginegoogle-cloud-storage

解决方案


您可以在写入时指定存储桶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

希望这能回答你的问题!!


推荐阅读