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