smtp.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import logging
  2. import smtplib
  3. from email.mime.multipart import MIMEMultipart
  4. from email.mime.text import MIMEText
  5. class SMTPClient:
  6. def __init__(
  7. self, server: str, port: int, username: str, password: str, _from: str, use_tls=False, opportunistic_tls=False
  8. ):
  9. self.server = server
  10. self.port = port
  11. self._from = _from
  12. self.username = username
  13. self.password = password
  14. self.use_tls = use_tls
  15. self.opportunistic_tls = opportunistic_tls
  16. def send(self, mail: dict):
  17. smtp = None
  18. try:
  19. if self.use_tls:
  20. if self.opportunistic_tls:
  21. smtp = smtplib.SMTP(self.server, self.port, timeout=10)
  22. smtp.starttls()
  23. else:
  24. smtp = smtplib.SMTP_SSL(self.server, self.port, timeout=10)
  25. else:
  26. smtp = smtplib.SMTP(self.server, self.port, timeout=10)
  27. if self.username and self.password:
  28. smtp.login(self.username, self.password)
  29. msg = MIMEMultipart()
  30. msg["Subject"] = mail["subject"]
  31. msg["From"] = self._from
  32. msg["To"] = mail["to"]
  33. msg.attach(MIMEText(mail["html"], "html"))
  34. smtp.sendmail(self._from, mail["to"], msg.as_string())
  35. except smtplib.SMTPException as e:
  36. logging.exception(f"SMTP error occurred: {str(e)}")
  37. raise
  38. except TimeoutError as e:
  39. logging.exception(f"Timeout occurred while sending email: {str(e)}")
  40. raise
  41. except Exception as e:
  42. logging.exception(f"Unexpected error occurred while sending email: {str(e)}")
  43. raise
  44. finally:
  45. if smtp:
  46. smtp.quit()