Getting mail attachment to python file object

后端 未结 3 705
小鲜肉
小鲜肉 2020-12-02 10:10

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 m

3条回答
  •  悲哀的现实
    2020-12-02 10:53

    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.

提交回复
热议问题