-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget email.py
More file actions
49 lines (43 loc) · 1.36 KB
/
get email.py
File metadata and controls
49 lines (43 loc) · 1.36 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
#!/usr/bin/env python2.7
import sys
import imaplib
import getpass
import email
import datetime
M = imaplib.IMAP4_SSL('imap.gmail.com')
try:
M.login('notatallawhistleblowerIswear@gmail.com', getpass.getpass())
except imaplib.IMAP4.error:
print "LOGIN FAILED!!! "
# ... exit or deal with failure...
rv, mailboxes = M.list()
if rv == 'OK':
print "Mailboxes:"
print mailboxes
rv, data = M.select("Top Secret/PRISM Documents")
if rv == 'OK':
print "Processing mailbox...\n"
process_mailbox(M) # ... do something with emails, see below ...
M.close()
M.logout()
# Note: This function definition needs to be placed
# before the previous block of code that calls it.
def process_mailbox(M):
rv, data = M.search(None, "ALL")
if rv != 'OK':
print "No messages found!"
return
for num in data[0].split():
rv, data = M.fetch(num, '(RFC822)')
if rv != 'OK':
print "ERROR getting message", num
return
msg = email.message_from_string(data[0][1])
print 'Message %s: %s' % (num, msg['Subject'])
print 'Raw Date:', msg['Date']
date_tuple = email.utils.parsedate_tz(msg['Date'])
if date_tuple:
local_date = datetime.datetime.fromtimestamp(
email.utils.mktime_tz(date_tuple))
print "Local Date:", \
local_date.strftime("%a, %d %b %Y %H:%M:%S")