ext_mail.py 2.9 KB

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