Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

smtp.py 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import logging
  2. import smtplib
  3. from email.mime.multipart import MIMEMultipart
  4. from email.mime.text import MIMEText
  5. logger = logging.getLogger(__name__)
  6. class SMTPClient:
  7. def __init__(
  8. self, server: str, port: int, username: str, password: str, _from: str, use_tls=False, opportunistic_tls=False
  9. ):
  10. self.server = server
  11. self.port = port
  12. self._from = _from
  13. self.username = username
  14. self.password = password
  15. self.use_tls = use_tls
  16. self.opportunistic_tls = opportunistic_tls
  17. def send(self, mail: dict):
  18. smtp = None
  19. try:
  20. if self.use_tls:
  21. if self.opportunistic_tls:
  22. smtp = smtplib.SMTP(self.server, self.port, timeout=10)
  23. # Send EHLO command with the HELO domain name as the server address
  24. smtp.ehlo(self.server)
  25. smtp.starttls()
  26. # Resend EHLO command to identify the TLS session
  27. smtp.ehlo(self.server)
  28. else:
  29. smtp = smtplib.SMTP_SSL(self.server, self.port, timeout=10)
  30. else:
  31. smtp = smtplib.SMTP(self.server, self.port, timeout=10)
  32. # Only authenticate if both username and password are non-empty
  33. if self.username and self.password and self.username.strip() and self.password.strip():
  34. smtp.login(self.username, self.password)
  35. msg = MIMEMultipart()
  36. msg["Subject"] = mail["subject"]
  37. msg["From"] = self._from
  38. msg["To"] = mail["to"]
  39. msg.attach(MIMEText(mail["html"], "html"))
  40. smtp.sendmail(self._from, mail["to"], msg.as_string())
  41. except smtplib.SMTPException as e:
  42. logger.exception("SMTP error occurred")
  43. raise
  44. except TimeoutError as e:
  45. logger.exception("Timeout occurred while sending email")
  46. raise
  47. except Exception as e:
  48. logger.exception("Unexpected error occurred while sending email to %s", mail["to"])
  49. raise
  50. finally:
  51. if smtp:
  52. smtp.quit()