@mysterycode-liwen/dsh-mail 1.1.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +238 -219
- package/bridge.py +1257 -1131
- package/client.js +580 -163
- package/cordis.patch.yml +8 -8
- package/icon.svg +3 -3
- package/index.js +497 -396
- package/package.json +64 -64
- package/tools.js +158 -158
package/bridge.py
CHANGED
|
@@ -1,1131 +1,1257 @@
|
|
|
1
|
-
#!/usr/bin/env python3
|
|
2
|
-
"""Mail bridge for the DSH mail plugin.
|
|
3
|
-
|
|
4
|
-
Speaks a tiny JSON protocol over the environment: the caller puts one JSON
|
|
5
|
-
request into env var MAIL_REQUEST, this script writes one JSON result to stdout.
|
|
6
|
-
All network work uses Python's standard library (imaplib / smtplib), so the
|
|
7
|
-
Host half of the plugin only needs a subprocess, never raw sockets.
|
|
8
|
-
|
|
9
|
-
Operations
|
|
10
|
-
----------
|
|
11
|
-
test verify IMAP + SMTP connectivity for an account
|
|
12
|
-
listMessages list recent messages from a mailbox folder
|
|
13
|
-
getMessage fetch one message's full body by UID
|
|
14
|
-
getAttachment download one attachment of a message as base64
|
|
15
|
-
sendMessage send a message over SMTP (with attachments)
|
|
16
|
-
listSent read the server's Sent folder (cross-device sync)
|
|
17
|
-
getContacts read the synced contacts stored on the mail server
|
|
18
|
-
setContacts write the synced contacts to the mail server
|
|
19
|
-
collectAndSyncContacts scan + merge + persist contacts in one pass
|
|
20
|
-
"""
|
|
21
|
-
import os
|
|
22
|
-
import sys
|
|
23
|
-
import re
|
|
24
|
-
import base64
|
|
25
|
-
import html as html_mod
|
|
26
|
-
import json
|
|
27
|
-
import imaplib
|
|
28
|
-
import smtplib
|
|
29
|
-
import ssl
|
|
30
|
-
import socket
|
|
31
|
-
from html.parser import HTMLParser
|
|
32
|
-
from email.mime.text import MIMEText
|
|
33
|
-
from email.header import decode_header, make_header
|
|
34
|
-
from email.utils import parsedate_to_datetime, formatdate, getaddresses
|
|
35
|
-
import uuid
|
|
36
|
-
from email.mime.base import MIMEBase
|
|
37
|
-
from email.mime.multipart import MIMEMultipart
|
|
38
|
-
from email import encoders
|
|
39
|
-
|
|
40
|
-
# Local outbox records (mirrored to Sent so they appear in the IMAP Sent folder).
|
|
41
|
-
_OUTBOX_FOLDER = "Sent"
|
|
42
|
-
_CONTACTS_FOLDER = "DSHContacts"
|
|
43
|
-
_CONTACTS_SUBJECT = "dsh-mail-contacts-sync"
|
|
44
|
-
_SENT_FOLDERS = ["Sent", "Sent Messages", "Sent Items", "INBOX.Sent", "Sent Mail",
|
|
45
|
-
"[Gmail]/Sent Mail", "[Gmail]/Sent", "已发送", "已发送邮件"]
|
|
46
|
-
|
|
47
|
-
socket.setdefaulttimeout(20)
|
|
48
|
-
|
|
49
|
-
# Common CJK encodings to try when a part declares no charset or decodes with
|
|
50
|
-
# replacement characters (a frequent cause of mojibake in Chinese mail).
|
|
51
|
-
_FALLBACK_CHARSETS = ("utf-8", "gb18030", "gbk", "big5", "shift_jis", "euc-kr", "latin-1")
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
def decode_bytes(payload, charset=None):
|
|
55
|
-
"""Decode a byte payload, falling back through common charsets on failure."""
|
|
56
|
-
if payload is None:
|
|
57
|
-
return ""
|
|
58
|
-
candidates = []
|
|
59
|
-
if charset:
|
|
60
|
-
candidates.append(charset)
|
|
61
|
-
candidates.extend([c for c in _FALLBACK_CHARSETS if c != charset])
|
|
62
|
-
best = None
|
|
63
|
-
best_score = -1
|
|
64
|
-
for enc in candidates:
|
|
65
|
-
try:
|
|
66
|
-
text = payload.decode(enc)
|
|
67
|
-
except (LookupError, UnicodeDecodeError):
|
|
68
|
-
continue
|
|
69
|
-
# Score: prefer decodes without the replacement char, then ASCII-ish.
|
|
70
|
-
score = 1000 - text.count("\ufffd") * 10
|
|
71
|
-
if best is None or score > best_score:
|
|
72
|
-
best, best_score = text, score
|
|
73
|
-
if "\ufffd" not in text:
|
|
74
|
-
return text
|
|
75
|
-
return best if best is not None else payload.decode("utf-8", errors="replace")
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
# Tags whose *content* must be dropped entirely (scripts, styles, etc.).
|
|
79
|
-
_DROP_CONTENT = {"script", "style", "head", "noscript", "iframe", "object", "embed", "form", "svg"}
|
|
80
|
-
# Tags safe to keep for rich-text email rendering.
|
|
81
|
-
_SAFE_TAGS = {
|
|
82
|
-
"a", "img", "p", "br", "div", "span", "b", "strong", "i", "em", "u", "s", "small",
|
|
83
|
-
"h1", "h2", "h3", "h4", "h5", "h6", "ul", "ol", "li", "blockquote", "pre", "code",
|
|
84
|
-
"table", "thead", "tbody", "tfoot", "tr", "th", "td", "hr", "center", "font", "sub", "sup",
|
|
85
|
-
}
|
|
86
|
-
_SAFE_ATTRS = {
|
|
87
|
-
"a": {"href", "title", "target", "style"},
|
|
88
|
-
"img": {"src", "alt", "title", "width", "height", "style"},
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
class _SafeHTMLParser(HTMLParser):
|
|
93
|
-
"""Keep links/images/basic formatting; strip scripts, events, JS URLs.
|
|
94
|
-
|
|
95
|
-
Inline ``cid:`` images are rewritten to data URIs via ``cid_map`` so they
|
|
96
|
-
render instead of showing as broken images.
|
|
97
|
-
"""
|
|
98
|
-
|
|
99
|
-
def __init__(self, cid_map):
|
|
100
|
-
super().__init__(convert_charrefs=True)
|
|
101
|
-
self.cid_map = cid_map or {}
|
|
102
|
-
self.out = []
|
|
103
|
-
self.drop_depth = 0
|
|
104
|
-
|
|
105
|
-
def handle_starttag(self, tag, attrs):
|
|
106
|
-
tag = tag.lower()
|
|
107
|
-
if tag in _DROP_CONTENT:
|
|
108
|
-
self.drop_depth += 1
|
|
109
|
-
return
|
|
110
|
-
if self.drop_depth or tag not in _SAFE_TAGS:
|
|
111
|
-
return
|
|
112
|
-
allowed = _SAFE_ATTRS.get(tag, set())
|
|
113
|
-
parts = []
|
|
114
|
-
for key, value in attrs:
|
|
115
|
-
key = key.lower()
|
|
116
|
-
if key not in allowed or value is None:
|
|
117
|
-
continue
|
|
118
|
-
value = str(value)
|
|
119
|
-
if key in ("href", "src"):
|
|
120
|
-
low = value.strip().lower().replace("\x00", "")
|
|
121
|
-
# Block script/JS injection.
|
|
122
|
-
if low.startswith(("javascript:", "vbscript:", "file:")):
|
|
123
|
-
continue
|
|
124
|
-
if low.startswith("cid:"):
|
|
125
|
-
data_uri = self.cid_map.get(low[4:].strip("<>"))
|
|
126
|
-
if not data_uri:
|
|
127
|
-
continue
|
|
128
|
-
value = data_uri
|
|
129
|
-
elif low.startswith("data:"):
|
|
130
|
-
# Only allow image data URIs, never script/html data.
|
|
131
|
-
if not low.startswith("data:image/"):
|
|
132
|
-
continue
|
|
133
|
-
elif not low.startswith(("http://", "https://", "mailto:")) and key == "src":
|
|
134
|
-
# Relative image src cannot resolve in this context.
|
|
135
|
-
continue
|
|
136
|
-
parts.append(' %s="%s"' % (key, html_mod.escape(value, quote=True)))
|
|
137
|
-
self.out.append("<%s%s>" % (tag, "".join(parts)))
|
|
138
|
-
|
|
139
|
-
def handle_startendtag(self, tag, attrs):
|
|
140
|
-
self.handle_starttag(tag, attrs)
|
|
141
|
-
if tag.lower() not in _DROP_CONTENT and tag.lower() in _SAFE_TAGS and not self.drop_depth:
|
|
142
|
-
self.out.append("</%s>" % tag.lower())
|
|
143
|
-
|
|
144
|
-
def handle_endtag(self, tag):
|
|
145
|
-
tag = tag.lower()
|
|
146
|
-
if tag in _DROP_CONTENT:
|
|
147
|
-
if self.drop_depth:
|
|
148
|
-
self.drop_depth -= 1
|
|
149
|
-
return
|
|
150
|
-
if self.drop_depth or tag not in _SAFE_TAGS:
|
|
151
|
-
return
|
|
152
|
-
self.out.append("</%s>" % tag)
|
|
153
|
-
|
|
154
|
-
def handle_data(self, data):
|
|
155
|
-
if not self.drop_depth:
|
|
156
|
-
self.out.append(html_mod.escape(data))
|
|
157
|
-
|
|
158
|
-
def result(self):
|
|
159
|
-
return "".join(self.out)
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
def sanitize_html(raw_html, cid_map=None):
|
|
163
|
-
"""Sanitize an HTML email body, keeping links/images and inline cid images."""
|
|
164
|
-
if not raw_html:
|
|
165
|
-
return ""
|
|
166
|
-
parser = _SafeHTMLParser(cid_map)
|
|
167
|
-
try:
|
|
168
|
-
parser.feed(raw_html)
|
|
169
|
-
parser.close()
|
|
170
|
-
except Exception:
|
|
171
|
-
return ""
|
|
172
|
-
return parser.result()
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
def html_to_text(raw_html):
|
|
176
|
-
"""Turn an HTML fragment into readable plain text (no CSS/JS/entity junk)."""
|
|
177
|
-
text = raw_html
|
|
178
|
-
# Remove whole script/style/head blocks *including* their contents — CSS
|
|
179
|
-
# rules like "a { color: ... }" leaking into snippets are the main culprit.
|
|
180
|
-
text = re.sub(r"(?is)<(script|style|head|noscript)[^>]*>.*?</\1\s*>", " ", text)
|
|
181
|
-
text = re.sub(r"(?s)<!--.*?-->", " ", text)
|
|
182
|
-
text = re.sub(r"(?i)<\s*br\s*/?\s*>", "\n", text)
|
|
183
|
-
text = re.sub(r"(?i)</\s*(p|div|tr|li|h[1-6]|table|section|blockquote)\s*>", "\n", text)
|
|
184
|
-
text = re.sub(r"(?s)<[^>]+>", " ", text)
|
|
185
|
-
text = html_mod.unescape(text)
|
|
186
|
-
text = re.sub(r"[ \t\r\f\v]+", " ", text)
|
|
187
|
-
text = re.sub(r"\n\s*\n\s*\n+", "\n\n", text)
|
|
188
|
-
return text.strip()
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
def dec(value):
|
|
192
|
-
"""Decode a possibly RFC2047-encoded header into a readable string."""
|
|
193
|
-
if not value:
|
|
194
|
-
return ""
|
|
195
|
-
try:
|
|
196
|
-
return str(make_header(decode_header(value)))
|
|
197
|
-
except Exception:
|
|
198
|
-
try:
|
|
199
|
-
return str(value)
|
|
200
|
-
except Exception:
|
|
201
|
-
return ""
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
def _decode_part(part):
|
|
205
|
-
"""Decode a MIME part's raw bytes into a string, honouring charset."""
|
|
206
|
-
payload = part.get_payload(decode=True) # applies quoted-printable/base64
|
|
207
|
-
return decode_bytes(payload, part.get_content_charset())
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
def _build_cid_map(msg):
|
|
211
|
-
"""Map inline image Content-IDs to data URIs for rendering inside HTML."""
|
|
212
|
-
cid_map = {}
|
|
213
|
-
for part in msg.walk():
|
|
214
|
-
if part.is_multipart():
|
|
215
|
-
continue
|
|
216
|
-
ctype = part.get_content_type()
|
|
217
|
-
if not ctype.startswith("image/"):
|
|
218
|
-
continue
|
|
219
|
-
cid = part.get("Content-ID") or part.get("X-Attachment-Id")
|
|
220
|
-
if not cid:
|
|
221
|
-
continue
|
|
222
|
-
data = part.get_payload(decode=True)
|
|
223
|
-
if not data:
|
|
224
|
-
continue
|
|
225
|
-
# Guard against embedding huge images (data URI bloats the JSON reply).
|
|
226
|
-
if len(data) > 2 * 1024 * 1024:
|
|
227
|
-
continue
|
|
228
|
-
b64 = base64.b64encode(data).decode("ascii")
|
|
229
|
-
cid_map[cid.strip("<>")] = "data:%s;base64,%s" % (ctype, b64)
|
|
230
|
-
return cid_map
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
def attachments_of(msg):
|
|
234
|
-
"""List downloadable attachments as metadata only (no payload).
|
|
235
|
-
|
|
236
|
-
Inline images referenced by Content-ID are part of the rendered body, not
|
|
237
|
-
attachments, so they are skipped unless the part also carries a filename.
|
|
238
|
-
``index`` is the part's position in ``msg.walk()``; it is stable for the
|
|
239
|
-
same raw message, which lets a later call fetch exactly that part.
|
|
240
|
-
"""
|
|
241
|
-
result = []
|
|
242
|
-
try:
|
|
243
|
-
for idx, part in enumerate(msg.walk()):
|
|
244
|
-
if part.is_multipart():
|
|
245
|
-
continue
|
|
246
|
-
disp = str(part.get("Content-Disposition") or "")
|
|
247
|
-
filename = part.get_filename()
|
|
248
|
-
if not filename and "attachment" not in disp.lower():
|
|
249
|
-
continue
|
|
250
|
-
if "inline" in disp.lower() and not filename:
|
|
251
|
-
continue
|
|
252
|
-
try:
|
|
253
|
-
filename = dec(filename)
|
|
254
|
-
except Exception:
|
|
255
|
-
filename = str(filename or "")
|
|
256
|
-
filename = filename or ("attachment-%d" % idx)
|
|
257
|
-
try:
|
|
258
|
-
size = len(part.get_payload(decode=True) or b"")
|
|
259
|
-
except Exception:
|
|
260
|
-
size = 0
|
|
261
|
-
result.append({
|
|
262
|
-
"index": idx,
|
|
263
|
-
"name": filename,
|
|
264
|
-
"size": size,
|
|
265
|
-
"mime": part.get_content_type(),
|
|
266
|
-
})
|
|
267
|
-
except Exception:
|
|
268
|
-
pass
|
|
269
|
-
return result
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
def body_of(msg, want_html=False):
|
|
273
|
-
"""Extract body content from an email.message.Message.
|
|
274
|
-
|
|
275
|
-
Returns plain text by default (used for snippets). When ``want_html`` is
|
|
276
|
-
True returns a dict ``{"text": ..., "html": ...}`` where ``html`` is a
|
|
277
|
-
sanitized rich-text version with live links and inline images.
|
|
278
|
-
"""
|
|
279
|
-
plain = ""
|
|
280
|
-
rich = ""
|
|
281
|
-
try:
|
|
282
|
-
cid_map = _build_cid_map(msg)
|
|
283
|
-
if msg.is_multipart():
|
|
284
|
-
for part in msg.walk():
|
|
285
|
-
if part.is_multipart():
|
|
286
|
-
continue
|
|
287
|
-
ctype = part.get_content_type()
|
|
288
|
-
disp = str(part.get("Content-Disposition") or "")
|
|
289
|
-
if "attachment" in disp:
|
|
290
|
-
continue
|
|
291
|
-
if ctype == "text/plain" and not plain:
|
|
292
|
-
plain = _decode_part(part)
|
|
293
|
-
elif ctype == "text/html" and not rich:
|
|
294
|
-
raw = _decode_part(part)
|
|
295
|
-
rich = sanitize_html(raw, cid_map)
|
|
296
|
-
if not plain:
|
|
297
|
-
plain = html_to_text(raw)
|
|
298
|
-
if not plain and not rich:
|
|
299
|
-
return "" if not want_html else {"text": "", "html": ""}
|
|
300
|
-
else:
|
|
301
|
-
ctype = msg.get_content_type()
|
|
302
|
-
raw = _decode_part(msg)
|
|
303
|
-
if ctype == "text/html":
|
|
304
|
-
rich = sanitize_html(raw, cid_map)
|
|
305
|
-
plain = html_to_text(raw)
|
|
306
|
-
else:
|
|
307
|
-
plain = raw
|
|
308
|
-
except Exception as exc:
|
|
309
|
-
err = "[body decode error: %s]" % exc
|
|
310
|
-
return err if not want_html else {"text": err, "html": ""}
|
|
311
|
-
|
|
312
|
-
plain = plain[:20000]
|
|
313
|
-
rich = rich[:40000]
|
|
314
|
-
if want_html:
|
|
315
|
-
return {"text": plain, "html": rich or html_mod.escape(plain).replace("\n", "<br>")}
|
|
316
|
-
return plain
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
def imap_connect(acc):
|
|
320
|
-
host = acc["imapHost"]
|
|
321
|
-
port = int(acc.get("imapPort") or 993)
|
|
322
|
-
tls = acc.get("imapTls", True)
|
|
323
|
-
if tls:
|
|
324
|
-
client = imaplib.IMAP4_SSL(host, port)
|
|
325
|
-
else:
|
|
326
|
-
client = imaplib.IMAP4(host, port)
|
|
327
|
-
# Never send credentials in cleartext: require STARTTLS on non-SSL ports.
|
|
328
|
-
try:
|
|
329
|
-
code, _ = client.starttls(ssl.create_default_context())
|
|
330
|
-
if code != "OK":
|
|
331
|
-
raise RuntimeError("server declined STARTTLS (%s)" % code)
|
|
332
|
-
except Exception as exc:
|
|
333
|
-
try:
|
|
334
|
-
client.logout()
|
|
335
|
-
except Exception:
|
|
336
|
-
pass
|
|
337
|
-
raise RuntimeError(
|
|
338
|
-
"IMAP STARTTLS failed: %s — enable TLS and use port 993, or use a server that supports STARTTLS" % exc
|
|
339
|
-
)
|
|
340
|
-
client.login(acc["username"], acc["authCode"])
|
|
341
|
-
return client
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
def smtp_connect(acc):
|
|
345
|
-
host = acc["smtpHost"]
|
|
346
|
-
port = int(acc.get("smtpPort") or 465)
|
|
347
|
-
tls = acc.get("smtpTls", True)
|
|
348
|
-
if tls and port == 465:
|
|
349
|
-
client = smtplib.SMTP_SSL(host, port)
|
|
350
|
-
else:
|
|
351
|
-
client = smtplib.SMTP(host, port)
|
|
352
|
-
client.ehlo()
|
|
353
|
-
if tls:
|
|
354
|
-
client.starttls(context=ssl.create_default_context())
|
|
355
|
-
client.ehlo()
|
|
356
|
-
client.login(acc["username"], acc["authCode"])
|
|
357
|
-
return client
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
def op_test(req):
|
|
361
|
-
acc = req["account"]
|
|
362
|
-
imap = smtp = None
|
|
363
|
-
try:
|
|
364
|
-
imap = imap_connect(acc)
|
|
365
|
-
imap.select("INBOX", readonly=True)
|
|
366
|
-
except Exception as exc:
|
|
367
|
-
return dict(fail_result(exc), stage="imap")
|
|
368
|
-
finally:
|
|
369
|
-
if imap is not None:
|
|
370
|
-
try:
|
|
371
|
-
imap.logout()
|
|
372
|
-
except Exception:
|
|
373
|
-
pass
|
|
374
|
-
try:
|
|
375
|
-
smtp = smtp_connect(acc)
|
|
376
|
-
except Exception as exc:
|
|
377
|
-
return dict(fail_result(exc), stage="smtp")
|
|
378
|
-
finally:
|
|
379
|
-
if smtp is not None:
|
|
380
|
-
try:
|
|
381
|
-
smtp.quit()
|
|
382
|
-
except Exception:
|
|
383
|
-
pass
|
|
384
|
-
return {"ok": True}
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
def _imap_utf7_decode(name):
|
|
389
|
-
"""Decode IMAP modified UTF-7 (&XXXX-) mailbox names into Unicode."""
|
|
390
|
-
if not name or '&' not in name:
|
|
391
|
-
return name
|
|
392
|
-
import base64
|
|
393
|
-
out = []
|
|
394
|
-
i = 0
|
|
395
|
-
while i < len(name):
|
|
396
|
-
ch = name[i]
|
|
397
|
-
if ch == '&':
|
|
398
|
-
j = name.find('-', i + 1)
|
|
399
|
-
if j < 0:
|
|
400
|
-
out.append(ch); i += 1; continue
|
|
401
|
-
chunk = name[i + 1:j]
|
|
402
|
-
if chunk == '':
|
|
403
|
-
out.append('&')
|
|
404
|
-
else:
|
|
405
|
-
try:
|
|
406
|
-
data = base64.b64decode(chunk + '===')
|
|
407
|
-
out.append(data.decode('utf-16-be'))
|
|
408
|
-
except Exception:
|
|
409
|
-
out.append(name[i:j + 1])
|
|
410
|
-
i = j + 1
|
|
411
|
-
else:
|
|
412
|
-
out.append(ch); i += 1
|
|
413
|
-
return ''.join(out)
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
def _mailbox_variants(name):
|
|
417
|
-
"""Both spellings of a mailbox: unicode and IMAP modified UTF-7.
|
|
418
|
-
|
|
419
|
-
LIST returns names in modified UTF-7, which _folder_entries decodes to
|
|
420
|
-
unicode. But SELECT/APPEND expect the UTF-7 spelling again, so always
|
|
421
|
-
offer both.
|
|
422
|
-
"""
|
|
423
|
-
variants = [name]
|
|
424
|
-
try:
|
|
425
|
-
utf7 = None
|
|
426
|
-
if '&' in name:
|
|
427
|
-
utf7 = name # already in UTF-7; offer the decoded unicode form
|
|
428
|
-
decoded = _imap_utf7_decode(name)
|
|
429
|
-
if decoded not in variants:
|
|
430
|
-
variants.append(decoded)
|
|
431
|
-
else:
|
|
432
|
-
utf7 = name.encode('utf-7').decode('ascii').replace('+', '&')
|
|
433
|
-
if utf7 and utf7 not in variants:
|
|
434
|
-
variants.append(utf7)
|
|
435
|
-
except Exception:
|
|
436
|
-
pass
|
|
437
|
-
return variants
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
def _folder_entries(client):
|
|
441
|
-
"""Parse IMAP LIST into [(name, flags)] robustly.
|
|
442
|
-
|
|
443
|
-
IMAP LIST looks like: (\\HasNoChildren \\Sent) "/" "Sent Items"
|
|
444
|
-
The mailbox name is everything AFTER the delimiter and may itself contain
|
|
445
|
-
spaces, so it must never be found by splitting on whitespace.
|
|
446
|
-
"""
|
|
447
|
-
entries = []
|
|
448
|
-
try:
|
|
449
|
-
typ, boxes = client.list()
|
|
450
|
-
if typ != "OK":
|
|
451
|
-
return entries
|
|
452
|
-
for box in boxes or []:
|
|
453
|
-
text = box.decode("utf-8", errors="replace") if isinstance(box, bytes) else str(box)
|
|
454
|
-
# Strip an optional "* LIST " / "* XLIST " status prefix.
|
|
455
|
-
text = re.sub(r"^\s*\*\s+(?:X?LIST)\s+", "", text, flags=re.IGNORECASE)
|
|
456
|
-
# flags (...) | delimiter ("x" or NIL) | mailbox name (rest)
|
|
457
|
-
m = re.match(r'^\s*(\(([^)]*)\))?\s*("(?:[^"\\]|\\.)*"|NIL)\s+(.+?)\s*$', text)
|
|
458
|
-
if not m:
|
|
459
|
-
continue
|
|
460
|
-
flags = m.group(2) or ""
|
|
461
|
-
name = m.group(4).strip()
|
|
462
|
-
if len(name) >= 2 and name[0] == '"' and name[-1] == '"':
|
|
463
|
-
name = name[1:-1].replace('\\"', '"').replace('\\\\', '\\')
|
|
464
|
-
if name:
|
|
465
|
-
entries.append((_imap_utf7_decode(name), flags))
|
|
466
|
-
except Exception:
|
|
467
|
-
pass
|
|
468
|
-
return entries
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
def _folder_names(client):
|
|
472
|
-
"""Mailbox names from an IMAP LIST response."""
|
|
473
|
-
return [name for name, _flags in _folder_entries(client)]
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
def _find_sent_folder(client):
|
|
477
|
-
"""One Sent folder (SPECIAL-USE first) for APPEND / single-folder scans."""
|
|
478
|
-
folders = _sent_folders(client)
|
|
479
|
-
return folders[0] if folders else None
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
def _sent_folders(client):
|
|
483
|
-
"""All folders that look like Sent, so no provider's mail is missed."""
|
|
484
|
-
entries = _folder_entries(client)
|
|
485
|
-
special = [name for name, flags in entries if "\\Sent" in flags]
|
|
486
|
-
named = []
|
|
487
|
-
for cand in _SENT_FOLDERS:
|
|
488
|
-
for name, _flags in entries:
|
|
489
|
-
if name not in special and cand.lower() in name.lower() and name not in named:
|
|
490
|
-
named.append(name)
|
|
491
|
-
result = []
|
|
492
|
-
for name in special + named:
|
|
493
|
-
if name not in result:
|
|
494
|
-
result.append(name)
|
|
495
|
-
return result
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
def _imap_close(client):
|
|
499
|
-
"""Best-effort, exception-safe IMAP teardown."""
|
|
500
|
-
try:
|
|
501
|
-
client.close()
|
|
502
|
-
except Exception:
|
|
503
|
-
pass
|
|
504
|
-
try:
|
|
505
|
-
client.logout()
|
|
506
|
-
except Exception:
|
|
507
|
-
pass
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
def
|
|
511
|
-
"""
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
for
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
"
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
#
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
acc
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
if
|
|
947
|
-
continue
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
"
|
|
1106
|
-
"
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Mail bridge for the DSH mail plugin.
|
|
3
|
+
|
|
4
|
+
Speaks a tiny JSON protocol over the environment: the caller puts one JSON
|
|
5
|
+
request into env var MAIL_REQUEST, this script writes one JSON result to stdout.
|
|
6
|
+
All network work uses Python's standard library (imaplib / smtplib), so the
|
|
7
|
+
Host half of the plugin only needs a subprocess, never raw sockets.
|
|
8
|
+
|
|
9
|
+
Operations
|
|
10
|
+
----------
|
|
11
|
+
test verify IMAP + SMTP connectivity for an account
|
|
12
|
+
listMessages list recent messages from a mailbox folder
|
|
13
|
+
getMessage fetch one message's full body by UID
|
|
14
|
+
getAttachment download one attachment of a message as base64
|
|
15
|
+
sendMessage send a message over SMTP (with attachments)
|
|
16
|
+
listSent read the server's Sent folder (cross-device sync)
|
|
17
|
+
getContacts read the synced contacts stored on the mail server
|
|
18
|
+
setContacts write the synced contacts to the mail server
|
|
19
|
+
collectAndSyncContacts scan + merge + persist contacts in one pass
|
|
20
|
+
"""
|
|
21
|
+
import os
|
|
22
|
+
import sys
|
|
23
|
+
import re
|
|
24
|
+
import base64
|
|
25
|
+
import html as html_mod
|
|
26
|
+
import json
|
|
27
|
+
import imaplib
|
|
28
|
+
import smtplib
|
|
29
|
+
import ssl
|
|
30
|
+
import socket
|
|
31
|
+
from html.parser import HTMLParser
|
|
32
|
+
from email.mime.text import MIMEText
|
|
33
|
+
from email.header import decode_header, make_header
|
|
34
|
+
from email.utils import parsedate_to_datetime, formatdate, getaddresses
|
|
35
|
+
import uuid
|
|
36
|
+
from email.mime.base import MIMEBase
|
|
37
|
+
from email.mime.multipart import MIMEMultipart
|
|
38
|
+
from email import encoders
|
|
39
|
+
|
|
40
|
+
# Local outbox records (mirrored to Sent so they appear in the IMAP Sent folder).
|
|
41
|
+
_OUTBOX_FOLDER = "Sent"
|
|
42
|
+
_CONTACTS_FOLDER = "DSHContacts"
|
|
43
|
+
_CONTACTS_SUBJECT = "dsh-mail-contacts-sync"
|
|
44
|
+
_SENT_FOLDERS = ["Sent", "Sent Messages", "Sent Items", "INBOX.Sent", "Sent Mail",
|
|
45
|
+
"[Gmail]/Sent Mail", "[Gmail]/Sent", "已发送", "已发送邮件"]
|
|
46
|
+
|
|
47
|
+
socket.setdefaulttimeout(20)
|
|
48
|
+
|
|
49
|
+
# Common CJK encodings to try when a part declares no charset or decodes with
|
|
50
|
+
# replacement characters (a frequent cause of mojibake in Chinese mail).
|
|
51
|
+
_FALLBACK_CHARSETS = ("utf-8", "gb18030", "gbk", "big5", "shift_jis", "euc-kr", "latin-1")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def decode_bytes(payload, charset=None):
|
|
55
|
+
"""Decode a byte payload, falling back through common charsets on failure."""
|
|
56
|
+
if payload is None:
|
|
57
|
+
return ""
|
|
58
|
+
candidates = []
|
|
59
|
+
if charset:
|
|
60
|
+
candidates.append(charset)
|
|
61
|
+
candidates.extend([c for c in _FALLBACK_CHARSETS if c != charset])
|
|
62
|
+
best = None
|
|
63
|
+
best_score = -1
|
|
64
|
+
for enc in candidates:
|
|
65
|
+
try:
|
|
66
|
+
text = payload.decode(enc)
|
|
67
|
+
except (LookupError, UnicodeDecodeError):
|
|
68
|
+
continue
|
|
69
|
+
# Score: prefer decodes without the replacement char, then ASCII-ish.
|
|
70
|
+
score = 1000 - text.count("\ufffd") * 10
|
|
71
|
+
if best is None or score > best_score:
|
|
72
|
+
best, best_score = text, score
|
|
73
|
+
if "\ufffd" not in text:
|
|
74
|
+
return text
|
|
75
|
+
return best if best is not None else payload.decode("utf-8", errors="replace")
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
# Tags whose *content* must be dropped entirely (scripts, styles, etc.).
|
|
79
|
+
_DROP_CONTENT = {"script", "style", "head", "noscript", "iframe", "object", "embed", "form", "svg"}
|
|
80
|
+
# Tags safe to keep for rich-text email rendering.
|
|
81
|
+
_SAFE_TAGS = {
|
|
82
|
+
"a", "img", "p", "br", "div", "span", "b", "strong", "i", "em", "u", "s", "small",
|
|
83
|
+
"h1", "h2", "h3", "h4", "h5", "h6", "ul", "ol", "li", "blockquote", "pre", "code",
|
|
84
|
+
"table", "thead", "tbody", "tfoot", "tr", "th", "td", "hr", "center", "font", "sub", "sup",
|
|
85
|
+
}
|
|
86
|
+
_SAFE_ATTRS = {
|
|
87
|
+
"a": {"href", "title", "target", "style"},
|
|
88
|
+
"img": {"src", "alt", "title", "width", "height", "style"},
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class _SafeHTMLParser(HTMLParser):
|
|
93
|
+
"""Keep links/images/basic formatting; strip scripts, events, JS URLs.
|
|
94
|
+
|
|
95
|
+
Inline ``cid:`` images are rewritten to data URIs via ``cid_map`` so they
|
|
96
|
+
render instead of showing as broken images.
|
|
97
|
+
"""
|
|
98
|
+
|
|
99
|
+
def __init__(self, cid_map):
|
|
100
|
+
super().__init__(convert_charrefs=True)
|
|
101
|
+
self.cid_map = cid_map or {}
|
|
102
|
+
self.out = []
|
|
103
|
+
self.drop_depth = 0
|
|
104
|
+
|
|
105
|
+
def handle_starttag(self, tag, attrs):
|
|
106
|
+
tag = tag.lower()
|
|
107
|
+
if tag in _DROP_CONTENT:
|
|
108
|
+
self.drop_depth += 1
|
|
109
|
+
return
|
|
110
|
+
if self.drop_depth or tag not in _SAFE_TAGS:
|
|
111
|
+
return
|
|
112
|
+
allowed = _SAFE_ATTRS.get(tag, set())
|
|
113
|
+
parts = []
|
|
114
|
+
for key, value in attrs:
|
|
115
|
+
key = key.lower()
|
|
116
|
+
if key not in allowed or value is None:
|
|
117
|
+
continue
|
|
118
|
+
value = str(value)
|
|
119
|
+
if key in ("href", "src"):
|
|
120
|
+
low = value.strip().lower().replace("\x00", "")
|
|
121
|
+
# Block script/JS injection.
|
|
122
|
+
if low.startswith(("javascript:", "vbscript:", "file:")):
|
|
123
|
+
continue
|
|
124
|
+
if low.startswith("cid:"):
|
|
125
|
+
data_uri = self.cid_map.get(low[4:].strip("<>"))
|
|
126
|
+
if not data_uri:
|
|
127
|
+
continue
|
|
128
|
+
value = data_uri
|
|
129
|
+
elif low.startswith("data:"):
|
|
130
|
+
# Only allow image data URIs, never script/html data.
|
|
131
|
+
if not low.startswith("data:image/"):
|
|
132
|
+
continue
|
|
133
|
+
elif not low.startswith(("http://", "https://", "mailto:")) and key == "src":
|
|
134
|
+
# Relative image src cannot resolve in this context.
|
|
135
|
+
continue
|
|
136
|
+
parts.append(' %s="%s"' % (key, html_mod.escape(value, quote=True)))
|
|
137
|
+
self.out.append("<%s%s>" % (tag, "".join(parts)))
|
|
138
|
+
|
|
139
|
+
def handle_startendtag(self, tag, attrs):
|
|
140
|
+
self.handle_starttag(tag, attrs)
|
|
141
|
+
if tag.lower() not in _DROP_CONTENT and tag.lower() in _SAFE_TAGS and not self.drop_depth:
|
|
142
|
+
self.out.append("</%s>" % tag.lower())
|
|
143
|
+
|
|
144
|
+
def handle_endtag(self, tag):
|
|
145
|
+
tag = tag.lower()
|
|
146
|
+
if tag in _DROP_CONTENT:
|
|
147
|
+
if self.drop_depth:
|
|
148
|
+
self.drop_depth -= 1
|
|
149
|
+
return
|
|
150
|
+
if self.drop_depth or tag not in _SAFE_TAGS:
|
|
151
|
+
return
|
|
152
|
+
self.out.append("</%s>" % tag)
|
|
153
|
+
|
|
154
|
+
def handle_data(self, data):
|
|
155
|
+
if not self.drop_depth:
|
|
156
|
+
self.out.append(html_mod.escape(data))
|
|
157
|
+
|
|
158
|
+
def result(self):
|
|
159
|
+
return "".join(self.out)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def sanitize_html(raw_html, cid_map=None):
|
|
163
|
+
"""Sanitize an HTML email body, keeping links/images and inline cid images."""
|
|
164
|
+
if not raw_html:
|
|
165
|
+
return ""
|
|
166
|
+
parser = _SafeHTMLParser(cid_map)
|
|
167
|
+
try:
|
|
168
|
+
parser.feed(raw_html)
|
|
169
|
+
parser.close()
|
|
170
|
+
except Exception:
|
|
171
|
+
return ""
|
|
172
|
+
return parser.result()
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def html_to_text(raw_html):
|
|
176
|
+
"""Turn an HTML fragment into readable plain text (no CSS/JS/entity junk)."""
|
|
177
|
+
text = raw_html
|
|
178
|
+
# Remove whole script/style/head blocks *including* their contents — CSS
|
|
179
|
+
# rules like "a { color: ... }" leaking into snippets are the main culprit.
|
|
180
|
+
text = re.sub(r"(?is)<(script|style|head|noscript)[^>]*>.*?</\1\s*>", " ", text)
|
|
181
|
+
text = re.sub(r"(?s)<!--.*?-->", " ", text)
|
|
182
|
+
text = re.sub(r"(?i)<\s*br\s*/?\s*>", "\n", text)
|
|
183
|
+
text = re.sub(r"(?i)</\s*(p|div|tr|li|h[1-6]|table|section|blockquote)\s*>", "\n", text)
|
|
184
|
+
text = re.sub(r"(?s)<[^>]+>", " ", text)
|
|
185
|
+
text = html_mod.unescape(text)
|
|
186
|
+
text = re.sub(r"[ \t\r\f\v]+", " ", text)
|
|
187
|
+
text = re.sub(r"\n\s*\n\s*\n+", "\n\n", text)
|
|
188
|
+
return text.strip()
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def dec(value):
|
|
192
|
+
"""Decode a possibly RFC2047-encoded header into a readable string."""
|
|
193
|
+
if not value:
|
|
194
|
+
return ""
|
|
195
|
+
try:
|
|
196
|
+
return str(make_header(decode_header(value)))
|
|
197
|
+
except Exception:
|
|
198
|
+
try:
|
|
199
|
+
return str(value)
|
|
200
|
+
except Exception:
|
|
201
|
+
return ""
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _decode_part(part):
|
|
205
|
+
"""Decode a MIME part's raw bytes into a string, honouring charset."""
|
|
206
|
+
payload = part.get_payload(decode=True) # applies quoted-printable/base64
|
|
207
|
+
return decode_bytes(payload, part.get_content_charset())
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _build_cid_map(msg):
|
|
211
|
+
"""Map inline image Content-IDs to data URIs for rendering inside HTML."""
|
|
212
|
+
cid_map = {}
|
|
213
|
+
for part in msg.walk():
|
|
214
|
+
if part.is_multipart():
|
|
215
|
+
continue
|
|
216
|
+
ctype = part.get_content_type()
|
|
217
|
+
if not ctype.startswith("image/"):
|
|
218
|
+
continue
|
|
219
|
+
cid = part.get("Content-ID") or part.get("X-Attachment-Id")
|
|
220
|
+
if not cid:
|
|
221
|
+
continue
|
|
222
|
+
data = part.get_payload(decode=True)
|
|
223
|
+
if not data:
|
|
224
|
+
continue
|
|
225
|
+
# Guard against embedding huge images (data URI bloats the JSON reply).
|
|
226
|
+
if len(data) > 2 * 1024 * 1024:
|
|
227
|
+
continue
|
|
228
|
+
b64 = base64.b64encode(data).decode("ascii")
|
|
229
|
+
cid_map[cid.strip("<>")] = "data:%s;base64,%s" % (ctype, b64)
|
|
230
|
+
return cid_map
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def attachments_of(msg):
|
|
234
|
+
"""List downloadable attachments as metadata only (no payload).
|
|
235
|
+
|
|
236
|
+
Inline images referenced by Content-ID are part of the rendered body, not
|
|
237
|
+
attachments, so they are skipped unless the part also carries a filename.
|
|
238
|
+
``index`` is the part's position in ``msg.walk()``; it is stable for the
|
|
239
|
+
same raw message, which lets a later call fetch exactly that part.
|
|
240
|
+
"""
|
|
241
|
+
result = []
|
|
242
|
+
try:
|
|
243
|
+
for idx, part in enumerate(msg.walk()):
|
|
244
|
+
if part.is_multipart():
|
|
245
|
+
continue
|
|
246
|
+
disp = str(part.get("Content-Disposition") or "")
|
|
247
|
+
filename = part.get_filename()
|
|
248
|
+
if not filename and "attachment" not in disp.lower():
|
|
249
|
+
continue
|
|
250
|
+
if "inline" in disp.lower() and not filename:
|
|
251
|
+
continue
|
|
252
|
+
try:
|
|
253
|
+
filename = dec(filename)
|
|
254
|
+
except Exception:
|
|
255
|
+
filename = str(filename or "")
|
|
256
|
+
filename = filename or ("attachment-%d" % idx)
|
|
257
|
+
try:
|
|
258
|
+
size = len(part.get_payload(decode=True) or b"")
|
|
259
|
+
except Exception:
|
|
260
|
+
size = 0
|
|
261
|
+
result.append({
|
|
262
|
+
"index": idx,
|
|
263
|
+
"name": filename,
|
|
264
|
+
"size": size,
|
|
265
|
+
"mime": part.get_content_type(),
|
|
266
|
+
})
|
|
267
|
+
except Exception:
|
|
268
|
+
pass
|
|
269
|
+
return result
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def body_of(msg, want_html=False):
|
|
273
|
+
"""Extract body content from an email.message.Message.
|
|
274
|
+
|
|
275
|
+
Returns plain text by default (used for snippets). When ``want_html`` is
|
|
276
|
+
True returns a dict ``{"text": ..., "html": ...}`` where ``html`` is a
|
|
277
|
+
sanitized rich-text version with live links and inline images.
|
|
278
|
+
"""
|
|
279
|
+
plain = ""
|
|
280
|
+
rich = ""
|
|
281
|
+
try:
|
|
282
|
+
cid_map = _build_cid_map(msg)
|
|
283
|
+
if msg.is_multipart():
|
|
284
|
+
for part in msg.walk():
|
|
285
|
+
if part.is_multipart():
|
|
286
|
+
continue
|
|
287
|
+
ctype = part.get_content_type()
|
|
288
|
+
disp = str(part.get("Content-Disposition") or "")
|
|
289
|
+
if "attachment" in disp:
|
|
290
|
+
continue
|
|
291
|
+
if ctype == "text/plain" and not plain:
|
|
292
|
+
plain = _decode_part(part)
|
|
293
|
+
elif ctype == "text/html" and not rich:
|
|
294
|
+
raw = _decode_part(part)
|
|
295
|
+
rich = sanitize_html(raw, cid_map)
|
|
296
|
+
if not plain:
|
|
297
|
+
plain = html_to_text(raw)
|
|
298
|
+
if not plain and not rich:
|
|
299
|
+
return "" if not want_html else {"text": "", "html": ""}
|
|
300
|
+
else:
|
|
301
|
+
ctype = msg.get_content_type()
|
|
302
|
+
raw = _decode_part(msg)
|
|
303
|
+
if ctype == "text/html":
|
|
304
|
+
rich = sanitize_html(raw, cid_map)
|
|
305
|
+
plain = html_to_text(raw)
|
|
306
|
+
else:
|
|
307
|
+
plain = raw
|
|
308
|
+
except Exception as exc:
|
|
309
|
+
err = "[body decode error: %s]" % exc
|
|
310
|
+
return err if not want_html else {"text": err, "html": ""}
|
|
311
|
+
|
|
312
|
+
plain = plain[:20000]
|
|
313
|
+
rich = rich[:40000]
|
|
314
|
+
if want_html:
|
|
315
|
+
return {"text": plain, "html": rich or html_mod.escape(plain).replace("\n", "<br>")}
|
|
316
|
+
return plain
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def imap_connect(acc):
|
|
320
|
+
host = acc["imapHost"]
|
|
321
|
+
port = int(acc.get("imapPort") or 993)
|
|
322
|
+
tls = acc.get("imapTls", True)
|
|
323
|
+
if tls:
|
|
324
|
+
client = imaplib.IMAP4_SSL(host, port)
|
|
325
|
+
else:
|
|
326
|
+
client = imaplib.IMAP4(host, port)
|
|
327
|
+
# Never send credentials in cleartext: require STARTTLS on non-SSL ports.
|
|
328
|
+
try:
|
|
329
|
+
code, _ = client.starttls(ssl.create_default_context())
|
|
330
|
+
if code != "OK":
|
|
331
|
+
raise RuntimeError("server declined STARTTLS (%s)" % code)
|
|
332
|
+
except Exception as exc:
|
|
333
|
+
try:
|
|
334
|
+
client.logout()
|
|
335
|
+
except Exception:
|
|
336
|
+
pass
|
|
337
|
+
raise RuntimeError(
|
|
338
|
+
"IMAP STARTTLS failed: %s — enable TLS and use port 993, or use a server that supports STARTTLS" % exc
|
|
339
|
+
)
|
|
340
|
+
client.login(acc["username"], acc["authCode"])
|
|
341
|
+
return client
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def smtp_connect(acc):
|
|
345
|
+
host = acc["smtpHost"]
|
|
346
|
+
port = int(acc.get("smtpPort") or 465)
|
|
347
|
+
tls = acc.get("smtpTls", True)
|
|
348
|
+
if tls and port == 465:
|
|
349
|
+
client = smtplib.SMTP_SSL(host, port)
|
|
350
|
+
else:
|
|
351
|
+
client = smtplib.SMTP(host, port)
|
|
352
|
+
client.ehlo()
|
|
353
|
+
if tls:
|
|
354
|
+
client.starttls(context=ssl.create_default_context())
|
|
355
|
+
client.ehlo()
|
|
356
|
+
client.login(acc["username"], acc["authCode"])
|
|
357
|
+
return client
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def op_test(req):
|
|
361
|
+
acc = req["account"]
|
|
362
|
+
imap = smtp = None
|
|
363
|
+
try:
|
|
364
|
+
imap = imap_connect(acc)
|
|
365
|
+
imap.select("INBOX", readonly=True)
|
|
366
|
+
except Exception as exc:
|
|
367
|
+
return dict(fail_result(exc), stage="imap")
|
|
368
|
+
finally:
|
|
369
|
+
if imap is not None:
|
|
370
|
+
try:
|
|
371
|
+
imap.logout()
|
|
372
|
+
except Exception:
|
|
373
|
+
pass
|
|
374
|
+
try:
|
|
375
|
+
smtp = smtp_connect(acc)
|
|
376
|
+
except Exception as exc:
|
|
377
|
+
return dict(fail_result(exc), stage="smtp")
|
|
378
|
+
finally:
|
|
379
|
+
if smtp is not None:
|
|
380
|
+
try:
|
|
381
|
+
smtp.quit()
|
|
382
|
+
except Exception:
|
|
383
|
+
pass
|
|
384
|
+
return {"ok": True}
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def _imap_utf7_decode(name):
|
|
389
|
+
"""Decode IMAP modified UTF-7 (&XXXX-) mailbox names into Unicode."""
|
|
390
|
+
if not name or '&' not in name:
|
|
391
|
+
return name
|
|
392
|
+
import base64
|
|
393
|
+
out = []
|
|
394
|
+
i = 0
|
|
395
|
+
while i < len(name):
|
|
396
|
+
ch = name[i]
|
|
397
|
+
if ch == '&':
|
|
398
|
+
j = name.find('-', i + 1)
|
|
399
|
+
if j < 0:
|
|
400
|
+
out.append(ch); i += 1; continue
|
|
401
|
+
chunk = name[i + 1:j]
|
|
402
|
+
if chunk == '':
|
|
403
|
+
out.append('&')
|
|
404
|
+
else:
|
|
405
|
+
try:
|
|
406
|
+
data = base64.b64decode(chunk + '===')
|
|
407
|
+
out.append(data.decode('utf-16-be'))
|
|
408
|
+
except Exception:
|
|
409
|
+
out.append(name[i:j + 1])
|
|
410
|
+
i = j + 1
|
|
411
|
+
else:
|
|
412
|
+
out.append(ch); i += 1
|
|
413
|
+
return ''.join(out)
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
def _mailbox_variants(name):
|
|
417
|
+
"""Both spellings of a mailbox: unicode and IMAP modified UTF-7.
|
|
418
|
+
|
|
419
|
+
LIST returns names in modified UTF-7, which _folder_entries decodes to
|
|
420
|
+
unicode. But SELECT/APPEND expect the UTF-7 spelling again, so always
|
|
421
|
+
offer both.
|
|
422
|
+
"""
|
|
423
|
+
variants = [name]
|
|
424
|
+
try:
|
|
425
|
+
utf7 = None
|
|
426
|
+
if '&' in name:
|
|
427
|
+
utf7 = name # already in UTF-7; offer the decoded unicode form
|
|
428
|
+
decoded = _imap_utf7_decode(name)
|
|
429
|
+
if decoded not in variants:
|
|
430
|
+
variants.append(decoded)
|
|
431
|
+
else:
|
|
432
|
+
utf7 = name.encode('utf-7').decode('ascii').replace('+', '&')
|
|
433
|
+
if utf7 and utf7 not in variants:
|
|
434
|
+
variants.append(utf7)
|
|
435
|
+
except Exception:
|
|
436
|
+
pass
|
|
437
|
+
return variants
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def _folder_entries(client):
|
|
441
|
+
"""Parse IMAP LIST into [(name, flags)] robustly.
|
|
442
|
+
|
|
443
|
+
IMAP LIST looks like: (\\HasNoChildren \\Sent) "/" "Sent Items"
|
|
444
|
+
The mailbox name is everything AFTER the delimiter and may itself contain
|
|
445
|
+
spaces, so it must never be found by splitting on whitespace.
|
|
446
|
+
"""
|
|
447
|
+
entries = []
|
|
448
|
+
try:
|
|
449
|
+
typ, boxes = client.list()
|
|
450
|
+
if typ != "OK":
|
|
451
|
+
return entries
|
|
452
|
+
for box in boxes or []:
|
|
453
|
+
text = box.decode("utf-8", errors="replace") if isinstance(box, bytes) else str(box)
|
|
454
|
+
# Strip an optional "* LIST " / "* XLIST " status prefix.
|
|
455
|
+
text = re.sub(r"^\s*\*\s+(?:X?LIST)\s+", "", text, flags=re.IGNORECASE)
|
|
456
|
+
# flags (...) | delimiter ("x" or NIL) | mailbox name (rest)
|
|
457
|
+
m = re.match(r'^\s*(\(([^)]*)\))?\s*("(?:[^"\\]|\\.)*"|NIL)\s+(.+?)\s*$', text)
|
|
458
|
+
if not m:
|
|
459
|
+
continue
|
|
460
|
+
flags = m.group(2) or ""
|
|
461
|
+
name = m.group(4).strip()
|
|
462
|
+
if len(name) >= 2 and name[0] == '"' and name[-1] == '"':
|
|
463
|
+
name = name[1:-1].replace('\\"', '"').replace('\\\\', '\\')
|
|
464
|
+
if name:
|
|
465
|
+
entries.append((_imap_utf7_decode(name), flags))
|
|
466
|
+
except Exception:
|
|
467
|
+
pass
|
|
468
|
+
return entries
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
def _folder_names(client):
|
|
472
|
+
"""Mailbox names from an IMAP LIST response."""
|
|
473
|
+
return [name for name, _flags in _folder_entries(client)]
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def _find_sent_folder(client):
|
|
477
|
+
"""One Sent folder (SPECIAL-USE first) for APPEND / single-folder scans."""
|
|
478
|
+
folders = _sent_folders(client)
|
|
479
|
+
return folders[0] if folders else None
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
def _sent_folders(client):
|
|
483
|
+
"""All folders that look like Sent, so no provider's mail is missed."""
|
|
484
|
+
entries = _folder_entries(client)
|
|
485
|
+
special = [name for name, flags in entries if "\\Sent" in flags]
|
|
486
|
+
named = []
|
|
487
|
+
for cand in _SENT_FOLDERS:
|
|
488
|
+
for name, _flags in entries:
|
|
489
|
+
if name not in special and cand.lower() in name.lower() and name not in named:
|
|
490
|
+
named.append(name)
|
|
491
|
+
result = []
|
|
492
|
+
for name in special + named:
|
|
493
|
+
if name not in result:
|
|
494
|
+
result.append(name)
|
|
495
|
+
return result
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
def _imap_close(client):
|
|
499
|
+
"""Best-effort, exception-safe IMAP teardown."""
|
|
500
|
+
try:
|
|
501
|
+
client.close()
|
|
502
|
+
except Exception:
|
|
503
|
+
pass
|
|
504
|
+
try:
|
|
505
|
+
client.logout()
|
|
506
|
+
except Exception:
|
|
507
|
+
pass
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
def _fetch_summary(msg_data):
|
|
511
|
+
"""Parse a partial FETCH reply into ``(message, flags)``.
|
|
512
|
+
|
|
513
|
+
The list view only needs a few headers and a short preview, so we ask IMAP
|
|
514
|
+
for just those instead of the full RFC822 payload (which may carry large
|
|
515
|
+
attachments). ``msg_data`` is imaplib's FETCH tuple list. Returns
|
|
516
|
+
``(None, flags)`` when nothing usable was returned, so the caller can fall
|
|
517
|
+
back to a full fetch.
|
|
518
|
+
"""
|
|
519
|
+
header_bytes = None
|
|
520
|
+
body_bytes = None
|
|
521
|
+
flags = ""
|
|
522
|
+
for item in msg_data:
|
|
523
|
+
if not isinstance(item, tuple) or len(item) < 2:
|
|
524
|
+
continue
|
|
525
|
+
spec = item[0]
|
|
526
|
+
if isinstance(spec, str):
|
|
527
|
+
spec = spec.encode("utf-8", "replace")
|
|
528
|
+
upper = spec.upper()
|
|
529
|
+
if b"BODY[1]" in upper:
|
|
530
|
+
body_bytes = item[1]
|
|
531
|
+
elif b"BODY[HEADER" in upper:
|
|
532
|
+
header_bytes = item[1]
|
|
533
|
+
match = re.search(rb"FLAGS \(([^)]*)\)", spec)
|
|
534
|
+
if match:
|
|
535
|
+
flags = match.group(1).decode(errors="replace")
|
|
536
|
+
if header_bytes is None and body_bytes is None:
|
|
537
|
+
return None, flags
|
|
538
|
+
from email import message_from_bytes
|
|
539
|
+
# HEADER.FIELDS already ends with a blank line; one more separator keeps
|
|
540
|
+
# the body from being swallowed into the header block.
|
|
541
|
+
raw = (header_bytes or b"") + b"\r\n" + (body_bytes or b"")
|
|
542
|
+
return message_from_bytes(raw), flags
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
def _full_message(client, uid):
|
|
546
|
+
"""Last-resort full RFC822 fetch, used only when a partial fetch fails."""
|
|
547
|
+
typ, data = client.uid("FETCH", uid, "(RFC822 FLAGS)")
|
|
548
|
+
if typ != "OK" or not data:
|
|
549
|
+
return None, ""
|
|
550
|
+
from email import message_from_bytes
|
|
551
|
+
first = next((item for item in data if isinstance(item, tuple) and item[1]), None)
|
|
552
|
+
if first is None:
|
|
553
|
+
return None, ""
|
|
554
|
+
flags = ""
|
|
555
|
+
for item in data:
|
|
556
|
+
if not isinstance(item, tuple):
|
|
557
|
+
continue
|
|
558
|
+
match = re.search(rb"FLAGS \(([^)]*)\)", item[0] if isinstance(item[0], bytes) else str(item[0]).encode())
|
|
559
|
+
if match:
|
|
560
|
+
flags = match.group(1).decode(errors="replace")
|
|
561
|
+
break
|
|
562
|
+
return message_from_bytes(first[1]), flags
|
|
563
|
+
|
|
564
|
+
|
|
565
|
+
def _fetch_summaries_bulk(client, uids):
|
|
566
|
+
"""Fetch summary data for many UIDs in a single IMAP round trip.
|
|
567
|
+
|
|
568
|
+
imaplib returns one ``(spec, literal)`` tuple per literal plus plain
|
|
569
|
+
trailer bytes. Each message's first tuple carries ``UID <n>``; later
|
|
570
|
+
literals for that message (the body part) only carry the item name, so we
|
|
571
|
+
carry the current UID forward. Returns ``uid -> (msg, flags)``; UIDs the
|
|
572
|
+
server did not echo are simply absent and the caller falls back to a
|
|
573
|
+
per-UID fetch for those.
|
|
574
|
+
"""
|
|
575
|
+
if not uids:
|
|
576
|
+
return {}
|
|
577
|
+
fetch_spec = "(FLAGS BODY.PEEK[HEADER.FIELDS (FROM TO SUBJECT DATE)] BODY.PEEK[1])"
|
|
578
|
+
uid_set = ",".join(u.decode() if isinstance(u, bytes) else str(u) for u in uids)
|
|
579
|
+
try:
|
|
580
|
+
typ, data = client.uid("FETCH", uid_set, fetch_spec)
|
|
581
|
+
except Exception:
|
|
582
|
+
return {}
|
|
583
|
+
if typ != "OK" or not data:
|
|
584
|
+
return {}
|
|
585
|
+
parts = {} # uid -> [header_bytes, body_bytes, flags]
|
|
586
|
+
current = None
|
|
587
|
+
for item in data:
|
|
588
|
+
if isinstance(item, tuple):
|
|
589
|
+
spec, literal = item[0], item[1]
|
|
590
|
+
elif isinstance(item, bytes):
|
|
591
|
+
spec, literal = item, None
|
|
592
|
+
else:
|
|
593
|
+
continue
|
|
594
|
+
if isinstance(spec, str):
|
|
595
|
+
spec = spec.encode("utf-8", "replace")
|
|
596
|
+
match = re.search(rb"UID\s+(\d+)", spec)
|
|
597
|
+
if match:
|
|
598
|
+
key = match.group(1).decode()
|
|
599
|
+
if key not in parts:
|
|
600
|
+
parts[key] = [None, None, ""]
|
|
601
|
+
current = key
|
|
602
|
+
if current is None:
|
|
603
|
+
continue
|
|
604
|
+
upper = spec.upper()
|
|
605
|
+
if literal is not None and b"BODY[1]" in upper:
|
|
606
|
+
parts[current][1] = literal
|
|
607
|
+
elif literal is not None and b"BODY[HEADER" in upper:
|
|
608
|
+
parts[current][0] = literal
|
|
609
|
+
flags_match = re.search(rb"FLAGS \(([^)]*)\)", spec)
|
|
610
|
+
if flags_match:
|
|
611
|
+
parts[current][2] = flags_match.group(1).decode(errors="replace")
|
|
612
|
+
from email import message_from_bytes
|
|
613
|
+
result = {}
|
|
614
|
+
for key, (header_bytes, body_bytes, flags) in parts.items():
|
|
615
|
+
if header_bytes is None and body_bytes is None:
|
|
616
|
+
continue
|
|
617
|
+
# HEADER.FIELDS ends with a blank line; one more separator keeps the
|
|
618
|
+
# body out of the header block when reassembling the message.
|
|
619
|
+
raw = (header_bytes or b"") + b"\r\n" + (body_bytes or b"")
|
|
620
|
+
try:
|
|
621
|
+
result[key] = (message_from_bytes(raw), flags)
|
|
622
|
+
except Exception:
|
|
623
|
+
pass
|
|
624
|
+
return result
|
|
625
|
+
|
|
626
|
+
|
|
627
|
+
def _list_messages_in(client, folder, limit):
|
|
628
|
+
"""List recent messages of one folder as summary dicts."""
|
|
629
|
+
selected = False
|
|
630
|
+
last = None
|
|
631
|
+
for variant in _mailbox_variants(folder):
|
|
632
|
+
try:
|
|
633
|
+
typ, data = client.select('"%s"' % variant.replace('"', ""), readonly=True)
|
|
634
|
+
except Exception as exc:
|
|
635
|
+
last = exc; continue
|
|
636
|
+
if typ == "OK":
|
|
637
|
+
selected = True; break
|
|
638
|
+
last = imap_data_text(data)
|
|
639
|
+
if not selected:
|
|
640
|
+
return {"ok": False, "error": "\u9009\u62e9\u6587\u4ef6\u5939\u5931\u8d25\uff1a%s" % (last or ""), "code": "folder"}
|
|
641
|
+
typ, data = client.uid("SEARCH", None, "ALL")
|
|
642
|
+
if typ != "OK":
|
|
643
|
+
return {"ok": False, "error": "\u641c\u7d22\u90ae\u4ef6\u5931\u8d25\uff1a%s" % imap_data_text(data), "code": "search"}
|
|
644
|
+
ids = (data[0] or b"").split()
|
|
645
|
+
chosen = ids[-limit:][::-1]
|
|
646
|
+
messages = []
|
|
647
|
+
# Fetch displayed headers, first body part and flags for all UIDs in a
|
|
648
|
+
# single round trip. Servers that do not echo every UID are covered by a
|
|
649
|
+
# per-UID fallback below, so the result stays identical to serial FETCH.
|
|
650
|
+
fetch_spec = "(FLAGS BODY.PEEK[HEADER.FIELDS (FROM TO SUBJECT DATE)] BODY.PEEK[1])"
|
|
651
|
+
bulk = _fetch_summaries_bulk(client, chosen)
|
|
652
|
+
for uid in chosen:
|
|
653
|
+
try:
|
|
654
|
+
key = uid.decode() if isinstance(uid, bytes) else str(uid)
|
|
655
|
+
pair = bulk.get(key)
|
|
656
|
+
if pair is not None:
|
|
657
|
+
msg, flags = pair
|
|
658
|
+
else:
|
|
659
|
+
msg = flags = None
|
|
660
|
+
try:
|
|
661
|
+
typ, msg_data = client.uid("FETCH", uid, fetch_spec)
|
|
662
|
+
if typ == "OK" and msg_data:
|
|
663
|
+
msg, flags = _fetch_summary(msg_data)
|
|
664
|
+
except Exception:
|
|
665
|
+
pass
|
|
666
|
+
if msg is None: # partial fetch failed or returned nothing usable
|
|
667
|
+
msg, flags = _full_message(client, uid)
|
|
668
|
+
if msg is None:
|
|
669
|
+
continue
|
|
670
|
+
date_str = msg.get("Date")
|
|
671
|
+
try:
|
|
672
|
+
date_iso = parsedate_to_datetime(date_str).isoformat() if date_str else None
|
|
673
|
+
except Exception:
|
|
674
|
+
date_iso = date_str
|
|
675
|
+
preview = body_of(msg).strip()[:200]
|
|
676
|
+
messages.append({
|
|
677
|
+
"uid": uid.decode(),
|
|
678
|
+
"from": dec(msg.get("From")),
|
|
679
|
+
"to": dec(msg.get("To")),
|
|
680
|
+
"subject": dec(msg.get("Subject")) or "(no subject)",
|
|
681
|
+
"date": date_iso,
|
|
682
|
+
"snippet": preview,
|
|
683
|
+
"seen": "\\Seen" in flags,
|
|
684
|
+
})
|
|
685
|
+
except Exception:
|
|
686
|
+
continue
|
|
687
|
+
return {"ok": True, "messages": messages, "total": len(ids)}
|
|
688
|
+
|
|
689
|
+
|
|
690
|
+
def op_list_messages(req):
|
|
691
|
+
acc = req["account"]
|
|
692
|
+
folder = req.get("folder") or "INBOX"
|
|
693
|
+
limit = max(1, min(int(req.get("limit") or 20), 100))
|
|
694
|
+
try:
|
|
695
|
+
client = imap_connect(acc)
|
|
696
|
+
except Exception as exc:
|
|
697
|
+
return fail_result(exc)
|
|
698
|
+
try:
|
|
699
|
+
return _list_messages_in(client, folder, limit)
|
|
700
|
+
finally:
|
|
701
|
+
_imap_close(client)
|
|
702
|
+
|
|
703
|
+
|
|
704
|
+
def op_get_message(req):
|
|
705
|
+
acc = req["account"]
|
|
706
|
+
uid = str(req["uid"])
|
|
707
|
+
folder = req.get("folder") or "INBOX"
|
|
708
|
+
try:
|
|
709
|
+
client = imap_connect(acc)
|
|
710
|
+
except Exception as exc:
|
|
711
|
+
return fail_result(exc)
|
|
712
|
+
try:
|
|
713
|
+
# Open the mailbox writable so reading a message can mark it \Seen,
|
|
714
|
+
# matching normal mail-client behaviour. BODY.PEEK reads the content
|
|
715
|
+
# without marking, then we set the flag explicitly so read state
|
|
716
|
+
# persists across reloads. Marking is best-effort and never fails read.
|
|
717
|
+
typ, data = client.select('"%s"' % folder.replace('"', ""), readonly=False)
|
|
718
|
+
if typ != "OK":
|
|
719
|
+
return {"ok": False, "error": "选择文件夹失败:%s" % imap_data_text(data), "code": "folder"}
|
|
720
|
+
typ, msg_data = client.uid("FETCH", str(uid), "(BODY.PEEK[])")
|
|
721
|
+
if typ != "OK" or not msg_data or msg_data[0] is None:
|
|
722
|
+
return {"ok": False, "error": "未找到这封邮件(可能已被删除)。", "code": "not_found"}
|
|
723
|
+
try:
|
|
724
|
+
client.uid("STORE", str(uid), "+FLAGS", "(\\Seen)")
|
|
725
|
+
except Exception:
|
|
726
|
+
pass
|
|
727
|
+
from email import message_from_bytes
|
|
728
|
+
msg = message_from_bytes(msg_data[0][1])
|
|
729
|
+
date_str = msg.get("Date")
|
|
730
|
+
try:
|
|
731
|
+
date_iso = parsedate_to_datetime(date_str).isoformat() if date_str else None
|
|
732
|
+
except Exception:
|
|
733
|
+
date_iso = date_str
|
|
734
|
+
body = body_of(msg, want_html=True)
|
|
735
|
+
return {
|
|
736
|
+
"ok": True,
|
|
737
|
+
"uid": uid,
|
|
738
|
+
"from": dec(msg.get("From")),
|
|
739
|
+
"to": dec(msg.get("To")),
|
|
740
|
+
"subject": dec(msg.get("Subject")) or "(no subject)",
|
|
741
|
+
"date": date_iso,
|
|
742
|
+
"body": body["text"],
|
|
743
|
+
"html": body["html"],
|
|
744
|
+
"attachments": attachments_of(msg),
|
|
745
|
+
}
|
|
746
|
+
finally:
|
|
747
|
+
try:
|
|
748
|
+
client.close()
|
|
749
|
+
except Exception:
|
|
750
|
+
pass
|
|
751
|
+
try:
|
|
752
|
+
client.logout()
|
|
753
|
+
except Exception:
|
|
754
|
+
pass
|
|
755
|
+
|
|
756
|
+
|
|
757
|
+
def op_get_attachment(req):
|
|
758
|
+
"""Return one attachment's bytes as base64, addressed by part index.
|
|
759
|
+
|
|
760
|
+
The index is the position in the message's part walk, as reported by
|
|
761
|
+
``attachments_of`` when the message was read. Reading uses BODY.PEEK so
|
|
762
|
+
downloading an attachment never changes the read/unread flag.
|
|
763
|
+
"""
|
|
764
|
+
acc = req["account"]
|
|
765
|
+
uid = str(req["uid"])
|
|
766
|
+
folder = req.get("folder") or "INBOX"
|
|
767
|
+
index = int(req.get("index") or 0)
|
|
768
|
+
try:
|
|
769
|
+
client = imap_connect(acc)
|
|
770
|
+
except Exception as exc:
|
|
771
|
+
return fail_result(exc)
|
|
772
|
+
try:
|
|
773
|
+
typ, data = client.select('"%s"' % folder.replace('"', ""), readonly=True)
|
|
774
|
+
if typ != "OK":
|
|
775
|
+
return {"ok": False, "error": "选择文件夹失败:%s" % imap_data_text(data), "code": "folder"}
|
|
776
|
+
typ, msg_data = client.uid("FETCH", uid, "(BODY.PEEK[])")
|
|
777
|
+
if typ != "OK" or not msg_data or msg_data[0] is None:
|
|
778
|
+
return {"ok": False, "error": "未找到这封邮件(可能已被删除)。", "code": "not_found"}
|
|
779
|
+
from email import message_from_bytes
|
|
780
|
+
msg = message_from_bytes(msg_data[0][1])
|
|
781
|
+
parts = list(msg.walk())
|
|
782
|
+
if index < 0 or index >= len(parts):
|
|
783
|
+
return {"ok": False, "error": "附件位置已失效,请重新打开邮件。", "code": "not_found"}
|
|
784
|
+
part = parts[index]
|
|
785
|
+
payload = part.get_payload(decode=True)
|
|
786
|
+
if payload is None:
|
|
787
|
+
return {"ok": False, "error": "这个附件没有可下载的内容。", "code": "generic"}
|
|
788
|
+
# Refuse absurdly large payloads: the JSON reply carries the bytes and
|
|
789
|
+
# the Host half buffers the whole bridge response in memory.
|
|
790
|
+
if len(payload) > 25 * 1024 * 1024:
|
|
791
|
+
return {"ok": False, "error": "附件超过 25 MB,暂不支持下载。", "code": "toolarge"}
|
|
792
|
+
filename = dec(part.get_filename()) or ("attachment-%d" % index)
|
|
793
|
+
return {
|
|
794
|
+
"ok": True,
|
|
795
|
+
"name": filename,
|
|
796
|
+
"mime": part.get_content_type(),
|
|
797
|
+
"size": len(payload),
|
|
798
|
+
"content": base64.b64encode(payload).decode("ascii"),
|
|
799
|
+
}
|
|
800
|
+
finally:
|
|
801
|
+
try:
|
|
802
|
+
client.close()
|
|
803
|
+
except Exception:
|
|
804
|
+
pass
|
|
805
|
+
try:
|
|
806
|
+
client.logout()
|
|
807
|
+
except Exception:
|
|
808
|
+
pass
|
|
809
|
+
|
|
810
|
+
|
|
811
|
+
def _contact_entries(addr_header):
|
|
812
|
+
"""Return [{name, email}] from a From/To/Cc header value."""
|
|
813
|
+
result = []
|
|
814
|
+
for name, addr in getaddresses([addr_header or ""]):
|
|
815
|
+
addr = (addr or "").strip()
|
|
816
|
+
if not addr or "@" not in addr:
|
|
817
|
+
continue
|
|
818
|
+
name = dec(name) if name else ""
|
|
819
|
+
result.append({"name": name, "email": addr})
|
|
820
|
+
return result
|
|
821
|
+
|
|
822
|
+
|
|
823
|
+
def _attachment_parts(attachments):
|
|
824
|
+
"""Turn [{name, content(base64)}] into MIMEBase parts."""
|
|
825
|
+
import mimetypes
|
|
826
|
+
parts = []
|
|
827
|
+
for att in attachments or []:
|
|
828
|
+
fname = str(att.get("name") or "attachment")
|
|
829
|
+
try:
|
|
830
|
+
data = base64.b64decode(att.get("content") or "")
|
|
831
|
+
except Exception:
|
|
832
|
+
data = b""
|
|
833
|
+
mime = str(att.get("mime") or "").strip()
|
|
834
|
+
if "/" not in mime:
|
|
835
|
+
mime = mimetypes.guess_type(fname)[0] or "application/octet-stream"
|
|
836
|
+
maintype, subtype = mime.split("/", 1)
|
|
837
|
+
part = MIMEBase(maintype, subtype)
|
|
838
|
+
part.set_payload(data)
|
|
839
|
+
encoders.encode_base64(part)
|
|
840
|
+
safe = fname.replace("\r", "").replace("\n", "")
|
|
841
|
+
# RFC 2231 encoding keeps non-ASCII filenames intact for clients.
|
|
842
|
+
part.add_header("Content-Disposition", "attachment", filename=("utf-8", "", safe))
|
|
843
|
+
parts.append(part)
|
|
844
|
+
return parts
|
|
845
|
+
|
|
846
|
+
|
|
847
|
+
def build_message(acc, recipients, subject, body, attachments=None):
|
|
848
|
+
"""Build the outgoing message, multipart only when attachments exist."""
|
|
849
|
+
attachments = attachments or []
|
|
850
|
+
if attachments:
|
|
851
|
+
msg = MIMEMultipart("mixed")
|
|
852
|
+
msg.attach(MIMEText(body or "", "plain", "utf-8"))
|
|
853
|
+
for part in _attachment_parts(attachments):
|
|
854
|
+
msg.attach(part)
|
|
855
|
+
else:
|
|
856
|
+
msg = MIMEText(body or "", "plain", "utf-8")
|
|
857
|
+
msg["From"] = acc["username"]
|
|
858
|
+
msg["To"] = ", ".join(recipients)
|
|
859
|
+
msg["Subject"] = subject or ""
|
|
860
|
+
msg["Date"] = formatdate(localtime=True)
|
|
861
|
+
msg["Message-ID"] = "<%s@%s>" % (uuid.uuid4().hex, acc["username"].split("@")[-1] or "local")
|
|
862
|
+
return msg
|
|
863
|
+
|
|
864
|
+
|
|
865
|
+
def _append_to_sent(acc, recipients, subject, body, attachments=None):
|
|
866
|
+
"""Mirror a successfully sent message into the IMAP Sent folder.
|
|
867
|
+
|
|
868
|
+
Failures here never block the send: the message was already delivered.
|
|
869
|
+
"""
|
|
870
|
+
client = None
|
|
871
|
+
try:
|
|
872
|
+
msg = build_message(acc, recipients, subject, body, attachments)
|
|
873
|
+
client = imap_connect(acc)
|
|
874
|
+
sent_folder = _find_sent_folder(client) or _OUTBOX_FOLDER
|
|
875
|
+
try:
|
|
876
|
+
client.append('"%s"' % sent_folder.replace('"', ""), None, None, msg.as_bytes())
|
|
877
|
+
except Exception:
|
|
878
|
+
# Some servers only allow APPEND to INBOX; fall back there so the
|
|
879
|
+
# record is still retrievable, then the caller can list the folder.
|
|
880
|
+
try:
|
|
881
|
+
client.append("INBOX", None, None, msg.as_bytes())
|
|
882
|
+
except Exception:
|
|
883
|
+
pass
|
|
884
|
+
except Exception:
|
|
885
|
+
pass
|
|
886
|
+
finally:
|
|
887
|
+
if client is not None:
|
|
888
|
+
try:
|
|
889
|
+
client.close()
|
|
890
|
+
except Exception:
|
|
891
|
+
pass
|
|
892
|
+
try:
|
|
893
|
+
client.logout()
|
|
894
|
+
except Exception:
|
|
895
|
+
pass
|
|
896
|
+
|
|
897
|
+
|
|
898
|
+
def op_send_message(req):
|
|
899
|
+
acc = req["account"]
|
|
900
|
+
to = req["to"]
|
|
901
|
+
subject = req.get("subject") or ""
|
|
902
|
+
body = req.get("body") or ""
|
|
903
|
+
attachments = req.get("attachments") or []
|
|
904
|
+
# Multiple recipients are comma/semicolon separated; SMTP sendmail takes a
|
|
905
|
+
# list, and the MIME headers keep the original recipients visible.
|
|
906
|
+
recipients = [a.strip() for a in re.split(r"[,;\s]+", str(to)) if a.strip()]
|
|
907
|
+
if not recipients:
|
|
908
|
+
return {"ok": False, "error": "收件人不能为空。", "code": "generic"}
|
|
909
|
+
msg = build_message(acc, recipients, subject, body, attachments)
|
|
910
|
+
try:
|
|
911
|
+
client = smtp_connect(acc)
|
|
912
|
+
except Exception as exc:
|
|
913
|
+
return fail_result(exc)
|
|
914
|
+
try:
|
|
915
|
+
client.sendmail(acc["username"], recipients, msg.as_string())
|
|
916
|
+
except Exception as exc:
|
|
917
|
+
return fail_result(exc)
|
|
918
|
+
finally:
|
|
919
|
+
try:
|
|
920
|
+
client.quit()
|
|
921
|
+
except Exception:
|
|
922
|
+
pass
|
|
923
|
+
# Delivery succeeded — mirror to Sent so the outbox is backed by the real
|
|
924
|
+
# mailbox, independent of any one device.
|
|
925
|
+
_append_to_sent(acc, recipients, subject, body, attachments)
|
|
926
|
+
return {"ok": True}
|
|
927
|
+
|
|
928
|
+
|
|
929
|
+
def op_collect_contacts(req):
|
|
930
|
+
"""Scan IMAP folders for addresses and return unique {name,email} entries."""
|
|
931
|
+
acc = req["account"]
|
|
932
|
+
limit = max(1, min(int(req.get("limit") or 30), 60))
|
|
933
|
+
try:
|
|
934
|
+
client = imap_connect(acc)
|
|
935
|
+
except Exception as exc:
|
|
936
|
+
return fail_result(exc)
|
|
937
|
+
contacts = {}
|
|
938
|
+
try:
|
|
939
|
+
folders = ["INBOX"]
|
|
940
|
+
sent = _find_sent_folder(client)
|
|
941
|
+
if sent:
|
|
942
|
+
folders.append(sent)
|
|
943
|
+
for folder in folders[:4]:
|
|
944
|
+
try:
|
|
945
|
+
typ, _ = client.select('"%s"' % folder.replace('"', ""), readonly=True)
|
|
946
|
+
if typ != "OK":
|
|
947
|
+
continue
|
|
948
|
+
typ, data = client.uid("SEARCH", None, "ALL")
|
|
949
|
+
if typ != "OK" or not data or not data[0]:
|
|
950
|
+
continue
|
|
951
|
+
ids = data[0].split()
|
|
952
|
+
for uid in ids[-limit:]:
|
|
953
|
+
try:
|
|
954
|
+
typ, md = client.uid("FETCH", uid, "(BODY.PEEK[HEADER.FIELDS (FROM TO CC)])")
|
|
955
|
+
if typ != "OK" or not md or md[0] is None:
|
|
956
|
+
continue
|
|
957
|
+
head = md[0][1]
|
|
958
|
+
if isinstance(head, bytes):
|
|
959
|
+
head = head.decode("utf-8", errors="replace")
|
|
960
|
+
from email import message_from_string
|
|
961
|
+
m = message_from_string(head)
|
|
962
|
+
for h in ("From", "To", "Cc"):
|
|
963
|
+
for entry in _contact_entries(m.get(h)):
|
|
964
|
+
key = entry["email"].lower()
|
|
965
|
+
if key not in contacts:
|
|
966
|
+
contacts[key] = entry
|
|
967
|
+
except Exception:
|
|
968
|
+
continue
|
|
969
|
+
except Exception:
|
|
970
|
+
continue
|
|
971
|
+
result = []
|
|
972
|
+
for entry in contacts.values():
|
|
973
|
+
if entry["email"].lower() == acc.get("username", "").lower():
|
|
974
|
+
continue
|
|
975
|
+
result.append(entry)
|
|
976
|
+
result.sort(key=lambda c: (c["name"] or c["email"]).lower())
|
|
977
|
+
return {"ok": True, "contacts": result}
|
|
978
|
+
finally:
|
|
979
|
+
try:
|
|
980
|
+
client.close()
|
|
981
|
+
except Exception:
|
|
982
|
+
pass
|
|
983
|
+
try:
|
|
984
|
+
client.logout()
|
|
985
|
+
except Exception:
|
|
986
|
+
pass
|
|
987
|
+
|
|
988
|
+
|
|
989
|
+
def _decode_bytes_literal(token):
|
|
990
|
+
"""Decode a Python bytes literal (b'...') into readable text."""
|
|
991
|
+
try:
|
|
992
|
+
import ast
|
|
993
|
+
value = ast.literal_eval(token)
|
|
994
|
+
if isinstance(value, bytes):
|
|
995
|
+
return value.decode("utf-8", errors="replace")
|
|
996
|
+
except Exception:
|
|
997
|
+
pass
|
|
998
|
+
return token[2:-1].replace("\\'", "'").replace('\\"', '"').replace("\\\\", "\\").replace("\\n", "\n")
|
|
999
|
+
|
|
1000
|
+
|
|
1001
|
+
def _clean_error_text(value):
|
|
1002
|
+
"""Strip Python bytes reprs and collapse whitespace in an error message."""
|
|
1003
|
+
s = str(value)
|
|
1004
|
+
s = re.sub(r"b(['\"])(?:\\.|(?!\1).)*\1", lambda m: _decode_bytes_literal(m.group(0)), s)
|
|
1005
|
+
return re.sub(r"\s+", " ", s).strip()
|
|
1006
|
+
|
|
1007
|
+
|
|
1008
|
+
def error_info(exc):
|
|
1009
|
+
"""Classify a bridge exception into (code, readable message).
|
|
1010
|
+
|
|
1011
|
+
The code lets the UI show an actionable, localized explanation instead of
|
|
1012
|
+
dumping a raw IMAP/SMTP protocol error at the user.
|
|
1013
|
+
"""
|
|
1014
|
+
text = _clean_error_text(exc)
|
|
1015
|
+
low = text.lower()
|
|
1016
|
+
if isinstance(exc, (socket.timeout, TimeoutError)) or "timed out" in low or "timeout" in low:
|
|
1017
|
+
return "timeout", text
|
|
1018
|
+
if isinstance(exc, ssl.SSLError) or "ssl" in low or "certificate" in low or "wrong version number" in low:
|
|
1019
|
+
return "tls", text
|
|
1020
|
+
if isinstance(exc, smtplib.SMTPAuthenticationError) or \
|
|
1021
|
+
(isinstance(exc, smtplib.SMTPResponseException) and getattr(exc, "smtp_code", None) == 535) or \
|
|
1022
|
+
"authenticationfailed" in low or "authentication failed" in low or \
|
|
1023
|
+
"login fail" in low or "invalid credentials" in low:
|
|
1024
|
+
return "auth_failed", text
|
|
1025
|
+
if "login frequency limited" in low or "too many" in low or "频繁" in text:
|
|
1026
|
+
return "rate_limited", text
|
|
1027
|
+
if "service is not open" in low or "service not open" in low or "服务未开启" in text:
|
|
1028
|
+
return "service_disabled", text
|
|
1029
|
+
if isinstance(exc, (socket.gaierror, ConnectionRefusedError, ConnectionResetError, OSError)) or \
|
|
1030
|
+
"connection refused" in low or "name or service not known" in low or "network is unreachable" in low:
|
|
1031
|
+
return "network", text
|
|
1032
|
+
return "generic", text
|
|
1033
|
+
|
|
1034
|
+
|
|
1035
|
+
def imap_data_text(data):
|
|
1036
|
+
"""Readable text from an imaplib command result tuple."""
|
|
1037
|
+
if isinstance(data, (list, tuple)) and data:
|
|
1038
|
+
return _clean_error_text(data[-1])
|
|
1039
|
+
return _clean_error_text(data)
|
|
1040
|
+
|
|
1041
|
+
|
|
1042
|
+
def fail_result(exc):
|
|
1043
|
+
"""Build a structured, UI-friendly failure result from an exception."""
|
|
1044
|
+
code, message = error_info(exc)
|
|
1045
|
+
return {"ok": False, "error": message, "code": code}
|
|
1046
|
+
|
|
1047
|
+
|
|
1048
|
+
|
|
1049
|
+
def op_list_sent(req):
|
|
1050
|
+
"""Read all Sent folders from the mail server (true cross-device sync)."""
|
|
1051
|
+
acc = req["account"]
|
|
1052
|
+
limit = max(1, min(int(req.get("limit") or 50), 100))
|
|
1053
|
+
try:
|
|
1054
|
+
client = imap_connect(acc)
|
|
1055
|
+
except Exception as exc:
|
|
1056
|
+
return fail_result(exc)
|
|
1057
|
+
try:
|
|
1058
|
+
folders = _sent_folders(client)
|
|
1059
|
+
if not folders:
|
|
1060
|
+
return {"ok": False, "error": "未找到邮箱的已发送文件夹", "code": "folder"}
|
|
1061
|
+
merged = []
|
|
1062
|
+
seen = set()
|
|
1063
|
+
total = 0
|
|
1064
|
+
for folder in folders:
|
|
1065
|
+
part = _list_messages_in(client, folder, limit)
|
|
1066
|
+
if not part.get("ok"):
|
|
1067
|
+
continue
|
|
1068
|
+
total += int(part.get("total") or 0)
|
|
1069
|
+
for m in part.get("messages") or []:
|
|
1070
|
+
key = (str(m.get("subject") or ""), str(m.get("to") or ""),
|
|
1071
|
+
str(m.get("date") or ""), str(m.get("snippet") or "")[:80])
|
|
1072
|
+
if key in seen:
|
|
1073
|
+
continue
|
|
1074
|
+
seen.add(key)
|
|
1075
|
+
item = dict(m)
|
|
1076
|
+
item["folder"] = folder
|
|
1077
|
+
item["uid"] = str(m.get("uid") or "")
|
|
1078
|
+
item["id"] = folder + ":" + item["uid"]
|
|
1079
|
+
merged.append(item)
|
|
1080
|
+
merged.sort(key=lambda m: str(m.get("date") or ""), reverse=True)
|
|
1081
|
+
return {"ok": True, "messages": merged[:limit], "total": total or len(merged)}
|
|
1082
|
+
except Exception as exc:
|
|
1083
|
+
return fail_result(exc)
|
|
1084
|
+
finally:
|
|
1085
|
+
_imap_close(client)
|
|
1086
|
+
|
|
1087
|
+
|
|
1088
|
+
def _ensure_folder(client, name):
|
|
1089
|
+
"""Select a folder read-write, creating it if the server allows."""
|
|
1090
|
+
try:
|
|
1091
|
+
typ, _ = client.select('"%s"' % name)
|
|
1092
|
+
if typ == "OK":
|
|
1093
|
+
return True
|
|
1094
|
+
except Exception:
|
|
1095
|
+
pass
|
|
1096
|
+
try:
|
|
1097
|
+
client.create('"%s"' % name)
|
|
1098
|
+
typ, _ = client.select('"%s"' % name)
|
|
1099
|
+
return typ == "OK"
|
|
1100
|
+
except Exception:
|
|
1101
|
+
return False
|
|
1102
|
+
|
|
1103
|
+
|
|
1104
|
+
def op_get_contacts(req):
|
|
1105
|
+
"""Load the synced contact list from the mail server."""
|
|
1106
|
+
acc = req["account"]
|
|
1107
|
+
try:
|
|
1108
|
+
client = imap_connect(acc)
|
|
1109
|
+
except Exception as exc:
|
|
1110
|
+
return fail_result(exc)
|
|
1111
|
+
try:
|
|
1112
|
+
if not _ensure_folder(client, _CONTACTS_FOLDER):
|
|
1113
|
+
return {"ok": False, "error": "无法访问服务器上的联系人文件夹", "code": "folder"}
|
|
1114
|
+
typ, data = client.uid("SEARCH", None, 'HEADER Subject "%s"' % _CONTACTS_SUBJECT)
|
|
1115
|
+
if typ != "OK" or not data or not data[0]:
|
|
1116
|
+
return {"ok": True, "contacts": []}
|
|
1117
|
+
# SEARCH order is not guaranteed; some providers return UIDs in
|
|
1118
|
+
# descending order. Try every sync message from newest to oldest and
|
|
1119
|
+
# use the first one that parses, so stale copies can never win.
|
|
1120
|
+
uids = list(data[0].split())
|
|
1121
|
+
try:
|
|
1122
|
+
uids.sort(key=lambda x: int(x), reverse=True)
|
|
1123
|
+
except Exception:
|
|
1124
|
+
pass
|
|
1125
|
+
from email import message_from_bytes
|
|
1126
|
+
for uid in uids:
|
|
1127
|
+
typ, md = client.uid("FETCH", uid, "(RFC822)")
|
|
1128
|
+
if typ != "OK" or not md or md[0] is None:
|
|
1129
|
+
continue
|
|
1130
|
+
try:
|
|
1131
|
+
msg = message_from_bytes(md[0][1])
|
|
1132
|
+
raw = msg.get_payload(decode=True) or b""
|
|
1133
|
+
parsed = json.loads(raw.decode("utf-8", errors="replace"))
|
|
1134
|
+
contacts = parsed.get("contacts") if isinstance(parsed, dict) else None
|
|
1135
|
+
if isinstance(contacts, list):
|
|
1136
|
+
return {"ok": True, "contacts": contacts}
|
|
1137
|
+
except Exception:
|
|
1138
|
+
continue
|
|
1139
|
+
return {"ok": True, "contacts": []}
|
|
1140
|
+
except Exception as exc:
|
|
1141
|
+
return fail_result(exc)
|
|
1142
|
+
finally:
|
|
1143
|
+
_imap_close(client)
|
|
1144
|
+
|
|
1145
|
+
|
|
1146
|
+
def op_set_contacts(req):
|
|
1147
|
+
"""Replace the synced contact list on the mail server."""
|
|
1148
|
+
acc = req["account"]
|
|
1149
|
+
contacts = req.get("contacts") or []
|
|
1150
|
+
if not isinstance(contacts, list):
|
|
1151
|
+
return {"ok": False, "error": "contacts must be a list", "code": "generic"}
|
|
1152
|
+
try:
|
|
1153
|
+
client = imap_connect(acc)
|
|
1154
|
+
except Exception as exc:
|
|
1155
|
+
return fail_result(exc)
|
|
1156
|
+
try:
|
|
1157
|
+
if not _ensure_folder(client, _CONTACTS_FOLDER):
|
|
1158
|
+
return {"ok": False, "error": "无法访问服务器上的联系人文件夹", "code": "folder"}
|
|
1159
|
+
try:
|
|
1160
|
+
typ, data = client.uid("SEARCH", None, 'HEADER Subject "%s"' % _CONTACTS_SUBJECT)
|
|
1161
|
+
if typ == "OK" and data and data[0]:
|
|
1162
|
+
uids = data[0].split()
|
|
1163
|
+
client.uid("STORE", b",".join(uids), "+FLAGS", "(\\Deleted)")
|
|
1164
|
+
client.expunge()
|
|
1165
|
+
except Exception:
|
|
1166
|
+
pass
|
|
1167
|
+
msg = MIMEText(json.dumps({"contacts": contacts}, ensure_ascii=False), "plain", "utf-8")
|
|
1168
|
+
msg["Subject"] = _CONTACTS_SUBJECT
|
|
1169
|
+
msg["From"] = acc["username"]
|
|
1170
|
+
msg["To"] = acc["username"]
|
|
1171
|
+
msg["Date"] = formatdate(localtime=True)
|
|
1172
|
+
typ, _ = client.append('"%s"' % _CONTACTS_FOLDER, None, None, msg.as_bytes())
|
|
1173
|
+
if typ != "OK":
|
|
1174
|
+
return {"ok": False, "error": "写入服务器联系人失败", "code": "generic"}
|
|
1175
|
+
return {"ok": True, "contacts": contacts}
|
|
1176
|
+
except Exception as exc:
|
|
1177
|
+
return fail_result(exc)
|
|
1178
|
+
finally:
|
|
1179
|
+
_imap_close(client)
|
|
1180
|
+
|
|
1181
|
+
|
|
1182
|
+
def op_collect_and_sync_contacts(req):
|
|
1183
|
+
"""Scan addresses and persist the merged list in one IMAP session."""
|
|
1184
|
+
acc = req["account"]
|
|
1185
|
+
limit = max(1, min(int(req.get("limit") or 40), 60))
|
|
1186
|
+
client = None
|
|
1187
|
+
try:
|
|
1188
|
+
scan = op_collect_contacts({"account": acc, "limit": limit})
|
|
1189
|
+
found = (scan.get("contacts") or []) if scan.get("ok") else []
|
|
1190
|
+
current = op_get_contacts({"account": acc})
|
|
1191
|
+
contacts = list(current.get("contacts") or []) if current.get("ok") else []
|
|
1192
|
+
for c in found:
|
|
1193
|
+
email = str(c.get("email") or "").strip().lower()
|
|
1194
|
+
if not email:
|
|
1195
|
+
continue
|
|
1196
|
+
if any(str(x.get("email") or "").lower() == email for x in contacts):
|
|
1197
|
+
continue
|
|
1198
|
+
contacts.append({"email": email, "name": str(c.get("name") or "")})
|
|
1199
|
+
contacts.sort(key=lambda x: str(x.get("name") or x.get("email") or "").lower())
|
|
1200
|
+
client = imap_connect(acc)
|
|
1201
|
+
if not _ensure_folder(client, _CONTACTS_FOLDER):
|
|
1202
|
+
return {"ok": False, "error": "无法访问服务器上的联系人文件夹", "code": "folder"}
|
|
1203
|
+
try:
|
|
1204
|
+
typ, data = client.uid("SEARCH", None, 'HEADER Subject "%s"' % _CONTACTS_SUBJECT)
|
|
1205
|
+
if typ == "OK" and data and data[0]:
|
|
1206
|
+
client.uid("STORE", b",".join(data[0].split()), "+FLAGS", "(\\Deleted)")
|
|
1207
|
+
client.expunge()
|
|
1208
|
+
except Exception:
|
|
1209
|
+
pass
|
|
1210
|
+
msg = MIMEText(json.dumps({"contacts": contacts}, ensure_ascii=False), "plain", "utf-8")
|
|
1211
|
+
msg["Subject"] = _CONTACTS_SUBJECT
|
|
1212
|
+
msg["From"] = acc["username"]
|
|
1213
|
+
msg["To"] = acc["username"]
|
|
1214
|
+
msg["Date"] = formatdate(localtime=True)
|
|
1215
|
+
typ, _ = client.append('"%s"' % _CONTACTS_FOLDER, None, None, msg.as_bytes())
|
|
1216
|
+
if typ != "OK":
|
|
1217
|
+
return {"ok": False, "error": "写入服务器联系人失败", "code": "generic"}
|
|
1218
|
+
return {"ok": True, "contacts": contacts}
|
|
1219
|
+
except Exception as exc:
|
|
1220
|
+
return fail_result(exc)
|
|
1221
|
+
finally:
|
|
1222
|
+
if client is not None:
|
|
1223
|
+
_imap_close(client)
|
|
1224
|
+
|
|
1225
|
+
|
|
1226
|
+
OPS = {
|
|
1227
|
+
"test": op_test,
|
|
1228
|
+
"listMessages": op_list_messages,
|
|
1229
|
+
"getMessage": op_get_message,
|
|
1230
|
+
"sendMessage": op_send_message,
|
|
1231
|
+
"getAttachment": op_get_attachment,
|
|
1232
|
+
"listSent": op_list_sent,
|
|
1233
|
+
"getContacts": op_get_contacts,
|
|
1234
|
+
"setContacts": op_set_contacts,
|
|
1235
|
+
"collectAndSyncContacts": op_collect_and_sync_contacts,
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
|
|
1239
|
+
def main():
|
|
1240
|
+
try:
|
|
1241
|
+
req = json.loads(os.environ.get("MAIL_REQUEST", "{}"))
|
|
1242
|
+
op = req.get("op")
|
|
1243
|
+
fn = OPS.get(op)
|
|
1244
|
+
if fn is None:
|
|
1245
|
+
print(json.dumps({"ok": False, "error": "unknown op: %s" % op, "code": "generic"}))
|
|
1246
|
+
return
|
|
1247
|
+
result = fn(req)
|
|
1248
|
+
# ensure_ascii=True (default): emit pure ASCII (\uXXXX escapes) so the
|
|
1249
|
+
# output never hits a UnicodeEncodeError on a GBK/cp936 console. The
|
|
1250
|
+
# JS side JSON.parse() restores the original characters correctly.
|
|
1251
|
+
print(json.dumps(result))
|
|
1252
|
+
except Exception as exc:
|
|
1253
|
+
print(json.dumps(fail_result(exc)))
|
|
1254
|
+
|
|
1255
|
+
|
|
1256
|
+
if __name__ == "__main__":
|
|
1257
|
+
main()
|