Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

fix: add timeout to SMTPClient to prevent worker blocking (#4352)

Charles Zhou2eb468f88518
diff --git a/api/libs/smtp.py b/api/libs/smtp.py
index 30a795bd70a..f5735cbb2e2 100644
--- a/api/libs/smtp.py
+++ b/api/libs/smtp.py
@@ -1,3 +1,4 @@
+import logging
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
@@ -13,15 +14,30 @@ class SMTPClient:
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()