ext_mail.py 1.9 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 not api_url:
  20. raise ValueError('RESEND_API_URL is not set')
  21. resend.api_url = api_url
  22. resend.api_key = api_key
  23. self._client = resend.Emails
  24. else:
  25. raise ValueError('Unsupported mail type {}'.format(app.config.get('MAIL_TYPE')))
  26. def send(self, to: str, subject: str, html: str, from_: Optional[str] = None):
  27. if not self._client:
  28. raise ValueError('Mail client is not initialized')
  29. if not from_ and self._default_send_from:
  30. from_ = self._default_send_from
  31. if not from_:
  32. raise ValueError('mail from is not set')
  33. if not to:
  34. raise ValueError('mail to is not set')
  35. if not subject:
  36. raise ValueError('mail subject is not set')
  37. if not html:
  38. raise ValueError('mail html is not set')
  39. self._client.send({
  40. "from": from_,
  41. "to": to,
  42. "subject": subject,
  43. "html": html
  44. })
  45. def init_app(app: Flask):
  46. mail.init_app(app)
  47. mail = Mail()