Use context manager for SMTP
This commit is contained in:
@@ -76,11 +76,10 @@ class EmailService:
|
|||||||
smtp_host = self.config["smtp_host"]
|
smtp_host = self.config["smtp_host"]
|
||||||
smtp_port = self.config["smtp_port"]
|
smtp_port = self.config["smtp_port"]
|
||||||
|
|
||||||
server = smtplib.SMTP(smtp_host, smtp_port)
|
with smtplib.SMTP(smtp_host, smtp_port) as server:
|
||||||
if self.config.get("smtp_starttls", False):
|
if self.config.get("smtp_starttls", False):
|
||||||
server.starttls()
|
server.starttls()
|
||||||
|
|
||||||
try:
|
|
||||||
if self.config.get("smtp_user"):
|
if self.config.get("smtp_user"):
|
||||||
server.login(
|
server.login(
|
||||||
self.config["smtp_user"],
|
self.config["smtp_user"],
|
||||||
@@ -89,8 +88,6 @@ class EmailService:
|
|||||||
server.sendmail(msg["From"], [to], msg.as_string())
|
server.sendmail(msg["From"], [to], msg.as_string())
|
||||||
logging.info(f"Email sent: to={to} subject={subject}")
|
logging.info(f"Email sent: to={to} subject={subject}")
|
||||||
return True
|
return True
|
||||||
finally:
|
|
||||||
server.quit()
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logging.error(f"Email send failed: to={to} error={e}")
|
logging.error(f"Email send failed: to={to} error={e}")
|
||||||
|
|||||||
Reference in New Issue
Block a user