Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting mail attachment to python file object

Tags:

python

email

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?

like image 437
Joshua Partogi Avatar asked Nov 01 '10 10:11

Joshua Partogi


People also ask

How do I download an email attachment in Python?

Create an empty python file download_attachment.py. Add the following lines to it. print 'Proceeding' import email import getpass import imaplib import os import sys userName = '[email protected]' passwd = 'yourpassword' directory = '/full/path/to/the/directory' detach_dir = '.

Can python send an email with attachment?

Use Python's built-in smtplib library to send basic emails. Send emails with HTML content and attachments using the email package.


1 Answers

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.

like image 77
Gareth Rees Avatar answered Sep 22 '22 15:09

Gareth Rees