updated email service

This commit is contained in:
berkay 2025-04-24 17:41:14 +03:00
parent 9511f81bc0
commit 0bd8ddce4d
1 changed files with 33 additions and 12 deletions

View File

@ -27,6 +27,13 @@ class EmailSession:
print("Email sending is disabled", params)
return False
receivers = [email_configs.USERNAME]
# Ensure connection is established before sending
try:
# Check if connection exists, if not establish it
if not hasattr(self.email_sender, '_connected') or not self.email_sender._connected:
self.email_sender.connect()
self.email_sender.send(
subject=params.subject,
receivers=receivers,
@ -38,6 +45,9 @@ class EmailSession:
attachments=params.attachments or {},
)
return True
except Exception as e:
print(f"Error sending email: {e}")
raise
class EmailService:
@ -54,14 +64,25 @@ class EmailService:
"""Create and yield a new email session with active connection."""
email_sender = EmailSender(**email_configs.as_dict())
session = EmailSession(email_sender)
connection_established = False
try:
# Establish connection and set flag
email_sender.connect()
# Set a flag to track connection state
email_sender._connected = True
connection_established = True
yield session
except Exception as e:
print(f"Error with email connection: {e}")
raise
finally:
# Only close if connection was successfully established
if connection_established:
try:
email_sender.close()
email_sender._connected = False
except Exception as e:
print(f"Error closing email connection: {e}")
@classmethod
def send_email(cls, session: EmailSession, params: EmailSendModel) -> bool: