Spaces:
Sleeping

axeronis commited on
Commit
4906dec
·
1 Parent(s): c948380

Backend: Add Resend API integration for reliable email delivery

Browse files
backend/app/core/config.py CHANGED
@@ -79,6 +79,9 @@ class Settings(BaseSettings):
79
  SMTP_USER: Optional[str] = "microfunnel@yandex.kg"
80
  SMTP_PASSWORD: Optional[str] = "usjqasaddkqrrauv"
81
  EMAIL_FROM: str = "microfunnel@yandex.kg"
 
 
 
82
 
83
  # Email IMAP (Receiving)
84
  IMAP_SERVER: Optional[str] = None
 
79
  SMTP_USER: Optional[str] = "microfunnel@yandex.kg"
80
  SMTP_PASSWORD: Optional[str] = "usjqasaddkqrrauv"
81
  EMAIL_FROM: str = "microfunnel@yandex.kg"
82
+
83
+ # Resend API (Alternative to SMTP)
84
+ RESEND_API_KEY: Optional[str] = None
85
 
86
  # Email IMAP (Receiving)
87
  IMAP_SERVER: Optional[str] = None
backend/app/services/email.py CHANGED
@@ -40,9 +40,13 @@ class EmailService:
40
  Returns:
41
  True if sent successfully, False otherwise
42
  """
 
 
 
 
43
  if not self.smtp_host or not self.smtp_user:
44
  logger.warning("SMTP not configured, email not sent")
45
- return False
46
 
47
  try:
48
  # Create message
@@ -78,7 +82,7 @@ class EmailService:
78
  )
79
 
80
  logger.info(
81
- "Email sent successfully",
82
  to=to,
83
  subject=subject
84
  )
@@ -89,19 +93,65 @@ class EmailService:
89
  "Failed to send email via SMTP. Falling back to CONSOLE LOG.",
90
  error=str(e)
91
  )
92
-
93
- # FALLBACK: Log the email content (CRITICAL FOR DEVELOPMENT)
94
- print("="*60)
95
- print(f"📧 EMAIL FALLBACK (To: {to})")
96
- print(f"Subject: {subject}")
97
- print("-" * 20)
98
- if text_body:
99
- print(text_body.strip())
100
- else:
101
- print("(HTML Body hidden in logs)")
102
- print("="*60)
103
-
104
- return True # Return True so the API thinks it "sent" (to console)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
 
106
  async def send_hot_lead_notification(
107
  self,
 
40
  Returns:
41
  True if sent successfully, False otherwise
42
  """
43
+ """
44
+ if settings.RESEND_API_KEY:
45
+ return await self._send_via_resend(to, subject, html_body, text_body)
46
+
47
  if not self.smtp_host or not self.smtp_user:
48
  logger.warning("SMTP not configured, email not sent")
49
+ return self._fallback_log(to, subject, text_body)
50
 
51
  try:
52
  # Create message
 
82
  )
83
 
84
  logger.info(
85
+ "Email sent successfully (SMTP)",
86
  to=to,
87
  subject=subject
88
  )
 
93
  "Failed to send email via SMTP. Falling back to CONSOLE LOG.",
94
  error=str(e)
95
  )
96
+ return self._fallback_log(to, subject, text_body)
97
+
98
+ async def _send_via_resend(
99
+ self,
100
+ to: List[str],
101
+ subject: str,
102
+ html_body: str,
103
+ text_body: Optional[str] = None
104
+ ) -> bool:
105
+ """Send email via Resend API (HTTP)."""
106
+ import httpx
107
+
108
+ try:
109
+ async with httpx.AsyncClient() as client:
110
+ payload = {
111
+ "from": f"MicroFunnel Studio <{self.from_email}>", # Resend requires verifying domain or using their test domain
112
+ "to": to,
113
+ "subject": subject,
114
+ "html": html_body,
115
+ "text": text_body
116
+ }
117
+
118
+ # If using onboarding domain, 'from' must be 'onboarding@resend.dev'
119
+ # We will handle this gracefully: if user provided key but hasn't configured domain,
120
+ # they should probably set EMAIL_FROM to their verified domain or onboarding@resend.dev
121
+
122
+ response = await client.post(
123
+ "https://api.resend.com/emails",
124
+ headers={
125
+ "Authorization": f"Bearer {settings.RESEND_API_KEY}",
126
+ "Content-Type": "application/json"
127
+ },
128
+ json=payload
129
+ )
130
+
131
+ if response.status_code >= 400:
132
+ logger.error(f"Resend API Error: {response.text}")
133
+ # Fallback log mainly for dev
134
+ return self._fallback_log(to, subject, text_body)
135
+
136
+ logger.info("Email sent successfully (Resend API)", to=to, id=response.json().get("id"))
137
+ return True
138
+
139
+ except Exception as e:
140
+ logger.error(f"Resend API unexpected error: {e}")
141
+ return self._fallback_log(to, subject, text_body)
142
+
143
+ def _fallback_log(self, to, subject, text_body):
144
+ # FALLBACK: Log the email content
145
+ print("="*60)
146
+ print(f"📧 EMAIL FALLBACK (To: {to})")
147
+ print(f"Subject: {subject}")
148
+ print("-" * 20)
149
+ if text_body:
150
+ print(text_body.strip())
151
+ else:
152
+ print("(HTML Body hidden in logs)")
153
+ print("="*60)
154
+ return True
155
 
156
  async def send_hot_lead_notification(
157
  self,