senders.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035
  1. # coding=utf-8
  2. """
  3. 消息发送器模块
  4. 将报告数据发送到各种通知渠道:
  5. - 飞书 (Feishu/Lark)
  6. - 钉钉 (DingTalk)
  7. - 企业微信 (WeCom/WeWork)
  8. - Telegram
  9. - 邮件 (Email)
  10. - ntfy
  11. - Bark
  12. - Slack
  13. 每个发送函数都支持分批发送,并通过参数化配置实现与 CONFIG 的解耦。
  14. """
  15. import smtplib
  16. import time
  17. from datetime import datetime
  18. from email.header import Header
  19. from email.mime.multipart import MIMEMultipart
  20. from email.mime.text import MIMEText
  21. from email.utils import formataddr, formatdate, make_msgid
  22. from pathlib import Path
  23. from typing import Callable, Dict, List, Optional
  24. from urllib.parse import urlparse
  25. import requests
  26. from .batch import add_batch_headers, get_max_batch_header_size
  27. from .formatters import convert_markdown_to_mrkdwn, strip_markdown
  28. # === SMTP 邮件配置 ===
  29. SMTP_CONFIGS = {
  30. # Gmail(使用 STARTTLS)
  31. "gmail.com": {"server": "smtp.gmail.com", "port": 587, "encryption": "TLS"},
  32. # QQ邮箱(使用 SSL,更稳定)
  33. "qq.com": {"server": "smtp.qq.com", "port": 465, "encryption": "SSL"},
  34. # Outlook(使用 STARTTLS)
  35. "outlook.com": {"server": "smtp-mail.outlook.com", "port": 587, "encryption": "TLS"},
  36. "hotmail.com": {"server": "smtp-mail.outlook.com", "port": 587, "encryption": "TLS"},
  37. "live.com": {"server": "smtp-mail.outlook.com", "port": 587, "encryption": "TLS"},
  38. # 网易邮箱(使用 SSL,更稳定)
  39. "163.com": {"server": "smtp.163.com", "port": 465, "encryption": "SSL"},
  40. "126.com": {"server": "smtp.126.com", "port": 465, "encryption": "SSL"},
  41. # 新浪邮箱(使用 SSL)
  42. "sina.com": {"server": "smtp.sina.com", "port": 465, "encryption": "SSL"},
  43. # 搜狐邮箱(使用 SSL)
  44. "sohu.com": {"server": "smtp.sohu.com", "port": 465, "encryption": "SSL"},
  45. # 天翼邮箱(使用 SSL)
  46. "189.cn": {"server": "smtp.189.cn", "port": 465, "encryption": "SSL"},
  47. # 阿里云邮箱(使用 TLS)
  48. "aliyun.com": {"server": "smtp.aliyun.com", "port": 465, "encryption": "TLS"},
  49. # Yandex邮箱(使用 TLS)
  50. "yandex.com": {"server": "smtp.yandex.com", "port": 465, "encryption": "TLS"},
  51. }
  52. def send_to_feishu(
  53. webhook_url: str,
  54. report_data: Dict,
  55. report_type: str,
  56. update_info: Optional[Dict] = None,
  57. proxy_url: Optional[str] = None,
  58. mode: str = "daily",
  59. account_label: str = "",
  60. *,
  61. batch_size: int = 29000,
  62. batch_interval: float = 1.0,
  63. split_content_func: Callable = None,
  64. get_time_func: Callable = None,
  65. ) -> bool:
  66. """
  67. 发送到飞书(支持分批发送)
  68. Args:
  69. webhook_url: 飞书 Webhook URL
  70. report_data: 报告数据
  71. report_type: 报告类型
  72. update_info: 更新信息(可选)
  73. proxy_url: 代理 URL(可选)
  74. mode: 报告模式 (daily/current)
  75. account_label: 账号标签(多账号时显示)
  76. batch_size: 批次大小(字节)
  77. batch_interval: 批次发送间隔(秒)
  78. split_content_func: 内容分批函数
  79. get_time_func: 获取当前时间的函数
  80. Returns:
  81. bool: 发送是否成功
  82. """
  83. headers = {"Content-Type": "application/json"}
  84. proxies = None
  85. if proxy_url:
  86. proxies = {"http": proxy_url, "https": proxy_url}
  87. # 日志前缀
  88. log_prefix = f"飞书{account_label}" if account_label else "飞书"
  89. # 预留批次头部空间,避免添加头部后超限
  90. header_reserve = get_max_batch_header_size("feishu")
  91. batches = split_content_func(
  92. report_data,
  93. "feishu",
  94. update_info,
  95. max_bytes=batch_size - header_reserve,
  96. mode=mode,
  97. )
  98. # 统一添加批次头部(已预留空间,不会超限)
  99. batches = add_batch_headers(batches, "feishu", batch_size)
  100. print(f"{log_prefix}消息分为 {len(batches)} 批次发送 [{report_type}]")
  101. # 逐批发送
  102. for i, batch_content in enumerate(batches, 1):
  103. content_size = len(batch_content.encode("utf-8"))
  104. print(
  105. f"发送{log_prefix}第 {i}/{len(batches)} 批次,大小:{content_size} 字节 [{report_type}]"
  106. )
  107. total_titles = sum(
  108. len(stat["titles"]) for stat in report_data["stats"] if stat["count"] > 0
  109. )
  110. now = get_time_func() if get_time_func else datetime.now()
  111. payload = {
  112. "msg_type": "text",
  113. "content": {
  114. "total_titles": total_titles,
  115. "timestamp": now.strftime("%Y-%m-%d %H:%M:%S"),
  116. "report_type": report_type,
  117. "text": batch_content,
  118. },
  119. }
  120. try:
  121. response = requests.post(
  122. webhook_url, headers=headers, json=payload, proxies=proxies, timeout=30
  123. )
  124. if response.status_code == 200:
  125. result = response.json()
  126. # 检查飞书的响应状态
  127. if result.get("StatusCode") == 0 or result.get("code") == 0:
  128. print(f"{log_prefix}第 {i}/{len(batches)} 批次发送成功 [{report_type}]")
  129. # 批次间间隔
  130. if i < len(batches):
  131. time.sleep(batch_interval)
  132. else:
  133. error_msg = result.get("msg") or result.get("StatusMessage", "未知错误")
  134. print(
  135. f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],错误:{error_msg}"
  136. )
  137. return False
  138. else:
  139. print(
  140. f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],状态码:{response.status_code}"
  141. )
  142. return False
  143. except Exception as e:
  144. print(f"{log_prefix}第 {i}/{len(batches)} 批次发送出错 [{report_type}]:{e}")
  145. return False
  146. print(f"{log_prefix}所有 {len(batches)} 批次发送完成 [{report_type}]")
  147. return True
  148. def send_to_dingtalk(
  149. webhook_url: str,
  150. report_data: Dict,
  151. report_type: str,
  152. update_info: Optional[Dict] = None,
  153. proxy_url: Optional[str] = None,
  154. mode: str = "daily",
  155. account_label: str = "",
  156. *,
  157. batch_size: int = 20000,
  158. batch_interval: float = 1.0,
  159. split_content_func: Callable = None,
  160. ) -> bool:
  161. """
  162. 发送到钉钉(支持分批发送)
  163. Args:
  164. webhook_url: 钉钉 Webhook URL
  165. report_data: 报告数据
  166. report_type: 报告类型
  167. update_info: 更新信息(可选)
  168. proxy_url: 代理 URL(可选)
  169. mode: 报告模式 (daily/current)
  170. account_label: 账号标签(多账号时显示)
  171. batch_size: 批次大小(字节)
  172. batch_interval: 批次发送间隔(秒)
  173. split_content_func: 内容分批函数
  174. Returns:
  175. bool: 发送是否成功
  176. """
  177. headers = {"Content-Type": "application/json"}
  178. proxies = None
  179. if proxy_url:
  180. proxies = {"http": proxy_url, "https": proxy_url}
  181. # 日志前缀
  182. log_prefix = f"钉钉{account_label}" if account_label else "钉钉"
  183. # 预留批次头部空间,避免添加头部后超限
  184. header_reserve = get_max_batch_header_size("dingtalk")
  185. batches = split_content_func(
  186. report_data,
  187. "dingtalk",
  188. update_info,
  189. max_bytes=batch_size - header_reserve,
  190. mode=mode,
  191. )
  192. # 统一添加批次头部(已预留空间,不会超限)
  193. batches = add_batch_headers(batches, "dingtalk", batch_size)
  194. print(f"{log_prefix}消息分为 {len(batches)} 批次发送 [{report_type}]")
  195. # 逐批发送
  196. for i, batch_content in enumerate(batches, 1):
  197. content_size = len(batch_content.encode("utf-8"))
  198. print(
  199. f"发送{log_prefix}第 {i}/{len(batches)} 批次,大小:{content_size} 字节 [{report_type}]"
  200. )
  201. payload = {
  202. "msgtype": "markdown",
  203. "markdown": {
  204. "title": f"TrendRadar 热点分析报告 - {report_type}",
  205. "text": batch_content,
  206. },
  207. }
  208. try:
  209. response = requests.post(
  210. webhook_url, headers=headers, json=payload, proxies=proxies, timeout=30
  211. )
  212. if response.status_code == 200:
  213. result = response.json()
  214. if result.get("errcode") == 0:
  215. print(f"{log_prefix}第 {i}/{len(batches)} 批次发送成功 [{report_type}]")
  216. # 批次间间隔
  217. if i < len(batches):
  218. time.sleep(batch_interval)
  219. else:
  220. print(
  221. f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],错误:{result.get('errmsg')}"
  222. )
  223. return False
  224. else:
  225. print(
  226. f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],状态码:{response.status_code}"
  227. )
  228. return False
  229. except Exception as e:
  230. print(f"{log_prefix}第 {i}/{len(batches)} 批次发送出错 [{report_type}]:{e}")
  231. return False
  232. print(f"{log_prefix}所有 {len(batches)} 批次发送完成 [{report_type}]")
  233. return True
  234. def send_to_wework(
  235. webhook_url: str,
  236. report_data: Dict,
  237. report_type: str,
  238. update_info: Optional[Dict] = None,
  239. proxy_url: Optional[str] = None,
  240. mode: str = "daily",
  241. account_label: str = "",
  242. *,
  243. batch_size: int = 4000,
  244. batch_interval: float = 1.0,
  245. msg_type: str = "markdown",
  246. split_content_func: Callable = None,
  247. ) -> bool:
  248. """
  249. 发送到企业微信(支持分批发送,支持 markdown 和 text 两种格式)
  250. Args:
  251. webhook_url: 企业微信 Webhook URL
  252. report_data: 报告数据
  253. report_type: 报告类型
  254. update_info: 更新信息(可选)
  255. proxy_url: 代理 URL(可选)
  256. mode: 报告模式 (daily/current)
  257. account_label: 账号标签(多账号时显示)
  258. batch_size: 批次大小(字节)
  259. batch_interval: 批次发送间隔(秒)
  260. msg_type: 消息类型 (markdown/text)
  261. split_content_func: 内容分批函数
  262. Returns:
  263. bool: 发送是否成功
  264. """
  265. headers = {"Content-Type": "application/json"}
  266. proxies = None
  267. if proxy_url:
  268. proxies = {"http": proxy_url, "https": proxy_url}
  269. # 日志前缀
  270. log_prefix = f"企业微信{account_label}" if account_label else "企业微信"
  271. # 获取消息类型配置(markdown 或 text)
  272. is_text_mode = msg_type.lower() == "text"
  273. if is_text_mode:
  274. print(f"{log_prefix}使用 text 格式(个人微信模式)[{report_type}]")
  275. else:
  276. print(f"{log_prefix}使用 markdown 格式(群机器人模式)[{report_type}]")
  277. # text 模式使用 wework_text,markdown 模式使用 wework
  278. header_format_type = "wework_text" if is_text_mode else "wework"
  279. # 获取分批内容,预留批次头部空间
  280. header_reserve = get_max_batch_header_size(header_format_type)
  281. batches = split_content_func(
  282. report_data, "wework", update_info, max_bytes=batch_size - header_reserve, mode=mode
  283. )
  284. # 统一添加批次头部(已预留空间,不会超限)
  285. batches = add_batch_headers(batches, header_format_type, batch_size)
  286. print(f"{log_prefix}消息分为 {len(batches)} 批次发送 [{report_type}]")
  287. # 逐批发送
  288. for i, batch_content in enumerate(batches, 1):
  289. # 根据消息类型构建 payload
  290. if is_text_mode:
  291. # text 格式:去除 markdown 语法
  292. plain_content = strip_markdown(batch_content)
  293. payload = {"msgtype": "text", "text": {"content": plain_content}}
  294. content_size = len(plain_content.encode("utf-8"))
  295. else:
  296. # markdown 格式:保持原样
  297. payload = {"msgtype": "markdown", "markdown": {"content": batch_content}}
  298. content_size = len(batch_content.encode("utf-8"))
  299. print(
  300. f"发送{log_prefix}第 {i}/{len(batches)} 批次,大小:{content_size} 字节 [{report_type}]"
  301. )
  302. try:
  303. response = requests.post(
  304. webhook_url, headers=headers, json=payload, proxies=proxies, timeout=30
  305. )
  306. if response.status_code == 200:
  307. result = response.json()
  308. if result.get("errcode") == 0:
  309. print(f"{log_prefix}第 {i}/{len(batches)} 批次发送成功 [{report_type}]")
  310. # 批次间间隔
  311. if i < len(batches):
  312. time.sleep(batch_interval)
  313. else:
  314. print(
  315. f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],错误:{result.get('errmsg')}"
  316. )
  317. return False
  318. else:
  319. print(
  320. f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],状态码:{response.status_code}"
  321. )
  322. return False
  323. except Exception as e:
  324. print(f"{log_prefix}第 {i}/{len(batches)} 批次发送出错 [{report_type}]:{e}")
  325. return False
  326. print(f"{log_prefix}所有 {len(batches)} 批次发送完成 [{report_type}]")
  327. return True
  328. def send_to_telegram(
  329. bot_token: str,
  330. chat_id: str,
  331. report_data: Dict,
  332. report_type: str,
  333. update_info: Optional[Dict] = None,
  334. proxy_url: Optional[str] = None,
  335. mode: str = "daily",
  336. account_label: str = "",
  337. *,
  338. batch_size: int = 4000,
  339. batch_interval: float = 1.0,
  340. split_content_func: Callable = None,
  341. ) -> bool:
  342. """
  343. 发送到 Telegram(支持分批发送)
  344. Args:
  345. bot_token: Telegram Bot Token
  346. chat_id: Telegram Chat ID
  347. report_data: 报告数据
  348. report_type: 报告类型
  349. update_info: 更新信息(可选)
  350. proxy_url: 代理 URL(可选)
  351. mode: 报告模式 (daily/current)
  352. account_label: 账号标签(多账号时显示)
  353. batch_size: 批次大小(字节)
  354. batch_interval: 批次发送间隔(秒)
  355. split_content_func: 内容分批函数
  356. Returns:
  357. bool: 发送是否成功
  358. """
  359. headers = {"Content-Type": "application/json"}
  360. url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
  361. proxies = None
  362. if proxy_url:
  363. proxies = {"http": proxy_url, "https": proxy_url}
  364. # 日志前缀
  365. log_prefix = f"Telegram{account_label}" if account_label else "Telegram"
  366. # 获取分批内容,预留批次头部空间
  367. header_reserve = get_max_batch_header_size("telegram")
  368. batches = split_content_func(
  369. report_data, "telegram", update_info, max_bytes=batch_size - header_reserve, mode=mode
  370. )
  371. # 统一添加批次头部(已预留空间,不会超限)
  372. batches = add_batch_headers(batches, "telegram", batch_size)
  373. print(f"{log_prefix}消息分为 {len(batches)} 批次发送 [{report_type}]")
  374. # 逐批发送
  375. for i, batch_content in enumerate(batches, 1):
  376. content_size = len(batch_content.encode("utf-8"))
  377. print(
  378. f"发送{log_prefix}第 {i}/{len(batches)} 批次,大小:{content_size} 字节 [{report_type}]"
  379. )
  380. payload = {
  381. "chat_id": chat_id,
  382. "text": batch_content,
  383. "parse_mode": "HTML",
  384. "disable_web_page_preview": True,
  385. }
  386. try:
  387. response = requests.post(
  388. url, headers=headers, json=payload, proxies=proxies, timeout=30
  389. )
  390. if response.status_code == 200:
  391. result = response.json()
  392. if result.get("ok"):
  393. print(f"{log_prefix}第 {i}/{len(batches)} 批次发送成功 [{report_type}]")
  394. # 批次间间隔
  395. if i < len(batches):
  396. time.sleep(batch_interval)
  397. else:
  398. print(
  399. f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],错误:{result.get('description')}"
  400. )
  401. return False
  402. else:
  403. print(
  404. f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],状态码:{response.status_code}"
  405. )
  406. return False
  407. except Exception as e:
  408. print(f"{log_prefix}第 {i}/{len(batches)} 批次发送出错 [{report_type}]:{e}")
  409. return False
  410. print(f"{log_prefix}所有 {len(batches)} 批次发送完成 [{report_type}]")
  411. return True
  412. def send_to_email(
  413. from_email: str,
  414. password: str,
  415. to_email: str,
  416. report_type: str,
  417. html_file_path: str,
  418. custom_smtp_server: Optional[str] = None,
  419. custom_smtp_port: Optional[int] = None,
  420. *,
  421. get_time_func: Callable = None,
  422. ) -> bool:
  423. """
  424. 发送邮件通知
  425. Args:
  426. from_email: 发件人邮箱
  427. password: 邮箱密码/授权码
  428. to_email: 收件人邮箱(多个用逗号分隔)
  429. report_type: 报告类型
  430. html_file_path: HTML 报告文件路径
  431. custom_smtp_server: 自定义 SMTP 服务器(可选)
  432. custom_smtp_port: 自定义 SMTP 端口(可选)
  433. get_time_func: 获取当前时间的函数
  434. Returns:
  435. bool: 发送是否成功
  436. """
  437. try:
  438. if not html_file_path or not Path(html_file_path).exists():
  439. print(f"错误:HTML文件不存在或未提供: {html_file_path}")
  440. return False
  441. print(f"使用HTML文件: {html_file_path}")
  442. with open(html_file_path, "r", encoding="utf-8") as f:
  443. html_content = f.read()
  444. domain = from_email.split("@")[-1].lower()
  445. if custom_smtp_server and custom_smtp_port:
  446. # 使用自定义 SMTP 配置
  447. smtp_server = custom_smtp_server
  448. smtp_port = int(custom_smtp_port)
  449. # 根据端口判断加密方式:465=SSL, 587=TLS
  450. if smtp_port == 465:
  451. use_tls = False # SSL 模式(SMTP_SSL)
  452. elif smtp_port == 587:
  453. use_tls = True # TLS 模式(STARTTLS)
  454. else:
  455. # 其他端口优先尝试 TLS(更安全,更广泛支持)
  456. use_tls = True
  457. elif domain in SMTP_CONFIGS:
  458. # 使用预设配置
  459. config = SMTP_CONFIGS[domain]
  460. smtp_server = config["server"]
  461. smtp_port = config["port"]
  462. use_tls = config["encryption"] == "TLS"
  463. else:
  464. print(f"未识别的邮箱服务商: {domain},使用通用 SMTP 配置")
  465. smtp_server = f"smtp.{domain}"
  466. smtp_port = 587
  467. use_tls = True
  468. msg = MIMEMultipart("alternative")
  469. # 严格按照 RFC 标准设置 From header
  470. sender_name = "TrendRadar"
  471. msg["From"] = formataddr((sender_name, from_email))
  472. # 设置收件人
  473. recipients = [addr.strip() for addr in to_email.split(",")]
  474. if len(recipients) == 1:
  475. msg["To"] = recipients[0]
  476. else:
  477. msg["To"] = ", ".join(recipients)
  478. # 设置邮件主题
  479. now = get_time_func() if get_time_func else datetime.now()
  480. subject = f"TrendRadar 热点分析报告 - {report_type} - {now.strftime('%m月%d日 %H:%M')}"
  481. msg["Subject"] = Header(subject, "utf-8")
  482. # 设置其他标准 header
  483. msg["MIME-Version"] = "1.0"
  484. msg["Date"] = formatdate(localtime=True)
  485. msg["Message-ID"] = make_msgid()
  486. # 添加纯文本部分(作为备选)
  487. text_content = f"""
  488. TrendRadar 热点分析报告
  489. ========================
  490. 报告类型:{report_type}
  491. 生成时间:{now.strftime('%Y-%m-%d %H:%M:%S')}
  492. 请使用支持HTML的邮件客户端查看完整报告内容。
  493. """
  494. text_part = MIMEText(text_content, "plain", "utf-8")
  495. msg.attach(text_part)
  496. html_part = MIMEText(html_content, "html", "utf-8")
  497. msg.attach(html_part)
  498. print(f"正在发送邮件到 {to_email}...")
  499. print(f"SMTP 服务器: {smtp_server}:{smtp_port}")
  500. print(f"发件人: {from_email}")
  501. try:
  502. if use_tls:
  503. # TLS 模式
  504. server = smtplib.SMTP(smtp_server, smtp_port, timeout=30)
  505. server.set_debuglevel(0) # 设为1可以查看详细调试信息
  506. server.ehlo()
  507. server.starttls()
  508. server.ehlo()
  509. else:
  510. # SSL 模式
  511. server = smtplib.SMTP_SSL(smtp_server, smtp_port, timeout=30)
  512. server.set_debuglevel(0)
  513. server.ehlo()
  514. # 登录
  515. server.login(from_email, password)
  516. # 发送邮件
  517. server.send_message(msg)
  518. server.quit()
  519. print(f"邮件发送成功 [{report_type}] -> {to_email}")
  520. return True
  521. except smtplib.SMTPServerDisconnected:
  522. print("邮件发送失败:服务器意外断开连接,请检查网络或稍后重试")
  523. return False
  524. except smtplib.SMTPAuthenticationError as e:
  525. print("邮件发送失败:认证错误,请检查邮箱和密码/授权码")
  526. print(f"详细错误: {str(e)}")
  527. return False
  528. except smtplib.SMTPRecipientsRefused as e:
  529. print(f"邮件发送失败:收件人地址被拒绝 {e}")
  530. return False
  531. except smtplib.SMTPSenderRefused as e:
  532. print(f"邮件发送失败:发件人地址被拒绝 {e}")
  533. return False
  534. except smtplib.SMTPDataError as e:
  535. print(f"邮件发送失败:邮件数据错误 {e}")
  536. return False
  537. except smtplib.SMTPConnectError as e:
  538. print(f"邮件发送失败:无法连接到 SMTP 服务器 {smtp_server}:{smtp_port}")
  539. print(f"详细错误: {str(e)}")
  540. return False
  541. except Exception as e:
  542. print(f"邮件发送失败 [{report_type}]:{e}")
  543. import traceback
  544. traceback.print_exc()
  545. return False
  546. def send_to_ntfy(
  547. server_url: str,
  548. topic: str,
  549. token: Optional[str],
  550. report_data: Dict,
  551. report_type: str,
  552. update_info: Optional[Dict] = None,
  553. proxy_url: Optional[str] = None,
  554. mode: str = "daily",
  555. account_label: str = "",
  556. *,
  557. batch_size: int = 3800,
  558. split_content_func: Callable = None,
  559. ) -> bool:
  560. """
  561. 发送到 ntfy(支持分批发送,严格遵守4KB限制)
  562. Args:
  563. server_url: ntfy 服务器 URL
  564. topic: ntfy 主题
  565. token: ntfy 访问令牌(可选)
  566. report_data: 报告数据
  567. report_type: 报告类型
  568. update_info: 更新信息(可选)
  569. proxy_url: 代理 URL(可选)
  570. mode: 报告模式 (daily/current)
  571. account_label: 账号标签(多账号时显示)
  572. batch_size: 批次大小(字节)
  573. split_content_func: 内容分批函数
  574. Returns:
  575. bool: 发送是否成功
  576. """
  577. # 日志前缀
  578. log_prefix = f"ntfy{account_label}" if account_label else "ntfy"
  579. # 避免 HTTP header 编码问题
  580. report_type_en_map = {
  581. "当日汇总": "Daily Summary",
  582. "当前榜单汇总": "Current Ranking",
  583. "增量更新": "Incremental Update",
  584. "实时增量": "Realtime Incremental",
  585. "实时当前榜单": "Realtime Current Ranking",
  586. }
  587. report_type_en = report_type_en_map.get(report_type, "News Report")
  588. headers = {
  589. "Content-Type": "text/plain; charset=utf-8",
  590. "Markdown": "yes",
  591. "Title": report_type_en,
  592. "Priority": "default",
  593. "Tags": "news",
  594. }
  595. if token:
  596. headers["Authorization"] = f"Bearer {token}"
  597. # 构建完整URL,确保格式正确
  598. base_url = server_url.rstrip("/")
  599. if not base_url.startswith(("http://", "https://")):
  600. base_url = f"https://{base_url}"
  601. url = f"{base_url}/{topic}"
  602. proxies = None
  603. if proxy_url:
  604. proxies = {"http": proxy_url, "https": proxy_url}
  605. # 获取分批内容,预留批次头部空间
  606. header_reserve = get_max_batch_header_size("ntfy")
  607. batches = split_content_func(
  608. report_data, "ntfy", update_info, max_bytes=batch_size - header_reserve, mode=mode
  609. )
  610. # 统一添加批次头部(已预留空间,不会超限)
  611. batches = add_batch_headers(batches, "ntfy", batch_size)
  612. total_batches = len(batches)
  613. print(f"{log_prefix}消息分为 {total_batches} 批次发送 [{report_type}]")
  614. # 反转批次顺序,使得在ntfy客户端显示时顺序正确
  615. # ntfy显示最新消息在上面,所以我们从最后一批开始推送
  616. reversed_batches = list(reversed(batches))
  617. print(f"{log_prefix}将按反向顺序推送(最后批次先推送),确保客户端显示顺序正确")
  618. # 逐批发送(反向顺序)
  619. success_count = 0
  620. for idx, batch_content in enumerate(reversed_batches, 1):
  621. # 计算正确的批次编号(用户视角的编号)
  622. actual_batch_num = total_batches - idx + 1
  623. content_size = len(batch_content.encode("utf-8"))
  624. print(
  625. f"发送{log_prefix}第 {actual_batch_num}/{total_batches} 批次(推送顺序: {idx}/{total_batches}),大小:{content_size} 字节 [{report_type}]"
  626. )
  627. # 检查消息大小,确保不超过4KB
  628. if content_size > 4096:
  629. print(f"警告:{log_prefix}第 {actual_batch_num} 批次消息过大({content_size} 字节),可能被拒绝")
  630. # 更新 headers 的批次标识
  631. current_headers = headers.copy()
  632. if total_batches > 1:
  633. current_headers["Title"] = f"{report_type_en} ({actual_batch_num}/{total_batches})"
  634. try:
  635. response = requests.post(
  636. url,
  637. headers=current_headers,
  638. data=batch_content.encode("utf-8"),
  639. proxies=proxies,
  640. timeout=30,
  641. )
  642. if response.status_code == 200:
  643. print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次发送成功 [{report_type}]")
  644. success_count += 1
  645. if idx < total_batches:
  646. # 公共服务器建议 2-3 秒,自托管可以更短
  647. interval = 2 if "ntfy.sh" in server_url else 1
  648. time.sleep(interval)
  649. elif response.status_code == 429:
  650. print(
  651. f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次速率限制 [{report_type}],等待后重试"
  652. )
  653. time.sleep(10) # 等待10秒后重试
  654. # 重试一次
  655. retry_response = requests.post(
  656. url,
  657. headers=current_headers,
  658. data=batch_content.encode("utf-8"),
  659. proxies=proxies,
  660. timeout=30,
  661. )
  662. if retry_response.status_code == 200:
  663. print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次重试成功 [{report_type}]")
  664. success_count += 1
  665. else:
  666. print(
  667. f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次重试失败,状态码:{retry_response.status_code}"
  668. )
  669. elif response.status_code == 413:
  670. print(
  671. f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次消息过大被拒绝 [{report_type}],消息大小:{content_size} 字节"
  672. )
  673. else:
  674. print(
  675. f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次发送失败 [{report_type}],状态码:{response.status_code}"
  676. )
  677. try:
  678. print(f"错误详情:{response.text}")
  679. except:
  680. pass
  681. except requests.exceptions.ConnectTimeout:
  682. print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次连接超时 [{report_type}]")
  683. except requests.exceptions.ReadTimeout:
  684. print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次读取超时 [{report_type}]")
  685. except requests.exceptions.ConnectionError as e:
  686. print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次连接错误 [{report_type}]:{e}")
  687. except Exception as e:
  688. print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次发送异常 [{report_type}]:{e}")
  689. # 判断整体发送是否成功
  690. if success_count == total_batches:
  691. print(f"{log_prefix}所有 {total_batches} 批次发送完成 [{report_type}]")
  692. return True
  693. elif success_count > 0:
  694. print(f"{log_prefix}部分发送成功:{success_count}/{total_batches} 批次 [{report_type}]")
  695. return True # 部分成功也视为成功
  696. else:
  697. print(f"{log_prefix}发送完全失败 [{report_type}]")
  698. return False
  699. def send_to_bark(
  700. bark_url: str,
  701. report_data: Dict,
  702. report_type: str,
  703. update_info: Optional[Dict] = None,
  704. proxy_url: Optional[str] = None,
  705. mode: str = "daily",
  706. account_label: str = "",
  707. *,
  708. batch_size: int = 3600,
  709. batch_interval: float = 1.0,
  710. split_content_func: Callable = None,
  711. ) -> bool:
  712. """
  713. 发送到 Bark(支持分批发送,使用 markdown 格式)
  714. Args:
  715. bark_url: Bark URL(包含 device_key)
  716. report_data: 报告数据
  717. report_type: 报告类型
  718. update_info: 更新信息(可选)
  719. proxy_url: 代理 URL(可选)
  720. mode: 报告模式 (daily/current)
  721. account_label: 账号标签(多账号时显示)
  722. batch_size: 批次大小(字节)
  723. batch_interval: 批次发送间隔(秒)
  724. split_content_func: 内容分批函数
  725. Returns:
  726. bool: 发送是否成功
  727. """
  728. # 日志前缀
  729. log_prefix = f"Bark{account_label}" if account_label else "Bark"
  730. proxies = None
  731. if proxy_url:
  732. proxies = {"http": proxy_url, "https": proxy_url}
  733. # 解析 Bark URL,提取 device_key 和 API 端点
  734. # Bark URL 格式: https://api.day.app/device_key 或 https://bark.day.app/device_key
  735. parsed_url = urlparse(bark_url)
  736. device_key = parsed_url.path.strip('/').split('/')[0] if parsed_url.path else None
  737. if not device_key:
  738. print(f"{log_prefix} URL 格式错误,无法提取 device_key: {bark_url}")
  739. return False
  740. # 构建正确的 API 端点
  741. api_endpoint = f"{parsed_url.scheme}://{parsed_url.netloc}/push"
  742. # 获取分批内容,预留批次头部空间
  743. header_reserve = get_max_batch_header_size("bark")
  744. batches = split_content_func(
  745. report_data, "bark", update_info, max_bytes=batch_size - header_reserve, mode=mode
  746. )
  747. # 统一添加批次头部(已预留空间,不会超限)
  748. batches = add_batch_headers(batches, "bark", batch_size)
  749. total_batches = len(batches)
  750. print(f"{log_prefix}消息分为 {total_batches} 批次发送 [{report_type}]")
  751. # 反转批次顺序,使得在Bark客户端显示时顺序正确
  752. # Bark显示最新消息在上面,所以我们从最后一批开始推送
  753. reversed_batches = list(reversed(batches))
  754. print(f"{log_prefix}将按反向顺序推送(最后批次先推送),确保客户端显示顺序正确")
  755. # 逐批发送(反向顺序)
  756. success_count = 0
  757. for idx, batch_content in enumerate(reversed_batches, 1):
  758. # 计算正确的批次编号(用户视角的编号)
  759. actual_batch_num = total_batches - idx + 1
  760. content_size = len(batch_content.encode("utf-8"))
  761. print(
  762. f"发送{log_prefix}第 {actual_batch_num}/{total_batches} 批次(推送顺序: {idx}/{total_batches}),大小:{content_size} 字节 [{report_type}]"
  763. )
  764. # 检查消息大小(Bark使用APNs,限制4KB)
  765. if content_size > 4096:
  766. print(
  767. f"警告:{log_prefix}第 {actual_batch_num}/{total_batches} 批次消息过大({content_size} 字节),可能被拒绝"
  768. )
  769. # 构建JSON payload
  770. payload = {
  771. "title": report_type,
  772. "markdown": batch_content,
  773. "device_key": device_key,
  774. "sound": "default",
  775. "group": "TrendRadar",
  776. "action": "none", # 点击推送跳到 APP 不弹出弹框,方便阅读
  777. }
  778. try:
  779. response = requests.post(
  780. api_endpoint,
  781. json=payload,
  782. proxies=proxies,
  783. timeout=30,
  784. )
  785. if response.status_code == 200:
  786. result = response.json()
  787. if result.get("code") == 200:
  788. print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次发送成功 [{report_type}]")
  789. success_count += 1
  790. # 批次间间隔
  791. if idx < total_batches:
  792. time.sleep(batch_interval)
  793. else:
  794. print(
  795. f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次发送失败 [{report_type}],错误:{result.get('message', '未知错误')}"
  796. )
  797. else:
  798. print(
  799. f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次发送失败 [{report_type}],状态码:{response.status_code}"
  800. )
  801. try:
  802. print(f"错误详情:{response.text}")
  803. except:
  804. pass
  805. except requests.exceptions.ConnectTimeout:
  806. print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次连接超时 [{report_type}]")
  807. except requests.exceptions.ReadTimeout:
  808. print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次读取超时 [{report_type}]")
  809. except requests.exceptions.ConnectionError as e:
  810. print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次连接错误 [{report_type}]:{e}")
  811. except Exception as e:
  812. print(f"{log_prefix}第 {actual_batch_num}/{total_batches} 批次发送异常 [{report_type}]:{e}")
  813. # 判断整体发送是否成功
  814. if success_count == total_batches:
  815. print(f"{log_prefix}所有 {total_batches} 批次发送完成 [{report_type}]")
  816. return True
  817. elif success_count > 0:
  818. print(f"{log_prefix}部分发送成功:{success_count}/{total_batches} 批次 [{report_type}]")
  819. return True # 部分成功也视为成功
  820. else:
  821. print(f"{log_prefix}发送完全失败 [{report_type}]")
  822. return False
  823. def send_to_slack(
  824. webhook_url: str,
  825. report_data: Dict,
  826. report_type: str,
  827. update_info: Optional[Dict] = None,
  828. proxy_url: Optional[str] = None,
  829. mode: str = "daily",
  830. account_label: str = "",
  831. *,
  832. batch_size: int = 4000,
  833. batch_interval: float = 1.0,
  834. split_content_func: Callable = None,
  835. ) -> bool:
  836. """
  837. 发送到 Slack(支持分批发送,使用 mrkdwn 格式)
  838. Args:
  839. webhook_url: Slack Webhook URL
  840. report_data: 报告数据
  841. report_type: 报告类型
  842. update_info: 更新信息(可选)
  843. proxy_url: 代理 URL(可选)
  844. mode: 报告模式 (daily/current)
  845. account_label: 账号标签(多账号时显示)
  846. batch_size: 批次大小(字节)
  847. batch_interval: 批次发送间隔(秒)
  848. split_content_func: 内容分批函数
  849. Returns:
  850. bool: 发送是否成功
  851. """
  852. headers = {"Content-Type": "application/json"}
  853. proxies = None
  854. if proxy_url:
  855. proxies = {"http": proxy_url, "https": proxy_url}
  856. # 日志前缀
  857. log_prefix = f"Slack{account_label}" if account_label else "Slack"
  858. # 获取分批内容,预留批次头部空间
  859. header_reserve = get_max_batch_header_size("slack")
  860. batches = split_content_func(
  861. report_data, "slack", update_info, max_bytes=batch_size - header_reserve, mode=mode
  862. )
  863. # 统一添加批次头部(已预留空间,不会超限)
  864. batches = add_batch_headers(batches, "slack", batch_size)
  865. print(f"{log_prefix}消息分为 {len(batches)} 批次发送 [{report_type}]")
  866. # 逐批发送
  867. for i, batch_content in enumerate(batches, 1):
  868. # 转换 Markdown 到 mrkdwn 格式
  869. mrkdwn_content = convert_markdown_to_mrkdwn(batch_content)
  870. content_size = len(mrkdwn_content.encode("utf-8"))
  871. print(
  872. f"发送{log_prefix}第 {i}/{len(batches)} 批次,大小:{content_size} 字节 [{report_type}]"
  873. )
  874. # 构建 Slack payload(使用简单的 text 字段,支持 mrkdwn)
  875. payload = {"text": mrkdwn_content}
  876. try:
  877. response = requests.post(
  878. webhook_url, headers=headers, json=payload, proxies=proxies, timeout=30
  879. )
  880. # Slack Incoming Webhooks 成功时返回 "ok" 文本
  881. if response.status_code == 200 and response.text == "ok":
  882. print(f"{log_prefix}第 {i}/{len(batches)} 批次发送成功 [{report_type}]")
  883. # 批次间间隔
  884. if i < len(batches):
  885. time.sleep(batch_interval)
  886. else:
  887. error_msg = response.text if response.text else f"状态码:{response.status_code}"
  888. print(
  889. f"{log_prefix}第 {i}/{len(batches)} 批次发送失败 [{report_type}],错误:{error_msg}"
  890. )
  891. return False
  892. except Exception as e:
  893. print(f"{log_prefix}第 {i}/{len(batches)} 批次发送出错 [{report_type}]:{e}")
  894. return False
  895. print(f"{log_prefix}所有 {len(batches)} 批次发送完成 [{report_type}]")
  896. return True