Skip to content

Commit

Permalink
fix: add timeout to SMTPClient to prevent worker blocking (langgenius…
Browse files Browse the repository at this point in the history
  • Loading branch information
chazzhou authored May 14, 2024
1 parent 98140ae commit 2eb468f
Showing 1 changed file with 28 additions and 12 deletions.
40 changes: 28 additions & 12 deletions api/libs/smtp.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import logging
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
Expand All @@ -13,15 +14,30 @@ def __init__(self, server: str, port: int, username: str, password: str, _from:
self._use_tls = use_tls

def send(self, mail: dict):
smtp = smtplib.SMTP(self.server, self.port)
if self._use_tls:
smtp.starttls()
if self.username and self.password:
smtp.login(self.username, self.password)
msg = MIMEMultipart()
msg['Subject'] = mail['subject']
msg['From'] = self._from
msg['To'] = mail['to']
msg.attach(MIMEText(mail['html'], 'html'))
smtp.sendmail(self.username, mail['to'], msg.as_string())
smtp.quit()
smtp = None
try:
smtp = smtplib.SMTP(self.server, self.port, timeout=10)
if self._use_tls:
smtp.starttls()
if self.username and self.password:
smtp.login(self.username, self.password)

msg = MIMEMultipart()
msg['Subject'] = mail['subject']
msg['From'] = self._from
msg['To'] = mail['to']
msg.attach(MIMEText(mail['html'], 'html'))

smtp.sendmail(self._from, mail['to'], msg.as_string())
except smtplib.SMTPException as e:
logging.error(f"SMTP error occurred: {str(e)}")
raise
except TimeoutError as e:
logging.error(f"Timeout occurred while sending email: {str(e)}")
raise
except Exception as e:
logging.error(f"Unexpected error occurred while sending email: {str(e)}")
raise
finally:
if smtp:
smtp.quit()

0 comments on commit 2eb468f

Please sign in to comment.