Spaces:
Sleeping
Sleeping
Download backend/app/services/email.py from axeronis/microfunnel-api: direct link, hf CLI and curl.
- Browser
- Download file 17.1 kB
-
https://huggingface.co/spaces/axeronis/microfunnel-api/resolve/main/backend/app/services/email.py
- Command line
-
hf download hf://spaces/axeronis/microfunnel-api/backend/app/services/email.py
-
curl -L -o email.py https://huggingface.co/spaces/axeronis/microfunnel-api/resolve/main/backend/app/services/email.py
17.1 kB
| """Email service for sending notifications.""" | |
| import aiosmtplib | |
| from email.mime.text import MIMEText | |
| from email.mime.multipart import MIMEMultipart | |
| from typing import List, Optional | |
| from app.core.config import settings | |
| from app.core.logging import get_logger | |
| logger = get_logger(__name__) | |
| class EmailService: | |
| """Service for sending emails via SMTP.""" | |
| def __init__(self): | |
| self.smtp_host = settings.SMTP_HOST | |
| self.smtp_port = settings.SMTP_PORT | |
| self.smtp_user = settings.SMTP_USER | |
| self.smtp_password = settings.SMTP_PASSWORD | |
| self.from_email = settings.EMAIL_FROM | |
| async def send_email( | |
| self, | |
| to: List[str], | |
| subject: str, | |
| html_body: str, | |
| text_body: Optional[str] = None, | |
| in_reply_to: Optional[str] = None, | |
| references: Optional[str] = None | |
| ) -> bool: | |
| """ | |
| Send email using SMTP. | |
| Args: | |
| to: List of recipient email addresses | |
| subject: Email subject | |
| html_body: HTML email body | |
| text_body: Plain text email body (optional) | |
| Returns: | |
| True if sent successfully, False otherwise | |
| """ | |
| if settings.RESEND_API_KEY: | |
| return await self._send_via_resend(to, subject, html_body, text_body) | |
| if settings.BREVO_API_KEY: | |
| return await self._send_via_brevo(to, subject, html_body, text_body) | |
| if not self.smtp_host or not self.smtp_user: | |
| logger.warning("SMTP not configured, email not sent") | |
| return self._fallback_log(to, subject, text_body) | |
| try: | |
| # Create message | |
| message = MIMEMultipart("alternative") | |
| message["Subject"] = subject | |
| message["From"] = self.from_email | |
| message["To"] = ", ".join(to) | |
| if in_reply_to: | |
| message["In-Reply-To"] = in_reply_to | |
| if references: | |
| message["References"] = references | |
| # Add text and HTML parts | |
| if text_body: | |
| message.attach(MIMEText(text_body, "plain")) | |
| message.attach(MIMEText(html_body, "html")) | |
| # Send email | |
| # Determine TLS/STARTTLS based on port | |
| use_tls = self.smtp_port == 465 | |
| start_tls = self.smtp_port == 587 | |
| await aiosmtplib.send( | |
| message, | |
| hostname=self.smtp_host, | |
| port=self.smtp_port, | |
| username=self.smtp_user, | |
| password=self.smtp_password, | |
| use_tls=use_tls, | |
| start_tls=start_tls | |
| ) | |
| logger.info( | |
| "Email sent successfully (SMTP)", | |
| to=to, | |
| subject=subject | |
| ) | |
| return True | |
| except Exception as e: | |
| logger.error( | |
| "Failed to send email via SMTP. Falling back to CONSOLE LOG.", | |
| error=str(e) | |
| ) | |
| return self._fallback_log(to, subject, text_body) | |
| async def _send_via_resend( | |
| self, | |
| to: List[str], | |
| subject: str, | |
| html_body: str, | |
| text_body: Optional[str] = None | |
| ) -> bool: | |
| """Send email via Resend API (HTTP).""" | |
| import httpx | |
| async def try_send(from_addr: str): | |
| async with httpx.AsyncClient() as client: | |
| payload = { | |
| "from": from_addr, | |
| "to": to, | |
| "subject": subject, | |
| "html": html_body, | |
| "text": text_body | |
| } | |
| return await client.post( | |
| "https://api.resend.com/emails", | |
| headers={ | |
| "Authorization": f"Bearer {settings.RESEND_API_KEY}", | |
| "Content-Type": "application/json" | |
| }, | |
| json=payload | |
| ) | |
| try: | |
| # 1. Try with configured email | |
| from_addr = f"{settings.APP_NAME} <{self.from_email}>" | |
| response = await try_send(from_addr) | |
| # 2. If rejected (likely domain not verified), try onboarding@resend.dev | |
| if response.status_code in [403, 422]: | |
| logger.warning(f"Resend rejected sender '{from_addr}'. Retrying with 'onboarding@resend.dev'...") | |
| response = await try_send("onboarding@resend.dev") | |
| if response.status_code >= 400: | |
| logger.error(f"Resend API Error: {response.text}") | |
| return self._fallback_log(to, subject, text_body) | |
| logger.info("Email sent successfully (Resend API)", to=to, id=response.json().get("id")) | |
| return True | |
| except Exception as e: | |
| logger.error(f"Resend API unexpected error: {e}") | |
| return self._fallback_log(to, subject, text_body) | |
| async def _send_via_brevo( | |
| self, | |
| to: List[str], | |
| subject: str, | |
| html_body: str, | |
| text_body: Optional[str] = None | |
| ) -> bool: | |
| """Send email via Brevo API.""" | |
| import httpx | |
| try: | |
| async with httpx.AsyncClient() as client: | |
| payload = { | |
| "sender": {"email": self.from_email, "name": settings.APP_NAME}, | |
| "to": [{"email": email} for email in to], | |
| "subject": subject, | |
| "htmlContent": html_body | |
| } | |
| if text_body: | |
| payload["textContent"] = text_body | |
| response = await client.post( | |
| "https://api.brevo.com/v3/smtp/email", | |
| headers={ | |
| "api-key": settings.BREVO_API_KEY, | |
| "Content-Type": "application/json", | |
| "Accept": "application/json" | |
| }, | |
| json=payload | |
| ) | |
| if response.status_code in [200, 201, 202]: | |
| logger.info("Email sent via Brevo API", to=to) | |
| return True | |
| logger.error(f"Brevo API mismatch: {response.text}") | |
| return self._fallback_log(to, subject, text_body) | |
| except Exception as e: | |
| logger.error(f"Brevo API error: {e}") | |
| return self._fallback_log(to, subject, text_body) | |
| def _fallback_log(self, to, subject, text_body): | |
| # FALLBACK: Log the email content | |
| print("="*60) | |
| print(f"📧 EMAIL FALLBACK (To: {to})") | |
| print(f"Subject: {subject}") | |
| print("-" * 20) | |
| if text_body: | |
| print(text_body.strip()) | |
| else: | |
| print("(HTML Body hidden in logs)") | |
| print("="*60) | |
| return True | |
| async def send_hot_lead_notification( | |
| self, | |
| manager_email: str, | |
| lead_name: str, | |
| lead_id: str, | |
| heat_score: int, | |
| summary: dict | |
| ) -> bool: | |
| """ | |
| Send notification about hot lead to manager. | |
| """ | |
| subject = f"🔥 Hot Lead Alert: {lead_name} (Score: {heat_score})" | |
| # Build HTML body | |
| html_body = f""" | |
| <html> | |
| <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;"> | |
| <div style="max-width: 600px; margin: 0 auto; padding: 20px;"> | |
| <h2 style="color: #dc2626;">🔥 Hot Lead Alert</h2> | |
| <div style="background: #fef2f2; border-left: 4px solid #dc2626; padding: 15px; margin: 20px 0;"> | |
| <h3 style="margin: 0 0 10px 0;">{lead_name}</h3> | |
| <p style="margin: 5px 0;"><strong>Heat Score:</strong> {heat_score}/100</p> | |
| <p style="margin: 5px 0;"><strong>Lead ID:</strong> {lead_id}</p> | |
| </div> | |
| <h3>AI Summary</h3> | |
| <ul style="background: #f9fafb; padding: 20px; border-radius: 8px;"> | |
| <li><strong>Intent:</strong> {summary.get('intent', 'N/A')}</li> | |
| <li><strong>Budget:</strong> {summary.get('budget', 'N/A')}</li> | |
| <li><strong>Timeline:</strong> {summary.get('timeline', 'N/A')}</li> | |
| <li><strong>Authority:</strong> {summary.get('authority', 'N/A')}</li> | |
| </ul> | |
| <h3>Pain Points</h3> | |
| <ul style="background: #fff7ed; padding: 20px; border-radius: 8px;"> | |
| {"".join(f"<li>{point}</li>" for point in summary.get('pain_points', []))} | |
| </ul> | |
| <h3>Recommendation</h3> | |
| <div style="background: #ecfdf5; padding: 15px; border-radius: 8px; border-left: 4px solid #10b981;"> | |
| <p>{summary.get('recommendation', 'Follow up immediately')}</p> | |
| </div> | |
| <div style="margin-top: 30px; padding-top: 20px; border-top: 1px solid #e5e7eb;"> | |
| <p style="color: #6b7280; font-size: 14px;"> | |
| This is an automated notification from {settings.APP_NAME}. | |
| <br> | |
| Please respond to this lead as soon as possible. | |
| </p> | |
| </div> | |
| </div> | |
| </body> | |
| </html> | |
| """ | |
| # Plain text fallback | |
| text_body = f""" | |
| 🔥 Hot Lead Alert | |
| Lead: {lead_name} | |
| Heat Score: {heat_score}/100 | |
| Lead ID: {lead_id} | |
| AI Summary: | |
| - Intent: {summary.get('intent', 'N/A')} | |
| - Budget: {summary.get('budget', 'N/A')} | |
| - Timeline: {summary.get('timeline', 'N/A')} | |
| - Authority: {summary.get('authority', 'N/A')} | |
| Recommendation: {summary.get('recommendation', 'Follow up immediately')} | |
| Please respond to this lead as soon as possible. | |
| """ | |
| return await self.send_email( | |
| to=[manager_email], | |
| subject=subject, | |
| html_body=html_body, | |
| text_body=text_body | |
| ) | |
| async def send_verification_email(self, to_email: str, code: str) -> bool: | |
| """Send email verification code.""" | |
| subject = f"Verify your email - {settings.APP_NAME}" | |
| html_body = f""" | |
| <html> | |
| <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;"> | |
| <div style="max-width: 600px; margin: 0 auto; padding: 20px;"> | |
| <h2 style="color: #2563eb;">Verify your email</h2> | |
| <p>Thanks for signing up for {settings.APP_NAME}! Please use the following code to verify your email address:</p> | |
| <div style="background: #eff6ff; border-left: 4px solid #2563eb; padding: 15px; margin: 20px 0;"> | |
| <h1 style="margin: 0; letter-spacing: 5px; color: #1e40af;">{code}</h1> | |
| </div> | |
| <p>This code will expire in 10 minutes.</p> | |
| <p>If you didn't create an account, you can ignore this email.</p> | |
| </div> | |
| </body> | |
| </html> | |
| """ | |
| text_body = f""" | |
| Verify your email | |
| Code: {code} | |
| This code will expire in 10 minutes. | |
| """ | |
| return await self.send_email( | |
| to=[to_email], | |
| subject=subject, | |
| html_body=html_body, | |
| text_body=text_body | |
| ) | |
| async def send_password_reset_email(self, to_email: str, code: str) -> bool: | |
| """Send password reset code.""" | |
| subject = f"Reset your password - {settings.APP_NAME}" | |
| html_body = f""" | |
| <html> | |
| <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;"> | |
| <div style="max-width: 600px; margin: 0 auto; padding: 20px;"> | |
| <h2 style="color: #2563eb;">Reset your password</h2> | |
| <p>We received a request to reset your password. Use the code below to proceed:</p> | |
| <div style="background: #eff6ff; border-left: 4px solid #2563eb; padding: 15px; margin: 20px 0;"> | |
| <h1 style="margin: 0; letter-spacing: 5px; color: #1e40af;">{code}</h1> | |
| </div> | |
| <p>This code will expire in 10 minutes.</p> | |
| <p>If you didn't request a password reset, you can ignore this email.</p> | |
| </div> | |
| </body> | |
| </html> | |
| """ | |
| text_body = f""" | |
| Reset your password | |
| Code: {code} | |
| This code will expire in 10 minutes. | |
| """ | |
| return await self.send_email( | |
| to=[to_email], | |
| subject=subject, | |
| html_body=html_body, | |
| text_body=text_body | |
| ) | |
| async def send_subscription_expiry_warning( | |
| self, | |
| to_email: str, | |
| company_name: str, | |
| days_remaining: int, | |
| plan_name: str | |
| ) -> bool: | |
| """Send subscription expiry warning email.""" | |
| subject = f"⚠️ Подписка истекает через {days_remaining} дн. - {settings.APP_NAME}" | |
| html_body = f""" | |
| <html> | |
| <body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333; background: #f8fafc;"> | |
| <div style="max-width: 600px; margin: 0 auto; padding: 20px;"> | |
| <div style="background: white; border-radius: 12px; padding: 30px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);"> | |
| <h2 style="color: #f59e0b; margin-top: 0;">⚠️ Подписка скоро истекает</h2> | |
| <p>Здравствуйте!</p> | |
| <p>Ваша подписка на план <strong>{plan_name.upper()}</strong> для компании <strong>{company_name}</strong> истекает через <strong>{days_remaining} дн.</strong></p> | |
| <div style="background: #fef3c7; border-left: 4px solid #f59e0b; padding: 15px; margin: 20px 0; border-radius: 0 8px 8px 0;"> | |
| <p style="margin: 0;">После истечения подписки:</p> | |
| <ul style="margin: 10px 0 0 0; padding-left: 20px;"> | |
| <li>AI-бот перестанет отвечать на сообщения</li> | |
| <li>Новые диалоги не будут создаваться</li> | |
| <li>Все ваши данные сохранятся</li> | |
| </ul> | |
| </div> | |
| <p>Продлите подписку сейчас, чтобы не терять клиентов!</p> | |
| <a href="https://microfunnel.online/settings/billing" style="display: inline-block; background: linear-gradient(135deg, #6366f1, #8b5cf6); color: white; padding: 12px 24px; border-radius: 8px; text-decoration: none; font-weight: bold; margin: 15px 0;"> | |
| Продлить подписку | |
| </a> | |
| <p style="color: #6b7280; font-size: 14px; margin-top: 30px; border-top: 1px solid #e5e7eb; padding-top: 20px;"> | |
| С уважением,<br> | |
| Команда {settings.APP_NAME} | |
| </p> | |
| </div> | |
| </div> | |
| </body> | |
| </html> | |
| """ | |
| text_body = f""" | |
| ⚠️ Подписка скоро истекает | |
| Ваша подписка на план {plan_name.upper()} для компании {company_name} истекает через {days_remaining} дн. | |
| После истечения подписки: | |
| - AI-бот перестанет отвечать на сообщения | |
| - Новые диалоги не будут создаваться | |
| - Все ваши данные сохранятся | |
| Продлите подписку: https://microfunnel.online/settings/billing | |
| """ | |
| return await self.send_email( | |
| to=[to_email], | |
| subject=subject, | |
| html_body=html_body, | |
| text_body=text_body | |
| ) | |
| # Singleton instance | |
| _email_service = None | |
| def get_email_service() -> EmailService: | |
| """Get email service singleton instance.""" | |
| global _email_service | |
| if _email_service is None: | |
| _email_service = EmailService() | |
| return _email_service | |
| email_service = get_email_service() | |