You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. # Send EHLO command with the HELO domain name as the server address
  23. smtp.ehlo(self.server)
  24. smtp.starttls()
  25. # Resend EHLO command to identify the TLS session
  26. smtp.ehlo(self.server)
  27. else:
  28. smtp = smtplib.SMTP_SSL(self.server, self.port, timeout=10)
  29. else:
  30. smtp = smtplib.SMTP(self.server, self.port, timeout=10)
  31. # Only authenticate if both username and password are non-empty
  32. if self.username and self.password and self.username.strip() and self.password.strip():
  33. smtp.login(self.username, self.password)
  34. msg = MIMEMultipart()
  35. msg["Subject"] = mail["subject"]
  36. msg["From"] = self._from
  37. msg["To"] = mail["to"]
  38. msg.attach(MIMEText(mail["html"], "html"))
  39. smtp.sendmail(self._from, mail["to"], msg.as_string())
  40. except smtplib.SMTPException as e:
  41. logging.exception("SMTP error occurred")
  42. raise
  43. except TimeoutError as e:
  44. logging.exception("Timeout occurred while sending email")
  45. raise
  46. except Exception as e:
  47. logging.exception(f"Unexpected error occurred while sending email to {mail['to']}")
  48. raise
  49. finally:
  50. if smtp:
  51. smtp.quit()