smtp.py 1.7 KB

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