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