+ 1

Read an Email via Python

Hi, today I've looked for a script that can let me to read emails through it. Here what I found: import imaplib import email msrvr = imaplib.IMAP4_SSL("imap.gmail.com", 993) msrvr.login("insert_your_email@gmail.com", "insert_your_password") status, cnt = msrvr.select("Inbox") stat, dta = msrvr.fetch(cnt[0], "(UID BODY[TEXT])") result, data = msrvr.uid("search", None, "ALL") inbox_item_list = data[0].split() most_recent = inbox_item_list[-1] oldest = inbox_item_list[0] result2, email_data = msrvr.uid("fetch", oldest, "(RFC822)") raw_email = email_data[0][1].decode("UTF-8") email_message = email.message_from_string(raw_email) #print(email_message["From"]) print(dta[0][1].decode("UTF-8")) msrvr.close() msrvr.logout() and there's the email text in print(dta[0][1].decode("UTF-8")). But now I have three questions to ask you: 1) How should I do to print who sent to me the email? I tried with print(email_message["From"]), but every time it says me: The Google community team <googlecommunityteam-noreply@google.com> 2) Then, how to print the email title? 3) And the arrival time? Thanks in advice, guys :))

12th Jun 2019, 11:49 AM
Giordano Fratti
Giordano Fratti - avatar
2 Answers
+ 5
I tested the following code with Python 2.7 and it worked for me. Obviously, I replaced the username and password with my gmail credentials. This is essentially a copy/paste from an answer by mazelife at: https://stackoverflow.com/questions/1225586/checking-email-with-python The only change I made was to reduce the connection_list to 15 elements because I was getting the following error when trying to process them all: File "C:\Python27\lib\poplib.py", line 232, in retr return self._longcmd('RETR %s' % which) File "C:\Python27\lib\poplib.py", line 167, in _longcmd return self._getlongresp() File "C:\Python27\lib\poplib.py", line 152, in _getlongresp line, o = self._getline() File "C:\Python27\lib\poplib.py", line 377, in _getline raise error_proto('line too long') poplib.error_proto: line too long Here is the code: import poplib from email import parser pop_conn = poplib.POP3_SSL('pop.gmail.com') pop_conn.user('youremailaddress@gmail.com') pop_conn.pass_('yourpassword') connection_list = pop_conn.list()[1][:15] #Get messages from server: messages = [pop_conn.retr(i) for i in range(1, len(connection_list) + 1)] # Concat message pieces: messages = ["\n".join(mssg[1]) for mssg in messages] #Parse message intom an email object: messages = [parser.Parser().parsestr(mssg) for mssg in messages] for message in messages: print message['subject'] pop_conn.quit()
14th Jun 2019, 7:40 PM
Josh Greig
Josh Greig - avatar
+ 2
Thanks man, you are helpful! :)))
16th Jun 2019, 10:30 AM
Giordano Fratti
Giordano Fratti - avatar