ext_mail.py 2.5 KB

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