· 6 years ago · Aug 14, 2019, 01:42 PM
1 import imaplib, email, os
2
3user = '****@gmail.com'
4password = '***'
5imap_url = 'imap.gmail.com'
6#Where you want your attachments to be saved (ensure this directory exists)
7attachment_dir = 'your_attachment_dir'
8# sets up the auth
9def auth(user,password,imap_url):
10 con = imaplib.IMAP4_SSL(imap_url)
11 con.login(user,password)
12 return con
13# extracts the body from the email
14def get_body(msg):
15 if msg.is_multipart():
16 return get_body(msg.get_payload(0))
17 else:
18 return msg.get_payload(None,True)
19# allows you to download attachments
20def get_attachments(msg):
21 for part in msg.walk():
22 if part.get_content_maintype()=='multipart':
23 continue
24 if part.get('Content-Disposition') is None:
25 continue
26 fileName = part.get_filename()
27
28 if bool(fileName):
29 filePath = os.path.join(attachment_dir, fileName)
30 with open(filePath,'wb') as f:
31 f.write(part.get_payload(decode=True))
32#search for a particular email
33def search(key,value,con):
34 result, data = con.search(None,key,'"{}"'.format(value))
35 return data
36#extracts emails from byte array
37def get_emails(result_bytes):
38 msgs = []
39 for num in result_bytes[0].split():
40 typ, data = con.fetch(num, '(RFC822)')
41 msgs.append(data)
42 return msgs
43
44
45def printRAW(*Text):
46 RAWOut = open(1, 'w', encoding='utf8', closefd=False)
47 print(*Text, file=RAWOut)
48 RAWOut.flush()
49 RAWOut.close()
50
51con = auth(user,password,imap_url)
52con.select('INBOX')
53
54result, data = con.fetch(b'21','(RFC822)')
55raw = email.message_from_bytes(data[0][1])
56get_attachments(raw)
57
58print(raw.get_payload(0))
59printRAW(raw.get_payload(0))