ext_mail.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. from typing import Optional
  2. import resend
  3. from flask import Flask
  4. class Mail:
  5. def __init__(self):
  6. self._client = None
  7. self._default_send_from = None
  8. def is_inited(self) -> bool:
  9. return self._client is not None
  10. def init_app(self, app: Flask):
  11. if app.config.get('MAIL_TYPE'):
  12. if app.config.get('MAIL_DEFAULT_SEND_FROM'):
  13. self._default_send_from = app.config.get('MAIL_DEFAULT_SEND_FROM')
  14. if app.config.get('MAIL_TYPE') == 'resend':
  15. api_key = app.config.get('RESEND_API_KEY')
  16. if not api_key:
  17. raise ValueError('RESEND_API_KEY is not set')
  18. api_url = app.config.get('RESEND_API_URL')
  19. if api_url:
  20. resend.api_url = api_url
  21. resend.api_key = api_key
  22. self._client = resend.Emails
  23. else:
  24. raise ValueError('Unsupported mail type {}'.format(app.config.get('MAIL_TYPE')))
  25. def send(self, to: str, subject: str, html: str, from_: Optional[str] = None):
  26. if not self._client:
  27. raise ValueError('Mail client is not initialized')
  28. if not from_ and self._default_send_from:
  29. from_ = self._default_send_from
  30. if not from_:
  31. raise ValueError('mail from is not set')
  32. if not to:
  33. raise ValueError('mail to is not set')
  34. if not subject:
  35. raise ValueError('mail subject is not set')
  36. if not html:
  37. raise ValueError('mail html is not set')
  38. self._client.send({
  39. "from": from_,
  40. "to": to,
  41. "subject": subject,
  42. "html": html
  43. })
  44. def init_app(app: Flask):
  45. mail.init_app(app)
  46. mail = Mail()