smtp.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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__(self, server: str, port: int, username: str, password: str, _from: str, use_tls=False):
  7. self.server = server
  8. self.port = port
  9. self._from = _from
  10. self.username = username
  11. self.password = password
  12. self._use_tls = use_tls
  13. def send(self, mail: dict):
  14. smtp = None
  15. try:
  16. smtp = smtplib.SMTP(self.server, self.port, timeout=10)
  17. if self._use_tls:
  18. smtp.starttls()
  19. if self.username and self.password:
  20. smtp.login(self.username, self.password)
  21. msg = MIMEMultipart()
  22. msg['Subject'] = mail['subject']
  23. msg['From'] = self._from
  24. msg['To'] = mail['to']
  25. msg.attach(MIMEText(mail['html'], 'html'))
  26. smtp.sendmail(self._from, mail['to'], msg.as_string())
  27. except smtplib.SMTPException as e:
  28. logging.error(f"SMTP error occurred: {str(e)}")
  29. raise
  30. except TimeoutError as e:
  31. logging.error(f"Timeout occurred while sending email: {str(e)}")
  32. raise
  33. except Exception as e:
  34. logging.error(f"Unexpected error occurred while sending email: {str(e)}")
  35. raise
  36. finally:
  37. if smtp:
  38. smtp.quit()