ext_mail.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import logging
  2. from typing import Optional
  3. import resend
  4. from flask import Flask
  5. from configs import dify_config
  6. class Mail:
  7. def __init__(self):
  8. self._client = None
  9. self._default_send_from = None
  10. def is_inited(self) -> bool:
  11. return self._client is not None
  12. def init_app(self, app: Flask):
  13. mail_type = dify_config.MAIL_TYPE
  14. if not mail_type:
  15. logging.warning("MAIL_TYPE is not set")
  16. return
  17. if dify_config.MAIL_DEFAULT_SEND_FROM:
  18. self._default_send_from = dify_config.MAIL_DEFAULT_SEND_FROM
  19. match mail_type:
  20. case "resend":
  21. api_key = dify_config.RESEND_API_KEY
  22. if not api_key:
  23. raise ValueError("RESEND_API_KEY is not set")
  24. api_url = dify_config.RESEND_API_URL
  25. if api_url:
  26. resend.api_url = api_url
  27. resend.api_key = api_key
  28. self._client = resend.Emails
  29. case "smtp":
  30. from libs.smtp import SMTPClient
  31. if not dify_config.SMTP_SERVER or not dify_config.SMTP_PORT:
  32. raise ValueError("SMTP_SERVER and SMTP_PORT are required for smtp mail type")
  33. if not dify_config.SMTP_USE_TLS and dify_config.SMTP_OPPORTUNISTIC_TLS:
  34. raise ValueError("SMTP_OPPORTUNISTIC_TLS is not supported without enabling SMTP_USE_TLS")
  35. self._client = SMTPClient(
  36. server=dify_config.SMTP_SERVER,
  37. port=dify_config.SMTP_PORT,
  38. username=dify_config.SMTP_USERNAME,
  39. password=dify_config.SMTP_PASSWORD,
  40. _from=dify_config.MAIL_DEFAULT_SEND_FROM,
  41. use_tls=dify_config.SMTP_USE_TLS,
  42. opportunistic_tls=dify_config.SMTP_OPPORTUNISTIC_TLS,
  43. )
  44. case _:
  45. raise ValueError("Unsupported mail type {}".format(mail_type))
  46. def send(self, to: str, subject: str, html: str, from_: Optional[str] = None):
  47. if not self._client:
  48. raise ValueError("Mail client is not initialized")
  49. if not from_ and self._default_send_from:
  50. from_ = self._default_send_from
  51. if not from_:
  52. raise ValueError("mail from is not set")
  53. if not to:
  54. raise ValueError("mail to is not set")
  55. if not subject:
  56. raise ValueError("mail subject is not set")
  57. if not html:
  58. raise ValueError("mail html is not set")
  59. self._client.send(
  60. {
  61. "from": from_,
  62. "to": to,
  63. "subject": subject,
  64. "html": html,
  65. }
  66. )
  67. def init_app(app: Flask):
  68. mail.init_app(app)
  69. mail = Mail()