-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmail.py
More file actions
180 lines (125 loc) · 5.07 KB
/
mail.py
File metadata and controls
180 lines (125 loc) · 5.07 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
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
import imaplib
import email
from email.header import decode_header
from email.policy import default
def decodeMimeWords(s):
decodedFragments = decode_header(s)
decodedString = ""
for fragment, encoding in decodedFragments:
if isinstance(fragment, bytes):
decodedString += fragment.decode(
encoding or "utf-8",
errors="replace"
)
else:
decodedString += fragment
return decodedString
class Account:
def __init__(self, address, password, server):
self.address = address
self.password = password
self.server = server
self.mail = imaplib.IMAP4_SSL(self.server)
self.mail.login(self.address, self.password)
self.mailboxes = [mailbox.decode().split("\"")[3] for mailbox in self.mail.list()[1]]
def getMailSinceDate(self, mailbox, sinceDate, limit=None):
emails = []
try:
self.mail.select("\""+mailbox+"\"")
imapDate = sinceDate.strftime("%d-%b-%Y")
status, messages = self.mail.uid("search", None, f"SINCE \"{imapDate}\"")
if status != "OK":
return emails
if not messages[0]:
return []
uids = messages[0].split()
if limit:
uids = uids[-limit:]
for uid in uids:
status, data = self.mail.uid("fetch", uid, "(BODY.PEEK[HEADER])")
if status != "OK":
continue
if not data or not isinstance(data[0], tuple):
continue
rawEmail = data[0][1]
if not isinstance(rawEmail, bytes):
continue
msg = email.message_from_bytes(rawEmail)
subject = decodeMimeWords(msg.get("subject", ""))
sender = decodeMimeWords(msg.get("from", ""))
date = msg.get("date", "")
emails.append({
"uid": int(uid),
"sender": sender,
"subject": subject,
"date": date
})
return emails
except imaplib.IMAP4.error as e:
print(f"IMAP error: {e}")
return []
def getMailSinceUID(self, mailbox, sinceUid, limit=None):
emails = []
try:
self.mail.select("\""+mailbox+"\"")
status, messages = self.mail.uid("search", None, f"UID {sinceUid + 1}:*")
if status != "OK":
return emails
if not messages[0]:
return []
uids = messages[0].split()
if limit:
uids = uids[-limit:]
for uid in uids:
status, data = self.mail.uid("fetch", uid, "(BODY.PEEK[HEADER])")
if status != "OK":
continue
if not data or not isinstance(data[0], tuple):
continue
rawEmail = data[0][1]
if not isinstance(rawEmail, bytes):
continue
msg = email.message_from_bytes(rawEmail)
subject = decodeMimeWords(msg.get("subject", ""))
sender = decodeMimeWords(msg.get("from", ""))
date = msg.get("date", "")
messageId = msg.get("Message-ID", "")
emails.append({
"uid": int(uid),
"sender": sender,
"subject": subject,
"date": date,
"messageId": messageId
})
return emails
except imaplib.IMAP4.error as e:
print(f"IMAP error: {e}")
return []
def getBody(self, mailbox, uid):
try:
self.mail.select("\""+mailbox+"\"")
result, data = self.mail.uid("fetch", str(uid), "(BODY[])")
if result == "OK" and data:
if isinstance(data[0], tuple):
rawEmail = data[0][1]
msg = email.message_from_bytes(rawEmail, policy=default)
if msg.is_multipart():
for part in msg.walk():
contentType = part.get_content_type()
contentDisposition = part.get("Content-Disposition")
if contentType in ["text/plain", "text/html"] and contentDisposition is None:
return part.get_payload(decode=True).decode()
else:
return msg.get_payload(decode=True).decode()
else:
return f"Error: Unexpected data format for UID {uid}"
else:
return f"Error fetching email with UID {uid}: {result}"
except imaplib.IMAP4.error as e:
print(f"IMAP error: {e}")
return ""
def moveEmail(self, uid, source, destination):
self.mail.select("\""+source+"\"")
self.mail.uid("MOVE", str(uid), destination)
def logout(self):
self.mail.logout()