zaheer140 commited on
Commit
bdb3959
·
verified ·
1 Parent(s): 7baef39

Create email_service.py

Browse files
SuperAgent/app/services/email_service.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import smtplib
3
+ from email.mime.multipart import MIMEMultipart
4
+ from email.mime.text import MIMEText
5
+ from email.mime.base import MIMEBase
6
+ from email import encoders
7
+ import logging
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+ class EmailService:
12
+ def __init__(self):
13
+ self.smtp_host = os.getenv("SMTP_HOST")
14
+ self.smtp_port = os.getenv("SMTP_PORT")
15
+ self.smtp_user = os.getenv("SMTP_USER")
16
+ self.smtp_pass = os.getenv("SMTP_PASSWORD")
17
+ self.smtp_from = os.getenv("SMTP_FROM", "[EMAIL_ADDRESS]")
18
+
19
+ def send_report(self, recipient: str, subject: str, body_html: str, attachment_path: str = None) -> bool:
20
+ if not recipient:
21
+ logger.warning("Email recipient is empty. Skipping email delivery.")
22
+ return False
23
+
24
+ if not self.smtp_host or not self.smtp_user or not self.smtp_pass:
25
+ logger.warning("SMTP credentials are not configured in environment. Printing email to console (MOCK).")
26
+ print(f"\n================ MOCK EMAIL SENT ================")
27
+ print(f"To: {recipient}")
28
+ print(f"From: {self.smtp_from}")
29
+ print(f"Subject: {subject}")
30
+ print(f"Body: {body_html[:300]}...")
31
+ if attachment_path:
32
+ print(f"Attachment: {os.path.basename(attachment_path)}")
33
+ print(f"=================================================\n")
34
+ return True
35
+
36
+ try:
37
+ # Create message container
38
+ msg = MIMEMultipart()
39
+ msg['From'] = self.smtp_from
40
+ msg['To'] = recipient
41
+ msg['Subject'] = subject
42
+
43
+ # Record the MIME types of both parts - text/html
44
+ msg.attach(MIMEText(body_html, 'html'))
45
+
46
+ # Attach PDF if provided
47
+ if attachment_path and os.path.exists(attachment_path):
48
+ filename = os.path.basename(attachment_path)
49
+ with open(attachment_path, "rb") as attachment:
50
+ part = MIMEBase("application", "octet-stream")
51
+ part.set_payload(attachment.read())
52
+ encoders.encode_base64(part)
53
+ part.add_header(
54
+ "Content-Disposition",
55
+ f"attachment; filename={filename}",
56
+ )
57
+ msg.attach(part)
58
+
59
+ # Connect to SMTP server
60
+ port = int(self.smtp_port) if self.smtp_port else 587
61
+ server = smtplib.SMTP(self.smtp_host, port)
62
+ server.starttls()
63
+ server.login(self.smtp_user, self.smtp_pass)
64
+
65
+ # Send email
66
+ server.sendmail(self.smtp_from, recipient, msg.as_string())
67
+ server.quit()
68
+
69
+ logger.info(f"Email sent successfully to {recipient}")
70
+ return True
71
+
72
+ except Exception as e:
73
+ logger.error(f"Failed to send email to {recipient}: {str(e)}")
74
+ return False
75
+
76
+ email_service = EmailService()