Python poplib get attachment

I am trying to access the POP3 mail server. I will poll messages and download attachments for each of them. I can successfully log in and receive messages, but I cannot figure out how to actually receive the attachment, which I will need to analyze later. I think I can save in tmp dir until I process it.

Here is what I got so far:

pop = poplib.POP3_SSL(server) pop.user(usr) pop.pass_(pwd) f = open(file_dir, 'w') num_msgs = len(pop.list()[1]) for msg_list in range(num_msgs): for msg in pop.retr(msg_list+1)[1]: mail = email.message_from_string(msg) for part in mail.walk(): f.write(part.get_payload(decode=True)) f.close() 

This is the code that I put together from the examples I found on the Internet, but was not a convincing example of how to get the application. The file I am writing to is empty. What am I missing here?

+6
source share
2 answers

See the full example below.

Import poplib and parser

import poplib from email import parser

Function returning a connection to the pop server:

 def mail_connection(server='pop.mymailserver.com'): pop_conn = poplib.POP3(server) pop_conn.user(' someuser@server ') pop_conn.pass_('password') return pop_conn 

Function to retrieve mail:

 def fetch_mail(delete_after=False): pop_conn = mail_connection() messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)] messages = ["\n".join(mssg[1]) for mssg in messages] messages = [parser.Parser().parsestr(mssg) for mssg in messages] if delete_after == True: delete_messages = [pop_conn.dele(i) for i in range(1, len(pop_conn.list()[1]) + 1)] pop_conn.quit() return messages 

Then the function of saving attachments as files. NB, allowed mimetypes ; you can have a list of them, for example:

 allowed_mimetypes = ["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"] 

etc.

 def get_attachments(): messages = fetch_mail() attachments = [] for msg in messages: for part in msg.walk(): if part.get_content_type() in allowed_mimetypes: name = part.get_filename() data = part.get_payload(decode=True) f = file(name,'wb') f.write(data) f.close() attachments.append(name) return attachments 
+4
source

I know this is an old question, but just in case: the value you pass to email.message_from_string is actually a list of email content, where each item is a string. You need to join it to get a string representation of this letter:

 mail = email.message_from_string("".join(msg)) 
+3
source

All Articles