ext_mail.py 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import logging
  2. from typing import Optional
  3. from flask import Flask
  4. from configs import dify_config
  5. from dify_app import DifyApp
  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. import resend # type: ignore
  22. api_key = dify_config.RESEND_API_KEY
  23. if not api_key:
  24. raise ValueError("RESEND_API_KEY is not set")
  25. api_url = dify_config.RESEND_API_URL
  26. if api_url:
  27. resend.api_url = api_url
  28. resend.api_key = api_key
  29. self._client = resend.Emails
  30. case "smtp":
  31. from libs.smtp import SMTPClient
  32. if not dify_config.SMTP_SERVER or not dify_config.SMTP_PORT:
  33. raise ValueError("SMTP_SERVER and SMTP_PORT are required for smtp mail type")
  34. if not dify_config.SMTP_USE_TLS and dify_config.SMTP_OPPORTUNISTIC_TLS:
  35. raise ValueError("SMTP_OPPORTUNISTIC_TLS is not supported without enabling SMTP_USE_TLS")
  36. self._client = SMTPClient(
  37. server=dify_config.SMTP_SERVER,
  38. port=dify_config.SMTP_PORT,
  39. username=dify_config.SMTP_USERNAME or "",
  40. password=dify_config.SMTP_PASSWORD or "",
  41. _from=dify_config.MAIL_DEFAULT_SEND_FROM or "",
  42. use_tls=dify_config.SMTP_USE_TLS,
  43. opportunistic_tls=dify_config.SMTP_OPPORTUNISTIC_TLS,
  44. )
  45. case _:
  46. raise ValueError("Unsupported mail type {}".format(mail_type))
  47. def send(self, to: str, subject: str, html: str, from_: Optional[str] = None):
  48. if not self._client:
  49. raise ValueError("Mail client is not initialized")
  50. if not from_ and self._default_send_from:
  51. from_ = self._default_send_from
  52. if not from_:
  53. raise ValueError("mail from is not set")
  54. if not to:
  55. raise ValueError("mail to is not set")
  56. if not subject:
  57. raise ValueError("mail subject is not set")
  58. if not html:
  59. raise ValueError("mail html is not set")
  60. self._client.send(
  61. {
  62. "from": from_,
  63. "to": to,
  64. "subject": subject,
  65. "html": html,
  66. }
  67. )
  68. def is_enabled() -> bool:
  69. return dify_config.MAIL_TYPE is not None and dify_config.MAIL_TYPE != ""
  70. def init_app(app: DifyApp):
  71. mail.init_app(app)
  72. mail = Mail()