I have properly implemented InboundMailHandler and I'm able to process all other mail_message fields except mail_message.attachments. The attachment filename is read properly but the contents are开发者_运维知识库 not being saved in the proper 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)
`
When I try to display the imported pdf file by going to the url: '/serve/%s' % blob_info.key() I get a page with what seems like encoded data, instead of the actual pdf file.
Looks like this:
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
Any ideas? Thanks
Email's attachments are EncodedPayload
objects; to get the data you should call the decode()
method.
Try with:
# Open the file and write to it
with files.open(file_name, 'a') as f:
f.write(contents.decode())
If you want attachments larger 1MB to be processed successfully, decode and convert to 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:]
Found the answer in this excellent blob post: http://john-smith.appspot.com/app-engine--what-the-docs-dont-tell-you-about-processing-inbound-mail
This is how to decode an email attachment for GAE inbound mail:
for attach in mail_message.attachments:
filename, encoded_data = attach
data = encoded_data.payload
if encoded_data.encoding:
data = data.decode(encoded_data.encoding)
精彩评论