· 8 years ago · Mar 15, 2018, 06:58 PM
1import time
2import imaplib
3import email
4import sys
5import re
6
7ORG_EMAIL = "@gmail.com"
8FROM_EMAIL = "some_gmail_account" + ORG_EMAIL
9FROM_PWD = "some_password"
10SMTP_SERVER = "imap.gmail.com"
11SMTP_PORT = 993
12Subject_Startswith = 'Test'
13
14# LOGGING-----------------------------------
15te = open('Email_Log_' + time.strftime("%Y_%m_%d_%Hh_%Mm") + '.txt',
16 'w') # File where you need to keep the logs
17
18
19class Unbuffered:
20 def __init__(self, stream):
21 self.stream = stream
22
23 def write(self, data):
24 self.stream.write(data)
25 self.stream.flush()
26 te.write(data) # Write the data of stdout here to a text file as well
27
28
29sys.stdout = Unbuffered(sys.stdout)
30# -------------------------------------------------
31#
32# Utility to read email from Gmail Using Python
33#
34# ------------------------------------------------
35
36def display_visible_html_using_re(text):
37 return(re.sub("(\<.*?\>)", "",text))
38
39def read_email_from_gmail():
40 try:
41 mail = imaplib.IMAP4_SSL(SMTP_SERVER)
42 mail.login(FROM_EMAIL,FROM_PWD)
43 mail.select('inbox')
44
45 type, data = mail.search(None, 'ALL')
46 mail_ids = data[0]
47
48 id_list = mail_ids.split()
49 first_email_id = int(id_list[0])
50 latest_email_id = int(id_list[-1])
51
52 for i in range(latest_email_id,first_email_id, -1):
53 typ, data = mail.fetch(i, '(RFC822)' )
54
55 for response_part in data:
56 if isinstance(response_part, tuple):
57 msg = email.message_from_string(response_part[1])
58 email_subject = msg['subject']
59 email_from = msg['from']
60 email_date= msg['date']
61 if email_subject.startswith(Subject_Startswith):
62 print 'From : ' + email_from + '\n'
63 print 'Subject : ' + email_subject + '\n'
64 print 'Date : ' + email_date + '\n'
65 try:
66 for part in msg.walk():
67 print display_visible_html_using_re(part.get_payload())
68 except:
69 print 'Email body couldnt be parsed'
70
71 except Exception, e:
72 print str(e)
73
74read_email_from_gmail()