#!/usr/bin/env python3 """ health-send-mail.py — 通过 QQ 邮箱 SMTP 465 SSL 发邮件 Usage: QQ_USER=f1f3@qq.com QQ_AUTH_CODE=xxx SMTP_HOST=smtp.qq.com SMTP_PORT=465 \ python3 health-send-mail.py <<< "body" Env required: QQ_USER 发件邮箱 (= 收件邮箱) QQ_AUTH_CODE QQ 邮箱授权码 (不是登录密码) SMTP_HOST 默认 smtp.qq.com SMTP_PORT 默认 465 """ import os import sys import smtplib import ssl import datetime from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.utils import formataddr def main(): if len(sys.argv) < 2: print("Usage: health-send-mail.py ", file=sys.stderr) sys.exit(2) subject = sys.argv[1] body = sys.stdin.read() if not sys.stdin.isatty() else "(empty)" user = os.environ.get('QQ_USER', '').strip() pwd = os.environ.get('QQ_AUTH_CODE', '').strip() host = os.environ.get('SMTP_HOST', 'smtp.qq.com').strip() port = int(os.environ.get('SMTP_PORT', '465')) sender_name = os.environ.get('SENDER_NAME', 'book 监控') if not user or not pwd: print("MISSING: QQ_USER / QQ_AUTH_CODE env not set", file=sys.stderr) sys.exit(3) msg = MIMEMultipart() msg['From'] = formataddr((sender_name, user)) msg['To'] = user msg['Subject'] = subject msg['Date'] = datetime.datetime.now().strftime('%a, %d %b %Y %H:%M:%S %z') msg.attach(MIMEText(body, 'plain', 'utf-8')) ctx = ssl.create_default_context() try: with smtplib.SMTP_SSL(host, port, timeout=15, context=ctx) as s: s.login(user, pwd) s.sendmail(user, [user], msg.as_string()) print(f"OK: sent '{subject}' to {user}") sys.exit(0) except smtplib.SMTPAuthenticationError as e: print(f"AUTH FAIL: {e} (check QQ_AUTH_CODE, may need reissue at mail.qq.com)", file=sys.stderr) sys.exit(4) except Exception as e: print(f"SMTP FAIL [{type(e).__name__}]: {e}", file=sys.stderr) sys.exit(5) if __name__ == '__main__': main()