ext_mail.py 1.6 KB

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