Google app engine 需要使用GAE InboundMailHandler处理附件的帮助吗
我已经正确地实现了InboundMailHandler,并且我能够处理除mail_message.attachments之外的所有其他mail_message字段。附件文件名已正确读取,但内容未以正确的mime_类型保存Google app engine 需要使用GAE InboundMailHandler处理附件的帮助吗,google-app-engine,email,blobstore,Google App Engine,Email,Blobstore,我已经正确地实现了InboundMailHandler,并且我能够处理除mail_message.attachments之外的所有其他mail_message字段。附件文件名已正确读取,但内容未以正确的mime_类型保存 if not hasattr(mail_message, 'attachments'): raise ProcessingFailedError('Email had no attached documents') el
if not hasattr(mail_message, 'attachments'):
raise ProcessingFailedError('Email had no attached documents')
else:
logging.info("Email has %i attachment(s) " % len(mail_message.attachments))
for attach in mail_message.attachments:
filename = attach[0]
contents = attach[1]
# Create the file
file_name = files.blobstore.create(mime_type = "application/pdf")
# Open the file and write to it
with files.open(file_name, 'a') as f:
f.write(contents)
# Finalize the file. Do this before attempting to read it.
files.finalize(file_name)
# Get the file's blob key
blob_key = files.blobstore.get_blob_key(file_name)
return blob_key
blob_info = blobstore.BlobInfo.get(blob_key)
`
当我试图通过转到url显示导入的pdf文件时:'/serve/%s'%blob_info.key()
我得到一个看起来像是编码数据的页面,而不是实际的pdf文件
看起来像这样:
从nobody到2011年8月4日23:45:06内容传输编码:base64 JVBERi0xLjMKJcTl8uXrp/Og0MTGCjQgMCBvYmoKPDwgL0xlbmd0aCA1IDAgUiAvRmlsdGVyIC9G bGF0ZURlY29kZSA+PgpzdHJlYW0KeAGtXVuXHLdxfu9fgSef2RxxOX2by6NMbSLalOyQK+ucyHpQ ED3IKWKF0VJ81VYVF3QU9MDY+Z40TSWWQQQL5TWKKYL5TYVQWQF3JF9KF9MDY+Z40TSWWWWWWW0KF8KZ5TWL5TYF8KF3F8KF8KX+++HVDFL8
有什么想法吗?感谢电子邮件的附件是
EncodedPayload
对象;要获取数据,应调用decode()
方法
尝试:
# Open the file and write to it
with files.open(file_name, 'a') as f:
f.write(contents.decode())
在这篇优秀的blob帖子中找到了答案: 以下是如何解码GAE入站邮件的电子邮件附件:
for attach in mail_message.attachments:
filename, encoded_data = attach
data = encoded_data.payload
if encoded_data.encoding:
data = data.decode(encoded_data.encoding)
如果要成功处理大于1MB的附件,请解码并转换为str:
#decode and convert to string
datastr = str(contents.decode())
with files.open(file_name, 'a') as f:
f.write(datastr[0:65536])
datastr=datastr[65536:]
while len(datastr) > 0:
f.write(datastr[0:65536])
datastr=datastr[65536:]
如果
if encoded\u data.encoding
检查无效,则decode
方法在内部无效。