send.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. from email.mime.text import MIMEText
  2. import logging
  3. import smtplib
  4. from .wechat import WeChat
  5. class Sender:
  6. def __init__(self, smtp_options=None, wechat_options=None) -> None:
  7. self.smtp = None
  8. self.wechat = None
  9. if smtp_options:
  10. try:
  11. self.__init_smtp(**smtp_options)
  12. except Exception as e:
  13. logging.exception('smtp login failed', exc_info=e)
  14. if wechat_options:
  15. try:
  16. self.wechat = WeChat(**wechat_options)
  17. except Exception as e:
  18. logging.exception('wechat login failed', exc_info=e)
  19. def __init_smtp(self, server, port, user, password, sender):
  20. self.smtp = smtplib.SMTP_SSL(server, port)
  21. self.smtp.login(user, password)
  22. self.smtp_from = sender
  23. logging.info('smtp login successful')
  24. def send_mail(self, to, text, subject=None):
  25. if not self.smtp: return
  26. msg = MIMEText(text, 'plain', 'utf-8')
  27. if subject:
  28. msg['Subject'] = subject
  29. msg['From'] = self.smtp_from
  30. msg['To'] = to
  31. try:
  32. self.smtp.sendmail(self.smtp.user, to, msg.as_bytes())
  33. logging.info('send mail successful')
  34. except Exception as e:
  35. logging.exception('send mail failed', exc_info=e)
  36. def send_wechat(self, touser, msg):
  37. if not self.wechat: return
  38. try:
  39. self.wechat.send(touser, msg)
  40. logging.info('send wechat successful')
  41. except Exception as e:
  42. logging.exception('send wechat failed', exc_info=e)
  43. def send(self, msg, subject=None, mail=None, wechat=None, phone=None):
  44. if mail:
  45. self.send_mail(mail, msg, subject)
  46. if wechat:
  47. self.send_wechat(wechat, msg)