-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgmailer.py
121 lines (110 loc) · 3.32 KB
/
gmailer.py
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#coding: utf-8
import imaplib
import email
from datetime import datetime,timedelta
from aes_cipher import AESCipher
from getpass import getpass
class gmailer(object):
def __init__(self):
cipher = AESCipher(getpass())
try:
id,ps = cipher.read_pass("gmail-id-pass.txt")
except:
print "Cannot read id-pass.txt"
exit()
try:
self.gmail = imaplib.IMAP4_SSL("imap.gmail.com")
self.gmail.login(id,ps)
except:
print "Login Failed."
return
def get_inbox(self):
self.gmail.select("INBOX")
def get_unseen(self):
self.typ, self.data = self.gmail.search(None,"(UNSEEN)")
def get_mailheaders(self,num=5):
if self.typ != "OK" or self.data == "":
print "ERROR: Invalid typ or data"
return
self.data = self.data[0].split()
self.data.reverse()
result_list = []
for mid in self.data[:num]:
result, d = self.gmail.fetch(mid,"(RFC822)")
raw_email = d[0][1]
tmp = []
tmp.append(mid)
try:
msg = email.message_from_string(raw_email.decode("utf-8"))
msg_encoding = "UTF-8" #email.Header.decode_header(msg.get('Subject'))[0][1] or 'iso-2022-jp'
msg = email.message_from_string(raw_email.decode(msg_encoding))
print msg.keys()
try:
fromObj = email.Header.decode_header(msg.get("From"))
addr = ""
for f in fromObj:
if isinstance(f[0],bytes):
addr += f[0].decode(msg_encoding)
else:
addr += f[0]
except:
addr = ""
tmp.append(addr)
try:
dateObj = email.Header.decode_header(msg.get("Date"))
date = self.__date_decode(dateObj)
except:
date = ""
tmp.append(date)
try:
content_type_obj = email.Header.decode_header(msg.get("Content-Type"))
tmp.append(content_type_obj)
except:
tmp.append("")
result_list.append(tmp)
except:
"ERROR: Message encode error"
print result_list
return result_list
def get_body(self,mid):
result, d = self.gmail.fetch(mid,"(RFC822)")
body = ""
raw_email = d[0][1]
try:
msg = email.message_from_string(raw_email.decode("utf-8"))
msg_encoding = email.Header.decode_header(msg.get('Subject'))[0][1] or 'iso-2022-jp'
msg = email.message_from_string(raw_email.decode("iso-2022-jp"))
except:
"ERROR: Message encode error"
return ""
if msg.is_multipart():
for payload in msg.get_payload():
if payload.get_content_type() == "text/plain":
body = payload.get_payload()
else:
if msg.get_content_type() == "text/plain":
body = msg.get_payload()
return body
def __date_decode(self,date):
mon_list = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
date_list = date[0][0].split()[1:]
time_list = date_list[3].split(":")
decoded = datetime(int(date_list[2]), mon_list.index(date_list[1])+1, int(date_list[0]), int(time_list[0]), int(time_list[1]), int(time_list[2]))
decoded = decoded - timedelta(hours=int(date_list[4][1:3]))
return decoded
def close(self):
self.gmail.close()
self.gmail.logout()
if __name__ == "__main__":
import quopri
gm = gmailer()
try:
gm.get_inbox()
gm.get_unseen()
header_list = gm.get_mailheaders(num=1)
print "getbody"
body = gm.get_body(9651)
print quopri.decodestring(body).decode("iso-2022-jp")
finally:
print "gm close"
gm.close()