|
| 1 | +import smtplib |
| 2 | +import os |
| 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 | +from typing import List, Optional |
| 8 | + |
| 9 | +def send_email_with_attachments(to_email: str, subject: str, body: str, attachments: Optional[List[str]] = None) -> bool: |
| 10 | + smtp_server = os.getenv("SMTP_SERVER") |
| 11 | + smtp_port = int(os.getenv("SMTP_PORT", "587")) |
| 12 | + smtp_user = os.getenv("SMTP_USER") |
| 13 | + smtp_pass = os.getenv("SMTP_PASS") |
| 14 | + from_email = os.getenv("EMAIL_FROM", smtp_user) |
| 15 | + if not (smtp_server and smtp_user and smtp_pass and to_email): |
| 16 | + raise ValueError("Missing SMTP configuration or recipient email") |
| 17 | + |
| 18 | + msg = MIMEMultipart() |
| 19 | + msg['From'] = from_email |
| 20 | + msg['To'] = to_email |
| 21 | + msg['Subject'] = subject |
| 22 | + msg.attach(MIMEText(body, 'plain')) |
| 23 | + |
| 24 | + if attachments: |
| 25 | + for path in attachments: |
| 26 | + part = MIMEBase('application', 'octet-stream') |
| 27 | + with open(path, 'rb') as f: |
| 28 | + part.set_payload(f.read()) |
| 29 | + encoders.encode_base64(part) |
| 30 | + part.add_header('Content-Disposition', f'attachment; filename="{os.path.basename(path)}"') |
| 31 | + msg.attach(part) |
| 32 | + |
| 33 | + with smtplib.SMTP(smtp_server, smtp_port) as server: |
| 34 | + server.starttls() |
| 35 | + server.login(smtp_user, smtp_pass) |
| 36 | + server.send_message(msg) |
| 37 | + return True |
0 commit comments