notify.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. """Send email notification via SMTP."""
  2. import json
  3. import smtplib
  4. from email.mime.text import MIMEText
  5. from email.mime.multipart import MIMEMultipart
  6. from shared import get_ssm, update_job
  7. def handler(event, context):
  8. # Step Functions Catch 会把原始 input 包在 error 结构里
  9. # 正常流程: event 有 job_id, email, summary
  10. # 错误流程: event 有 job_id, email + error_info.Error/Cause
  11. job_id = event.get('job_id', 'unknown')
  12. email = event.get('email', '')
  13. user_name = event.get('user_name', '')
  14. summary = event.get('summary', '')
  15. error_info = event.get('error_info', {})
  16. error = error_info.get('Error', '') if isinstance(error_info, dict) else ''
  17. cause = error_info.get('Cause', '') if isinstance(error_info, dict) else ''
  18. if error or cause:
  19. subject = f"[SP Transcribe] 任务 {job_id} 失败"
  20. body = f"任务 {job_id} 处理失败。\n\n错误: {error}\n详情: {cause[:500]}"
  21. if job_id != 'unknown':
  22. update_job(job_id, status='FAILED', error=str(error)[:500])
  23. else:
  24. subject = f"[SP Transcribe] 会议纪要 - {job_id}"
  25. body = summary or '(无总结内容)'
  26. update_job(job_id, status='COMPLETED')
  27. if not email:
  28. return {**event, 'notify': 'skipped (no email)'}
  29. # Send via SMTP
  30. smtp_host = get_ssm('smtp/host')
  31. smtp_port = int(get_ssm('smtp/port'))
  32. smtp_user = get_ssm('smtp/user')
  33. smtp_pass = get_ssm('smtp/pass')
  34. smtp_from = get_ssm('smtp/from')
  35. msg = MIMEMultipart('alternative')
  36. msg['Subject'] = subject
  37. msg['From'] = smtp_from
  38. msg['To'] = email
  39. # Plain text
  40. msg.attach(MIMEText(body, 'plain', 'utf-8'))
  41. # HTML (markdown-like)
  42. html_body = body.replace('\n', '<br>').replace('**', '<b>').replace('</b><b>', '')
  43. msg.attach(MIMEText(f"<html><body style='font-family:sans-serif'>{html_body}</body></html>", 'html', 'utf-8'))
  44. with _smtp_connect(smtp_host, smtp_port, smtp_user, smtp_pass) as server:
  45. server.send_message(msg)
  46. return {**event, 'notify': 'sent'}
  47. def _smtp_connect(host, port, user, passwd):
  48. """465 用 SMTP_SSL (隐式 TLS), 587 用 SMTP + STARTTLS"""
  49. if port == 465:
  50. server = smtplib.SMTP_SSL(host, port)
  51. else:
  52. server = smtplib.SMTP(host, port)
  53. server.starttls()
  54. server.login(user, passwd)
  55. return server