- Notifications
You must be signed in to change notification settings - Fork 638
Expand file tree
/
Copy pathP11_CheckEmail.py
More file actions
Latest commit
59 lines (46 loc) · 2.24 KB
/
Copy pathP11_CheckEmail.py
File metadata and controls
59 lines (46 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# Author: OMKAR PATHAK
# This script helps to read the latest emails and entieve the contents of the selected email
# First turn on this: https://myaccount.google.com/lesssecureapps?pli=1
importemail, getpass, imaplib, os
detach_dir='.'# directory where to save attachments (default: current)
# user = input("Enter your Gmail Username:")
pwd=getpass.getpass("Enter your Gmail Password: ")
# connecting to the gmail imap server
mail=imaplib.IMAP4_SSL("imap.gmail.com")
mail.login('omkarpathak.comp@mmcoe.edu.in', pwd)
mail.list()
mail.select('INBOX') # Specify from where to retrieve the email
response, ids=mail.search(None, '(ALL)') # search all types of mails
ids=ids[0].split()
ids=ids[::-1] # getting latest emails first
i=0
foremailidinids:
i+=1
response, data=mail.fetch(emailid, "(RFC822)") # fetching the mail
email_body=data[0][1] # getting the mail content
mailFetch=email.message_from_bytes(email_body) # parsing the mail content to get a mail object
#Check if any attachments at all
ifmailFetch.get_content_maintype() !='multipart':
continue
mailFetch['Subject'] =mailFetch['Subject'].replace(r'=?utf-8?q?', '')
mailFetch['Subject'] =mailFetch['Subject'].replace('_', ' ')
# print(type(mailFetch['Subject']))
print ("["+mailFetch["From"]+"]:"+mailFetch['Subject'].replace('=?utf-8?q?', '').replace('_', ' ').replace('=3F?=', '?').replace('?=',''))
# we use walk to create a generator so we can iterate on the parts and forget about the recursive headach
forpartinmailFetch.walk():
# multipart are just containers, so we skip them
ifpart.get_content_maintype() =='multipart':
continue
# is this part an attachment ?
ifpart.get('Content-Disposition') isNone:
continue
filename=mailFetch["From"] +"_hw1answer"
att_path=os.path.join(detach_dir, filename)
#Check if its already there
ifnotos.path.isfile(att_path) :
# finally write the stuff
fp=open(att_path, 'wb')
fp.write(part.get_payload(decode=True))
fp.close()
if (i==10): # Get only ten latest emails
break