@mysterycode-liwen/dsh-mail 0.0.0-stage → 1.0.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 ADDED
@@ -0,0 +1,1019 @@
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()