email_authorizations_service.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  1. import threading
  2. import socket
  3. import socks
  4. import imaplib
  5. import smtplib
  6. import email
  7. import asyncio
  8. import re
  9. import time
  10. from datetime import datetime, timedelta, timezone
  11. from email.message import EmailMessage
  12. from email.header import decode_header
  13. from typing import List, Optional
  14. from sqlalchemy.orm import Session
  15. from sqlalchemy.ext.asyncio import AsyncSession
  16. from sqlalchemy import select, text
  17. from starlette.concurrency import run_in_threadpool
  18. from app.core.logger import logger
  19. from app.core.biz_exception import NotFoundError, BizLogicError
  20. from app.models.email_authorizations import EmailAuthorization
  21. from app.schemas.email_authorizations import EmailAuthorizationCreate, EmailAuthorizationUpdate
  22. # 保持锁逻辑不变
  23. _PROXY_LOCK = threading.Lock()
  24. class EmailAuthorizationService:
  25. DEFAULT_READ_TOP_N_EMAIL = 10
  26. RETRY_DELAY_SECONDS = 5
  27. # =================================================================
  28. # 数据库操作 (DB CRUD) - 使用 AsyncSession
  29. # =================================================================
  30. @staticmethod
  31. async def get_all(db: AsyncSession) -> List[EmailAuthorization]:
  32. # AsyncSession 不支持 db.query,需要用 select(Model)
  33. stmt = select(EmailAuthorization).order_by(EmailAuthorization.id.desc())
  34. result = await db.execute(stmt)
  35. return result.scalars().all()
  36. @staticmethod
  37. async def get_by_id(db: AsyncSession, id: int) -> Optional[EmailAuthorization]:
  38. stmt = select(EmailAuthorization).where(EmailAuthorization.id == id)
  39. result = await db.execute(stmt)
  40. # scalar_one_or_none 类似于 .first(),但更严格(如果有多个会报错,这里id是主键所以没问题)
  41. obj = result.scalar_one_or_none()
  42. if not obj:
  43. raise NotFoundError("Email authorization not found")
  44. return obj
  45. @staticmethod
  46. async def get_by_email(db: AsyncSession, email: str) -> Optional[EmailAuthorization]:
  47. stmt = select(EmailAuthorization).where(EmailAuthorization.email == email)
  48. result = await db.execute(stmt)
  49. obj = result.scalar_one_or_none()
  50. if not obj:
  51. raise NotFoundError("Email authorization not found")
  52. return obj
  53. @staticmethod
  54. async def create(db: AsyncSession, obj_in: EmailAuthorizationCreate) -> EmailAuthorization:
  55. # 先检查是否存在
  56. stmt = select(EmailAuthorization).where(EmailAuthorization.email == obj_in.email)
  57. result = await db.execute(stmt)
  58. if result.scalar_one_or_none():
  59. raise BizLogicError(f"Email {obj_in.email} already exist")
  60. # 创建对象
  61. db_obj = EmailAuthorization(**obj_in.dict(exclude_unset=True))
  62. # db.add 是同步方法(只是添加到 session 上下文)
  63. db.add(db_obj)
  64. # commit 和 refresh 是异步的
  65. await db.commit()
  66. await db.refresh(db_obj)
  67. return db_obj
  68. @staticmethod
  69. async def update(db: AsyncSession, id: int, obj_in: EmailAuthorizationUpdate) -> Optional[EmailAuthorization]:
  70. stmt = select(EmailAuthorization).where(EmailAuthorization.id == id)
  71. result = await db.execute(stmt)
  72. db_obj = result.scalar_one_or_none()
  73. if not db_obj:
  74. raise NotFoundError("Email authorization not found")
  75. for field, value in obj_in.dict(exclude_unset=True).items():
  76. setattr(db_obj, field, value)
  77. db.add(db_obj)
  78. await db.commit()
  79. await db.refresh(db_obj)
  80. return db_obj
  81. @staticmethod
  82. async def delete(db: AsyncSession, id: int) -> Optional[EmailAuthorization]:
  83. stmt = select(EmailAuthorization).where(EmailAuthorization.id == id)
  84. result = await db.execute(stmt)
  85. db_obj = result.scalar_one_or_none()
  86. if not db_obj:
  87. raise NotFoundError("Email authorization not found")
  88. # delete 也是同步标记
  89. await db.delete(db_obj)
  90. await db.commit()
  91. return db_obj
  92. @staticmethod
  93. def _connect_imap_with_proxy(
  94. host: str,
  95. port: int,
  96. proxy_host: Optional[str] = None,
  97. proxy_port: Optional[int] = None,
  98. proxy_user: Optional[str] = None,
  99. proxy_password: Optional[str] = None,
  100. ) -> imaplib.IMAP4_SSL:
  101. """
  102. 创建连接 (同步方法,将在线程中运行)
  103. 使用 Lock 确保 socket patching 不会影响其他并发请求
  104. """
  105. if proxy_host and proxy_port and proxy_port > 0:
  106. with _PROXY_LOCK: # 加锁,防止多线程同时修改全局 socket
  107. original_socket = socket.socket
  108. socks.setdefaultproxy(
  109. proxy_type=socks.SOCKS5,
  110. addr=proxy_host,
  111. port=proxy_port,
  112. username=proxy_user or None,
  113. password=proxy_password or None,
  114. )
  115. socket.socket = socks.socksocket
  116. try:
  117. imap = imaplib.IMAP4_SSL(host, port)
  118. finally:
  119. socket.socket = original_socket
  120. else:
  121. imap = imaplib.IMAP4_SSL(host, port)
  122. return imap
  123. @staticmethod
  124. def _connect_smtp_with_proxy(
  125. host: str,
  126. port: int,
  127. proxy_host: Optional[str] = None,
  128. proxy_port: Optional[int] = None,
  129. proxy_user: Optional[str] = None,
  130. proxy_password: Optional[str] = None,
  131. ) -> smtplib.SMTP_SSL:
  132. """
  133. 创建连接 (同步方法,将在线程中运行)
  134. """
  135. if proxy_host and proxy_port and proxy_port > 0:
  136. with _PROXY_LOCK: # 加锁
  137. original_socket = socket.socket
  138. socks.setdefaultproxy(
  139. proxy_type=socks.SOCKS5,
  140. addr=proxy_host,
  141. port=proxy_port,
  142. username=proxy_user or None,
  143. password=proxy_password or None,
  144. )
  145. socket.socket = socks.socksocket
  146. try:
  147. smtp = smtplib.SMTP_SSL(host, port)
  148. finally:
  149. socket.socket = original_socket
  150. else:
  151. smtp = smtplib.SMTP_SSL(host, port)
  152. return smtp
  153. @staticmethod
  154. async def fetch_email_authorizations(
  155. auth,
  156. sender: str,
  157. recipient: str,
  158. subject_keywords: str,
  159. body_keywords: str,
  160. sent_date: str,
  161. expiry: int = 300,
  162. only_text: bool = True
  163. ) -> Optional[str]:
  164. """
  165. 在有效期内循环读取邮箱,找到符合条件的邮件(使用最后一条 Received 头作为收件时间)
  166. """
  167. def _worker():
  168. EMAIL_ACCOUNT = auth.email
  169. EMAIL_PASSWORD = auth.authorization_code
  170. IMAP_SERVER = auth.imap_server
  171. IMAP_PORT = auth.imap_port
  172. subject_keys = [s.strip() for s in subject_keywords.split(",") if s.strip()]
  173. body_keys = [s.strip() for s in body_keywords.split(",") if s.strip()]
  174. # === 时间计算 ===
  175. sent_dt = datetime.strptime(sent_date, "%Y-%m-%d %H:%M:%S").replace(tzinfo=timezone.utc)
  176. max_wait_time = min(5 * 60, expiry) # 最长等待5分钟
  177. expiry_at = time.time() + max_wait_time
  178. def get_received_time(msg):
  179. """
  180. 使用最后一条 Received 头解析收件时间
  181. """
  182. received_headers = msg.get_all("Received", [])
  183. if not received_headers:
  184. return None
  185. for i, header in enumerate(received_headers, 1):
  186. logger.debug(f" [{i}] {header}")
  187. last_received = received_headers[-1]
  188. if ";" not in last_received:
  189. return None
  190. time_str = last_received.split(";")[-1].strip()
  191. dt_tuple = email.utils.parsedate_tz(time_str)
  192. if not dt_tuple:
  193. return None
  194. return datetime.fromtimestamp(email.utils.mktime_tz(dt_tuple), tz=timezone.utc)
  195. mail = EmailAuthorizationService._connect_imap_with_proxy(
  196. IMAP_SERVER,
  197. IMAP_PORT,
  198. auth.proxy_host,
  199. auth.proxy_port,
  200. auth.proxy_username,
  201. auth.proxy_password,
  202. )
  203. mail.login(EMAIL_ACCOUNT, EMAIL_PASSWORD)
  204. mail.select("INBOX")
  205. while time.time() < expiry_at:
  206. mail.noop() # 刷新邮箱状态
  207. _, data = mail.search(None, "ALL")
  208. mail_ids = data[0].split()
  209. if not mail_ids:
  210. time.sleep(EmailAuthorizationService.RETRY_DELAY_SECONDS)
  211. continue
  212. recent_ids = mail_ids[-EmailAuthorizationService.DEFAULT_READ_TOP_N_EMAIL:]
  213. messages = []
  214. debug = True
  215. for email_id in reversed(recent_ids):
  216. res, msg_data = mail.fetch(email_id, "(RFC822)")
  217. if res != "OK" or not msg_data:
  218. if debug:
  219. logger.debug(f"[WARN] 邮件 ID={email_id.decode()} 获取失败")
  220. continue
  221. msg_bytes = None
  222. for part in msg_data:
  223. if isinstance(part, tuple):
  224. msg_bytes = part[1]
  225. if not msg_bytes:
  226. if debug:
  227. logger.debug(f"[WARN] 邮件 ID={email_id.decode()} 无正文")
  228. continue
  229. msg = email.message_from_bytes(msg_bytes)
  230. received_dt = get_received_time(msg)
  231. if not received_dt:
  232. if debug:
  233. logger.debug(f"[WARN] 邮件 ID={email_id.decode()} 未解析出 Received 时间")
  234. continue
  235. messages.append((msg, received_dt))
  236. if debug:
  237. logger.debug(f"[DEBUG] 成功解析邮件数: {len(messages)}")
  238. logger.debug(f"[DEBUG] 收件时间列表: {[m[1] for m in messages]}")
  239. # 按收件时间降序排序
  240. messages.sort(key=lambda x: x[1], reverse=True)
  241. for msg, received_dt in messages:
  242. # 判断是否在发送时间后的有效窗口内
  243. if received_dt < sent_dt:
  244. if debug:
  245. logger.debug(f"[INFO] 邮件太旧: {received_dt}")
  246. continue
  247. if received_dt > sent_dt + timedelta(seconds=expiry):
  248. if debug:
  249. logger.debug(f"[INFO] 邮件太新: {received_dt}")
  250. continue
  251. # 匹配发件人/收件人
  252. msg_from = msg.get("From", "")
  253. msg_to = msg.get("To", "")
  254. if sender.lower() not in msg_from.lower():
  255. if debug:
  256. logger.debug("发件人不匹配")
  257. continue
  258. if recipient.lower() not in msg_to.lower():
  259. if debug:
  260. logger.debug("收件人不匹配")
  261. continue
  262. # 匹配主题
  263. subject, enc = decode_header(msg.get("Subject"))[0]
  264. if isinstance(subject, bytes):
  265. subject = subject.decode(enc or "utf-8", errors="ignore")
  266. if subject_keys and not any(k.lower() in subject.lower() for k in subject_keys):
  267. continue
  268. # 提取正文
  269. body = EmailAuthorizationService._extract_body(msg, only_text)
  270. if body_keys and not any(k.lower() in body.lower() for k in body_keys):
  271. continue
  272. # 找到匹配邮件 → 返回内容
  273. mail.close()
  274. mail.logout()
  275. return body.strip()
  276. # 未匹配到 → 等待重试
  277. time.sleep(EmailAuthorizationService.RETRY_DELAY_SECONDS)
  278. mail.close()
  279. mail.logout()
  280. raise NotFoundError("Get email timeout")
  281. return await run_in_threadpool(_worker)
  282. @staticmethod
  283. def _process_recent_emails_sync(
  284. mail, recent_ids, sent_dt, expiry, sender, recipient, subject_keys, body_keys, only_text
  285. ) -> Optional[str]:
  286. """
  287. 同步辅助函数:处理邮件解析逻辑。
  288. 将这段繁琐的逻辑放入线程运行,避免阻塞 Async Loop。
  289. """
  290. messages = []
  291. debug = True
  292. for email_id in reversed(recent_ids):
  293. res, msg_data = mail.fetch(email_id, "(RFC822)")
  294. if res != "OK" or not msg_data:
  295. continue
  296. msg_bytes = None
  297. for part in msg_data:
  298. if isinstance(part, tuple):
  299. msg_bytes = part[1]
  300. if not msg_bytes:
  301. continue
  302. msg = email.message_from_bytes(msg_bytes)
  303. # 解析时间
  304. received_dt = None
  305. received_headers = msg.get_all("Received", [])
  306. if received_headers:
  307. last_received = received_headers[-1]
  308. if ";" in last_received:
  309. time_str = last_received.split(";")[-1].strip()
  310. dt_tuple = email.utils.parsedate_tz(time_str)
  311. if dt_tuple:
  312. received_dt = datetime.fromtimestamp(email.utils.mktime_tz(dt_tuple), tz=timezone.utc)
  313. if not received_dt:
  314. continue
  315. messages.append((msg, received_dt))
  316. # 排序
  317. messages.sort(key=lambda x: x[1], reverse=True)
  318. for msg, received_dt in messages:
  319. # 时间判定
  320. if received_dt < sent_dt:
  321. continue
  322. if received_dt > sent_dt + timedelta(seconds=expiry):
  323. continue
  324. # 匹配逻辑
  325. msg_from = msg.get("From", "")
  326. msg_to = msg.get("To", "")
  327. if sender.lower() not in msg_from.lower():
  328. continue
  329. if recipient.lower() not in msg_to.lower():
  330. continue
  331. subject_raw = msg.get("Subject")
  332. subject = ""
  333. if subject_raw:
  334. decoded_list = decode_header(subject_raw)
  335. if decoded_list:
  336. sub_bytes, enc = decoded_list[0]
  337. if isinstance(sub_bytes, bytes):
  338. subject = sub_bytes.decode(enc or "utf-8", errors="ignore")
  339. else:
  340. subject = str(sub_bytes)
  341. if subject_keys and not any(k.lower() in subject.lower() for k in subject_keys):
  342. continue
  343. body = EmailAuthorizationService._extract_body(msg, only_text)
  344. if body_keys and not any(k.lower() in body.lower() for k in body_keys):
  345. continue
  346. return body.strip()
  347. return None
  348. @staticmethod
  349. async def fetch_email_authorizations_from_top_n(
  350. auth,
  351. sender: str,
  352. recipient: str,
  353. subject_keywords: str,
  354. body_keywords: str,
  355. top: int = 10,
  356. only_text: bool = True
  357. ) -> Optional[str]:
  358. # 定义一个纯同步的 worker 函数来执行所有 IMAP 逻辑
  359. def _worker():
  360. subject_keys = [s.strip() for s in subject_keywords.split(",") if s.strip()]
  361. body_keys = [s.strip() for s in body_keywords.split(",") if s.strip()]
  362. mail = EmailAuthorizationService._connect_imap_with_proxy(
  363. auth.imap_server,
  364. auth.imap_port,
  365. auth.proxy_host,
  366. auth.proxy_port,
  367. auth.proxy_username,
  368. auth.proxy_password,
  369. )
  370. try:
  371. mail.login(auth.email, auth.authorization_code)
  372. mail.select("INBOX")
  373. _, data = mail.search(None, "ALL")
  374. mail_ids = data[0].split()
  375. if not mail_ids:
  376. return None
  377. recent_ids = mail_ids[-top:]
  378. # 复用上面的解析逻辑,但稍作调整,因为这个方法不需要时间过滤
  379. # 这里为了简单,直接写精简版解析
  380. for email_id in reversed(recent_ids):
  381. res, msg_data = mail.fetch(email_id, "(RFC822)")
  382. if res != "OK" or not msg_data: continue
  383. msg_bytes = None
  384. for part in msg_data:
  385. if isinstance(part, tuple): msg_bytes = part[1]
  386. if not msg_bytes: continue
  387. msg = email.message_from_bytes(msg_bytes)
  388. # 匹配逻辑
  389. msg_from = msg.get("From", "")
  390. msg_to = msg.get("To", "")
  391. if sender.lower() not in msg_from.lower(): continue
  392. if recipient.lower() not in msg_to.lower(): continue
  393. subject_raw = msg.get("Subject")
  394. subject = ""
  395. if subject_raw:
  396. d = decode_header(subject_raw)[0]
  397. subject = d[0].decode(d[1] or "utf-8", errors="ignore") if isinstance(d[0], bytes) else str(d[0])
  398. if subject_keys and not any(k.lower() in subject.lower() for k in subject_keys): continue
  399. body = EmailAuthorizationService._extract_body(msg, only_text)
  400. if body_keys and not any(k.lower() in body.lower() for k in body_keys): continue
  401. return body.strip()
  402. return None
  403. finally:
  404. try:
  405. mail.close()
  406. mail.logout()
  407. except:
  408. pass
  409. return await run_in_threadpool(_worker)
  410. @staticmethod
  411. async def forward_first_matching_email(
  412. auth,
  413. forward_to: str,
  414. sender: str,
  415. recipient: str,
  416. subject_keywords: str,
  417. body_keywords: str
  418. ):
  419. # 整个逻辑比较复杂且都是 IO,直接打包扔进线程池
  420. def _worker():
  421. subject_keys = [s.strip() for s in subject_keywords.split(",") if s.strip()]
  422. body_keys = [s.strip() for s in body_keywords.split(",") if s.strip()]
  423. mail = EmailAuthorizationService._connect_imap_with_proxy(
  424. auth.imap_server, auth.imap_port, auth.proxy_host, auth.proxy_port, auth.proxy_username, auth.proxy_password
  425. )
  426. try:
  427. mail.login(auth.email, auth.authorization_code)
  428. mail.select("INBOX")
  429. target = recipient
  430. # 注意:IMAP search 语法对引号很敏感,确保 target 没有特殊字符破坏命令
  431. query = f'(HEADER To "{target}")'
  432. res, data = mail.uid("search", None, query)
  433. if res != "OK": return None
  434. uids = data[0].split()
  435. msgs = []
  436. for uid in uids:
  437. res, msg_data = mail.uid("fetch", uid, "(RFC822)")
  438. if res != "OK": continue
  439. msg = email.message_from_bytes(msg_data[0][1])
  440. # 处理 Date 头可能缺失的情况
  441. date_str = msg.get("Date")
  442. if date_str:
  443. date_ = email.utils.parsedate_to_datetime(date_str)
  444. msgs.append((date_, msg))
  445. msgs.sort(key=lambda x: x[0], reverse=True)
  446. for _, msg in msgs:
  447. msg_from = msg.get("From", "")
  448. if sender.lower() not in msg_from.lower(): continue
  449. subject_raw = msg.get("Subject", "")
  450. subject = ""
  451. d = decode_header(subject_raw)[0]
  452. subject = d[0].decode(d[1] or "utf-8", errors="ignore") if isinstance(d[0], bytes) else str(d[0])
  453. if subject_keys and not any(k.lower() in subject.lower() for k in subject_keys): continue
  454. body = EmailAuthorizationService._extract_body(msg, True)
  455. if body_keys and not any(k.lower() in body.lower() for k in body_keys): continue
  456. # 准备转发
  457. # 注意:直接修改 Header 转发可能会破坏 DKIM 签名,更好的方式是作为附件转发
  458. # 但这里保持原逻辑
  459. del msg['From']
  460. del msg['To']
  461. del msg['Subject']
  462. msg['From'] = auth.email
  463. msg['To'] = forward_to
  464. msg['Subject'] = f"FWD: {subject}"
  465. # 调用同步的 send 方法
  466. EmailAuthorizationService.send_email_smtp(auth, msg)
  467. return f"邮件 '{subject}' 已成功转发至: {forward_to}"
  468. return None
  469. finally:
  470. try:
  471. mail.logout()
  472. except: pass
  473. return await run_in_threadpool(_worker)
  474. @staticmethod
  475. async def forward_first_matching_email2(
  476. db: Session,
  477. auth,
  478. forward_to: str,
  479. sender: str,
  480. recipient: str,
  481. subject_keywords: str,
  482. body_keywords: str
  483. ):
  484. # =========================================================
  485. # 第一步:在数据库中查找最新的 UID (主线程/DB线程执行)
  486. # =========================================================
  487. # 1. 构建动态 SQL
  488. # 假设表名为 emails,字段为 uid, sender, recipient, subject, body_text
  489. sql = "SELECT uid, subject FROM emails WHERE 1=1"
  490. params = {}
  491. # 2. 处理发件人 (模糊匹配)
  492. if sender.strip():
  493. sql += " AND sender LIKE :sender"
  494. params['sender'] = f"%{sender.strip()}%"
  495. # 3. 处理收件人 (模糊匹配)
  496. if recipient.strip():
  497. sql += " AND recipient LIKE :recipient"
  498. params['recipient'] = f"%{recipient.strip()}%"
  499. # 4. 处理主题关键词 (OR 关系)
  500. subj_keys = [k.strip() for k in subject_keywords.split(',') if k.strip()]
  501. if subj_keys:
  502. for i, k in enumerate(subj_keys):
  503. key_name = f"subj_{i}"
  504. # 直接拼接到主 SQL 中,要求同时满足
  505. sql += f" AND subject LIKE :{key_name}"
  506. params[key_name] = f"%{k}%"
  507. # 5. 处理内容关键词 (OR 关系)
  508. body_keys = [k.strip() for k in body_keywords.split(',') if k.strip()]
  509. if body_keys:
  510. for i, k in enumerate(body_keys):
  511. key_name = f"body_{i}"
  512. # 直接拼接到主 SQL 中,要求同时满足
  513. sql += f" AND body_text LIKE :{key_name}"
  514. params[key_name] = f"%{k}%"
  515. # 6. 获取最新的一条
  516. sql += " ORDER BY uid DESC LIMIT 1"
  517. try:
  518. # 执行查询
  519. result_proxy = await db.execute(text(sql), params)
  520. result = result_proxy.fetchone()
  521. if not result:
  522. logger.info(f"DB Search: No email found for {sender} -> {recipient}")
  523. return None
  524. target_uid = result.uid
  525. target_subject = result.subject
  526. logger.info(f"DB Search: Found UID {target_uid} matching criteria. Subject: {target_subject}")
  527. except Exception as e:
  528. logger.error(f"DB Search Error: {e}")
  529. return f"数据库查询失败: {str(e)}"
  530. # =========================================================
  531. # 第二步:去 IMAP 拉取原始内容并转发 (放入线程池执行 IO 操作)
  532. # =========================================================
  533. def _worker():
  534. mail = None
  535. try:
  536. # 1. 连接 IMAP
  537. mail = EmailAuthorizationService._connect_imap_with_proxy(
  538. auth.imap_server, auth.imap_port,
  539. auth.proxy_host, auth.proxy_port,
  540. auth.proxy_username, auth.proxy_password
  541. )
  542. mail.login(auth.email, auth.authorization_code)
  543. mail.select("INBOX")
  544. # 2. 根据 UID 精准拉取 (使用 fetch)
  545. # 注意:IMAPClient 的 fetch 方法
  546. # UID 必须转为 int 或者 sequence set 字符串
  547. res, data = mail.uid('fetch', str(target_uid), '(RFC822)')
  548. # 🔴 修正点:不要写 if target_uid in res
  549. # res 是状态字符串 "OK",data 是包含邮件内容的列表
  550. if res != 'OK':
  551. return f"IMAP Fetch 失败,状态码: {res}"
  552. if not data or not data[0]:
  553. return f"未找到 UID {target_uid} 的邮件内容 (可能已被物理删除)"
  554. # data[0] 通常是 tuple (byte_header, byte_content),但也可能是 None
  555. if isinstance(data[0], tuple):
  556. raw_email_bytes = data[0][1]
  557. else:
  558. # 如果 data[0] 只是 bytes (例如 b')'),说明没拿到邮件体
  559. return f"邮件数据格式异常,无法解析: {str(data)}"
  560. msg = email.message_from_bytes(raw_email_bytes)
  561. # 3. 处理转发逻辑
  562. # 使用数据库中查到的标题,确保标题准确
  563. subject = target_subject
  564. # 修改 Header 进行转发
  565. del msg['From']
  566. del msg['To']
  567. del msg['Cc']
  568. del msg['Subject']
  569. msg['From'] = auth.email # 发件人覆写为当前授权账号
  570. msg['To'] = forward_to
  571. msg['Subject'] = f"FWD: {subject}"
  572. # 4. 发送邮件 (SMTP)
  573. EmailAuthorizationService.send_email_smtp(auth, msg)
  574. return f"邮件 '{subject}' (UID: {target_uid}) 已成功转发至: {forward_to}"
  575. except Exception as e:
  576. logger.error(f"IMAP Forward Error: {e}")
  577. return f"邮件转发过程出错: {str(e)}"
  578. finally:
  579. if mail:
  580. try:
  581. mail.logout()
  582. except: pass
  583. # 在线程池中运行耗时 IO 操作
  584. return await run_in_threadpool(_worker)
  585. @staticmethod
  586. async def send_email(
  587. auth,
  588. send_to: str,
  589. subject: str,
  590. content_type: str,
  591. content: str
  592. ):
  593. def _worker():
  594. msg = EmailMessage()
  595. msg["From"] = auth.email
  596. msg["To"] = send_to
  597. msg["Subject"] = subject
  598. if content_type.lower() == "html":
  599. msg.set_content("") # 占位
  600. msg.add_alternative(content, subtype="html")
  601. else:
  602. msg.set_content(content)
  603. EmailAuthorizationService.send_email_smtp(auth, msg)
  604. return f"邮件 '{subject}' 成功发送至: {send_to}"
  605. return await run_in_threadpool(_worker)
  606. @staticmethod
  607. async def send_email_bulk(
  608. auth,
  609. send_to: str,
  610. subject: str,
  611. content_type: str,
  612. content: str
  613. ):
  614. def _worker():
  615. bcc_list = [s.strip() for s in send_to.split(",") if s.strip()]
  616. msg = EmailMessage()
  617. msg["From"] = auth.email
  618. msg["To"] = bcc_list[0] if bcc_list else auth.email # Fallback
  619. msg["Subject"] = subject
  620. if content_type.lower() == "html":
  621. msg.set_content("")
  622. msg.add_alternative(content, subtype="html")
  623. else:
  624. msg.set_content(content)
  625. EmailAuthorizationService.send_email_smtp(auth, msg, bcc_list=bcc_list)
  626. return f"邮件 '{subject}' 成功发送至: {send_to}"
  627. return await run_in_threadpool(_worker)
  628. # ----------------------------------------------------------------------
  629. # 底层 SMTP 发送 (保持同步,供 Worker 调用)
  630. # ----------------------------------------------------------------------
  631. @staticmethod
  632. def send_email_smtp(auth, msg, bcc_list=None):
  633. if bcc_list is None:
  634. bcc_list = []
  635. # 这里的 connect 内部已经加了锁,是安全的
  636. mail = EmailAuthorizationService._connect_smtp_with_proxy(
  637. auth.smtp_server,
  638. auth.smtp_port,
  639. auth.proxy_host,
  640. auth.proxy_port,
  641. auth.proxy_username,
  642. auth.proxy_password,
  643. )
  644. try:
  645. mail.login(auth.email, auth.authorization_code)
  646. if bcc_list:
  647. mail.send_message(msg, to_addrs=bcc_list)
  648. else:
  649. mail.send_message(msg)
  650. finally:
  651. mail.quit()
  652. @staticmethod
  653. def _extract_body(msg, only_text: bool = True) -> str:
  654. # 纯 CPU 计算,不需要 async,保留原样
  655. body_parts = []
  656. if msg.is_multipart():
  657. for part in msg.walk():
  658. ctype = part.get_content_type()
  659. if only_text and ctype != "text/plain":
  660. continue
  661. if not only_text and ctype not in ["text/plain", "text/html"]:
  662. continue
  663. if part.get("Content-Disposition"):
  664. continue
  665. charset = part.get_content_charset() or "utf-8"
  666. try:
  667. payload = part.get_payload(decode=True)
  668. if payload:
  669. text = payload.decode(charset, errors="ignore")
  670. body_parts.append(text)
  671. except Exception:
  672. continue
  673. else:
  674. charset = msg.get_content_charset() or "utf-8"
  675. payload = msg.get_payload(decode=True)
  676. if payload:
  677. body_parts.append(payload.decode(charset, errors="ignore"))
  678. body = "\n".join(body_parts)
  679. return re.sub(r"\s+", " ", body.strip())