Spaces:
Sleeping
Sleeping
| """ | |
| Email file generation for dev flow. | |
| Saves emails as .eml files that can be opened with any email client. | |
| """ | |
| import os | |
| from datetime import datetime | |
| from email.mime.multipart import MIMEMultipart | |
| from email.mime.text import MIMEText | |
| from logger import logger | |
| from config import ( | |
| EMAIL_SENDER, | |
| DEV_EMAIL_RECIPIENT, | |
| EMAIL_OUTPUT_DIR, | |
| ) | |
| class EmailHandler: | |
| """Handles email generation and file saving.""" | |
| def __init__( | |
| self, | |
| sender=EMAIL_SENDER, | |
| output_dir=EMAIL_OUTPUT_DIR, | |
| ): | |
| """ | |
| Initialize email handler. | |
| Args: | |
| sender (str): Sender email address | |
| output_dir (str): Directory to save email files | |
| """ | |
| if not sender: | |
| raise ValueError("Email sender not configured") | |
| self.sender = sender | |
| self.output_dir = output_dir | |
| os.makedirs(self.output_dir, exist_ok=True) | |
| logger.debug("EmailHandler initialized") | |
| def save_html_email(self, recipient, subject, html_content, text_content=None): | |
| """ | |
| Save HTML email as .eml file. | |
| Args: | |
| recipient (str): Recipient email address | |
| subject (str): Email subject | |
| html_content (str): HTML content | |
| text_content (str, optional): Plain text fallback | |
| Returns: | |
| str: Path to saved .eml file | |
| Raises: | |
| Exception: If file saving fails | |
| """ | |
| try: | |
| logger.info(f"Preparing email to {recipient}...") | |
| # Create message | |
| msg = MIMEMultipart("alternative") | |
| msg["Subject"] = subject | |
| msg["From"] = self.sender | |
| msg["To"] = recipient | |
| msg["Date"] = datetime.now().strftime("%a, %d %b %Y %H:%M:%S +0000") | |
| # Add text part | |
| if text_content: | |
| msg.attach(MIMEText(text_content, "plain")) | |
| # Add HTML part | |
| msg.attach(MIMEText(html_content, "html")) | |
| # Generate filename | |
| timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") | |
| filename = f"email_{timestamp}.eml" | |
| file_path = os.path.join(self.output_dir, filename) | |
| # Save email file | |
| with open(file_path, "w", encoding="utf-8") as f: | |
| f.write(msg.as_string()) | |
| logger.info(f"✓ Email saved to {file_path}") | |
| return file_path | |
| except Exception as e: | |
| logger.error(f"Failed to save email: {e}") | |
| raise | |
| def save_article_email(self, recipient, article_title, html_content): | |
| """ | |
| Save article email with formatted subject as .eml file. | |
| Args: | |
| recipient (str): Recipient email address | |
| article_title (str): Title of the article | |
| html_content (str): HTML content | |
| Returns: | |
| str: Path to saved .eml file | |
| """ | |
| subject = f"New Article: {article_title}" | |
| text_content = f"Article: {article_title}\n\nOpen the attached HTML file to view the full content." | |
| return self.save_html_email(recipient, subject, html_content, text_content) | |