ext_mail.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. elif app.config.get('MAIL_TYPE') == 'smtp':
  24. from libs.smtp import SMTPClient
  25. if not app.config.get('SMTP_SERVER') or not app.config.get('SMTP_PORT'):
  26. raise ValueError('SMTP_SERVER and SMTP_PORT are required for smtp mail type')
  27. if not app.config.get('SMTP_USERNAME') or not app.config.get('SMTP_PASSWORD'):
  28. raise ValueError('SMTP_USERNAME and SMTP_PASSWORD are required for smtp mail type')
  29. self._client = SMTPClient(
  30. server=app.config.get('SMTP_SERVER'),
  31. port=app.config.get('SMTP_PORT'),
  32. username=app.config.get('SMTP_USERNAME'),
  33. password=app.config.get('SMTP_PASSWORD'),
  34. _from=app.config.get('MAIL_DEFAULT_SEND_FROM'),
  35. use_tls=app.config.get('SMTP_USE_TLS')
  36. )
  37. else:
  38. raise ValueError('Unsupported mail type {}'.format(app.config.get('MAIL_TYPE')))
  39. def send(self, to: str, subject: str, html: str, from_: Optional[str] = None):
  40. if not self._client:
  41. raise ValueError('Mail client is not initialized')
  42. if not from_ and self._default_send_from:
  43. from_ = self._default_send_from
  44. if not from_:
  45. raise ValueError('mail from is not set')
  46. if not to:
  47. raise ValueError('mail to is not set')
  48. if not subject:
  49. raise ValueError('mail subject is not set')
  50. if not html:
  51. raise ValueError('mail html is not set')
  52. self._client.send({
  53. "from": from_,
  54. "to": to,
  55. "subject": subject,
  56. "html": html
  57. })
  58. def init_app(app: Flask):
  59. mail.init_app(app)
  60. mail = Mail()