· 7 years ago · Dec 13, 2018, 10:56 AM
1ORG_EMAIL = "@gmail.com"
2FROM_EMAIL = "mohit05011992" + ORG_EMAIL
3FROM_PWD = "tswbssoobmujkfwc"
4SMTP_SERVER = "imap.googlemail.com"
5SMTP_PORT = 993
6
7import smtplib
8import time
9import imaplib
10import email
11
12
13# -------------------------------------------------
14#
15# Utility to read email from Gmail Using Python
16#
17# ------------------------------------------------
18
19def read_email_from_gmail():
20 try:
21 mail = imaplib.IMAP4_SSL(SMTP_SERVER)
22
23 mail.login(FROM_EMAIL, FROM_PWD)
24
25 mail.select('inbox')
26
27 type, data = mail.search(None,
28 '(FROM "net.statement@citicorp.com" SUBJECT "Statement Online - CITIBANK REWARDS PLATINUM CARD")')
29
30 mail_ids = data[0]
31
32 id_list = mail_ids.split()
33 first_email_id = int(id_list[0])
34 latest_email_id = int(id_list[-1])
35 print len(id_list)
36 print "mohit"
37 for i in id_list:
38 type, data = mail.fetch(i, '(RFC822)')
39
40 for response_part in data:
41 if isinstance(response_part, tuple):
42 msg = email.message_from_string(response_part[1])
43 email_subject = msg['subject']
44 email_from = msg['from']
45 email_date = msg['date']
46
47
48 # emails = [email.message_from_string('\n'.join(message[1])) for message in messages]
49
50 # for mail in emails:
51 # check for attachment;
52 for part in msg.walk():
53 if not msg.is_multipart():
54 continue
55 if msg.get('Content-Disposition'):
56 continue
57 file_name = part.get_filename()
58
59 # check if email park has filename --> attachment part
60 if file_name:
61 file = open(str(i) + '_' + file_name,'w+')
62 file.write(part.get_payload(decode=True))
63 file.close()
64
65 except Exception, e:
66 print str(e)
67
68
69read_email_from_gmail();