获取邮件附件到python文件对象 [英] Getting mail attachment to python file object

查看:92
本文介绍了获取邮件附件到python文件对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个电子邮件多部分消息对象,我想将该电子邮件中的附件转换成python文件对象。这可能吗?如果可能,我应该研究什么方法或类来做这样的任务?

解决方案

我不是真的了解电子邮件多部分消息对象的含义。您是指属于 电子邮件的对象.message.Message class?



如果这是你的意思,这很简单。在多部分消息中, get_payload 方法返回消息部分列表(每个消息本身都是一个消息对象) 。您可以遍历这些部分并检查其属性:例如, get_content_type 方法返回零件的MIME类型,而 get_filename 方法返回零件的文件名(如果在消息中指定了)。然后当您找到正确的消息部分时,您可以调用 get_payload(decode = True)来获取解码的内容。

 >>>导入电子邮件
>>> msg = email.message_from_file(open('message.txt'))
>>> len(msg.get_payload())
2
>>> attachment = msg.get_payload()[1]
>>> attachment.get_content_type()
'image / png'
>>> open('attachment.png','wb')。write(attachment.get_payload(decode = True))

如果您以编程方式从您收到的电子邮件中提取附件,则可能需要对病毒和木马采取预防措施。特别是,您可能应该仅提取您认识的MIME类型的附件是安全的,您可能希望选择自己的文件名,或至少清理 get_filename 的输出。


I have got an email multipart message object, and I want to convert the attachment in that email message into python file object. Is this possible? If it is possible, what method or class in Python I should look into to do such task?

解决方案

I don't really understand what you mean by "email multipart message object". Do you mean an object belonging to the email.message.Message class?

If that is what you mean, it's straightforward. On a multipart message, the get_payload method returns a list of message parts (each of which is itself a Message object). You can iterate over these parts and examine their properties: for example, the get_content_type method returns the part's MIME type, and the get_filename method returns the part's filename (if any is specified in the message). Then when you've found the correct message part, you can call get_payload(decode=True) to get the decoded contents.

>>> import email
>>> msg = email.message_from_file(open('message.txt'))
>>> len(msg.get_payload())
2
>>> attachment = msg.get_payload()[1]
>>> attachment.get_content_type()
'image/png'
>>> open('attachment.png', 'wb').write(attachment.get_payload(decode=True))

If you're programmatically extracting attachments from email messages you have received, you might want to take precautions against viruses and trojans. In particular, you probably ought only to extract attachments whose MIME types you know are safe, and you probably want to pick your own filename, or at least sanitize the output of get_filename.

这篇关于获取邮件附件到python文件对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆