python - 将电子邮件附件保存到指定存储桶
问题描述
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)
解决方案
您可以在写入时指定存储桶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
希望这能回答你的问题!!
推荐阅读
- python - 任何人都可以解决无法使用 .replace 或 .fillna 填充空值的问题吗?
- sql - 查询从 PostgreSQL 表中获取过去 15 天的详细信息
- css - 文本超出容器时将字体缩放到大小?
- object-detection - YOLO darknet retrain 甚至没有开始说它在某些 *labels* 目录中找不到 *.txt
- python - 将两个在不同语料库上从零开始训练的 BERT 模型组合成一个模型的方法?
- javascript - 如何使用 ESLint 在 JS 或 TS 中检测本地类与全局类的名称冲突?
- aws-amplify - Can I have any way to import module about aws-export.js?
- php - php ajax multiple dropdown pagination
- spring - How to access datasource information in spring boot with spring data jpa and hibernate
- html - Rotating image gallery