我已正确实施InboundMailHandler,并且我能够处理除mail_message.attachments之外的所有其他mail_message字段。附件文件名已正确读取,但内容未保存在正确的mime_type
中 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文件。
看起来像这样:
From nobody Thu Aug 4 23:45:06 2011 content-transfer-encoding: base64 JVBERi0xLjMKJcTl8uXrp/Og0MTGCjQgMCBvYmoKPDwgL0xlbmd0aCA1IDAgUiAvRmlsdGVyIC9G bGF0ZURlY29kZSA+PgpzdHJlYW0KeAGtXVuXHLdxfu9fgSef2RxxOX2by6NMbSLalOyQK+ucyHpQ eDE3IkWKF0vJj81vyVf3Qu9Mdy+Z40TswqKAalThqwJQjfm1/Hv5tWzxv13blf2xK++el+/LL+X+ g/dtefq
有什么想法吗?感谢
答案 0 :(得分:2)
电子邮件的附件是EncodedPayload
个对象;要获取数据,您应该调用decode()
方法。
尝试:
# Open the file and write to it
with files.open(file_name, 'a') as f:
f.write(contents.decode())
答案 1 :(得分:1)
如果您想要成功处理大于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:]
答案 2 :(得分:-1)
在这个优秀的blob帖子中找到答案: http://john-smith.appspot.com/app-engine--what-the-docs-dont-tell-you-about-processing-inbound-mail
这是解码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)