ext_mail.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import logging
  2. from typing import Optional
  3. import resend
  4. from flask import Flask
  5. class Mail:
  6. def __init__(self):
  7. self._client = None
  8. self._default_send_from = None
  9. def is_inited(self) -> bool:
  10. return self._client is not None
  11. def init_app(self, app: Flask):
  12. if app.config.get('MAIL_TYPE'):
  13. if app.config.get('MAIL_DEFAULT_SEND_FROM'):
  14. self._default_send_from = app.config.get('MAIL_DEFAULT_SEND_FROM')
  15. if app.config.get('MAIL_TYPE') == 'resend':
  16. api_key = app.config.get('RESEND_API_KEY')
  17. if not api_key:
  18. raise ValueError('RESEND_API_KEY is not set')
  19. api_url = app.config.get('RESEND_API_URL')
  20. if api_url:
  21. resend.api_url = api_url
  22. resend.api_key = api_key
  23. self._client = resend.Emails
  24. elif app.config.get('MAIL_TYPE') == 'smtp':
  25. from libs.smtp import SMTPClient
  26. if not app.config.get('SMTP_SERVER') or not app.config.get('SMTP_PORT'):
  27. raise ValueError('SMTP_SERVER and SMTP_PORT are required for smtp mail type')
  28. self._client = SMTPClient(
  29. server=app.config.get('SMTP_SERVER'),
  30. port=app.config.get('SMTP_PORT'),
  31. username=app.config.get('SMTP_USERNAME'),
  32. password=app.config.get('SMTP_PASSWORD'),
  33. _from=app.config.get('MAIL_DEFAULT_SEND_FROM'),
  34. use_tls=app.config.get('SMTP_USE_TLS')
  35. )
  36. else:
  37. raise ValueError('Unsupported mail type {}'.format(app.config.get('MAIL_TYPE')))
  38. else:
  39. logging.warning('MAIL_TYPE is not set')
  40. def send(self, to: str, subject: str, html: str, from_: Optional[str] = None):
  41. if not self._client:
  42. raise ValueError('Mail client is not initialized')
  43. if not from_ and self._default_send_from:
  44. from_ = self._default_send_from
  45. if not from_:
  46. raise ValueError('mail from is not set')
  47. if not to:
  48. raise ValueError('mail to is not set')
  49. if not subject:
  50. raise ValueError('mail subject is not set')
  51. if not html:
  52. raise ValueError('mail html is not set')
  53. self._client.send({
  54. "from": from_,
  55. "to": to,
  56. "subject": subject,
  57. "html": html
  58. })
  59. def init_app(app: Flask):
  60. mail.init_app(app)
  61. mail = Mail()