-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathemail_tool.py
More file actions
56 lines (47 loc) · 1.69 KB
/
Copy pathemail_tool.py
File metadata and controls
56 lines (47 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import smtplib
import logging
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from config import SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASSWORD, EMAIL_FROM
def send_email(
subject: str,
body: str,
recipients: str,
cc: str = "",
html: bool = False
) -> str:
"""
Sends an email via SMTP.
Args:
subject: Email subject line
body: Email body (plain text or HTML)
recipients: Comma-separated To addresses
cc: Comma-separated CC addresses (optional)
html: If True, sends body as HTML. Default is plain text.
Returns:
Success or error message string.
"""
content_type = "html" if html else "plain"
try:
msg = MIMEMultipart()
msg["From"] = EMAIL_FROM
msg["To"] = recipients
if cc:
msg["Cc"] = cc
msg["Subject"] = subject
msg.attach(MIMEText(body, content_type))
all_recipients = [r.strip() for r in recipients.split(",") if r.strip()]
if cc:
all_recipients += [r.strip() for r in cc.split(",") if r.strip()]
with smtplib.SMTP(SMTP_HOST, SMTP_PORT) as server:
server.ehlo()
server.starttls()
server.login(SMTP_USER, SMTP_PASSWORD)
server.sendmail(EMAIL_FROM, all_recipients, msg.as_string())
result = f"Email sent to {recipients}" + (f", CC {cc}" if cc else "")
logging.info(f"[EMAIL] SUCCESS | to={recipients} | subject={subject}")
return result
except Exception as e:
error = f"ERROR sending email: {e}"
logging.error(f"[EMAIL] FAILED | to={recipients} | subject={subject} | error={e}")
return error