Mohamed478 commited on
Commit
014e180
·
1 Parent(s): 66fc53f

Replace email verification with Brevo REST API using requests

Browse files
Files changed (1) hide show
  1. app/main.py +37 -28
app/main.py CHANGED
@@ -17,8 +17,8 @@ from app.services.scraper import scrape_article_url
17
  from app.security import get_password_hash, verify_password, create_access_token, get_current_user, ACCESS_TOKEN_EXPIRE_MINUTES
18
  from datetime import timedelta, datetime
19
  import random
20
- import smtplib
21
- from email.mime.text import MIMEText
22
  from fastapi.security import OAuth2PasswordRequestForm
23
 
24
  # Load environment variables from .env file
@@ -126,44 +126,53 @@ def generate_ai_summary(content: str) -> str:
126
 
127
  # --- Auth Endpoints ---
128
 
129
- def send_verification_email(to_email: str, code: str):
130
  # For development, just print the code.
131
  print(f"\n{'='*40}")
132
  print(f"VERIFICATION CODE FOR {to_email}: {code}")
133
  print(f"{'='*40}\n")
134
 
135
- resend_api_key = os.environ.get("RESEND_API_KEY", "re_QUveyqc3_MtpKbD1avSzp9Q9pq7tfnEMN")
136
-
137
- # Send email via Resend HTTPS REST API (Port 443 - 100% reliable on Cloud)
138
- import urllib.request
139
- import urllib.error
140
- import json
141
-
142
- url = "https://api.resend.com/emails"
143
  headers = {
144
- "Authorization": f"Bearer {resend_api_key}",
145
- "Content-Type": "application/json"
 
146
  }
147
  payload = {
148
- "from": "Smart Reader <onboarding@resend.dev>",
149
- "to": [to_email],
 
 
 
 
 
 
 
150
  "subject": "كود تفعيل حسابك - Smart Reader",
151
- "html": f"<div dir='rtl' style='font-family: Arial, sans-serif; padding: 25px; background-color: #f4f4f7;'><div style='max-width: 500px; margin: 0 auto; background: #ffffff; padding: 30px; border-radius: 16px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); text-align: center;'><h2 style='color: #4f46e5; margin-bottom: 10px;'>Smart Reader</h2><p style='color: #4b5563; font-size: 16px;'>كود التفعيل الخاص بحسابك هو:</p><div style='background: #eef2ff; border: 2px dashed #6366f1; border-radius: 12px; padding: 15px; margin: 20px 0;'><span style='color: #4338ca; font-size: 32px; font-weight: bold; letter-spacing: 6px;'>{code}</span></div><p style='color: #9ca3af; font-size: 14px;'>هذا الكود صالح لمدة 10 دقائق فقط.</p></div></div>"
152
  }
153
-
154
  try:
155
- req = urllib.request.Request(url, data=json.dumps(payload).encode('utf-8'), headers=headers, method='POST')
156
- with urllib.request.urlopen(req, timeout=10) as response:
157
- res_data = response.read().decode('utf-8')
158
- print(f"SUCCESS: Email sent to {to_email} via Resend. Response: {res_data}")
159
- except urllib.error.HTTPError as e:
160
- try:
161
- err_body = e.read().decode('utf-8')
162
- except Exception:
163
- err_body = "<unable to read body>"
164
- print(f"Resend Email HTTPError {e.code} for {to_email}: Body={err_body}")
 
165
  except Exception as e:
166
- print(f"Resend Email Error for {to_email}: {e}")
 
 
167
 
168
  @app.post("/api/v1/auth/request-verification")
169
  def request_verification(req: schemas.EmailVerificationRequest, db: Session = Depends(get_db)):
 
17
  from app.security import get_password_hash, verify_password, create_access_token, get_current_user, ACCESS_TOKEN_EXPIRE_MINUTES
18
  from datetime import timedelta, datetime
19
  import random
20
+ import requests
21
+ import traceback
22
  from fastapi.security import OAuth2PasswordRequestForm
23
 
24
  # Load environment variables from .env file
 
126
 
127
  # --- Auth Endpoints ---
128
 
129
+ def send_verification_email(to_email: str, code: str) -> bool:
130
  # For development, just print the code.
131
  print(f"\n{'='*40}")
132
  print(f"VERIFICATION CODE FOR {to_email}: {code}")
133
  print(f"{'='*40}\n")
134
 
135
+ api_key = os.environ.get("BREVO_API_KEY")
136
+ if not api_key:
137
+ print("[Brevo Email Error]: BREVO_API_KEY environment variable is not set.")
138
+ return False
139
+
140
+ url = "https://api.brevo.com/v3/smtp/email"
 
 
141
  headers = {
142
+ "accept": "application/json",
143
+ "api-key": api_key,
144
+ "content-type": "application/json"
145
  }
146
  payload = {
147
+ "sender": {
148
+ "name": "Smart Reader",
149
+ "email": "smartreadercommunity1@gmail.com"
150
+ },
151
+ "to": [
152
+ {
153
+ "email": to_email
154
+ }
155
+ ],
156
  "subject": "كود تفعيل حسابك - Smart Reader",
157
+ "htmlContent": f"<div dir='rtl' style='font-family: Arial, sans-serif; padding: 25px; background-color: #f4f4f7;'><div style='max-width: 500px; margin: 0 auto; background: #ffffff; padding: 30px; border-radius: 16px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); text-align: center;'><h2 style='color: #4f46e5; margin-bottom: 10px;'>Smart Reader</h2><p style='color: #4b5563; font-size: 16px;'>كود التفعيل الخاص بحسابك هو:</p><div style='background: #eef2ff; border: 2px dashed #6366f1; border-radius: 12px; padding: 15px; margin: 20px 0;'><span style='color: #4338ca; font-size: 32px; font-weight: bold; letter-spacing: 6px;'>{code}</span></div><p style='color: #9ca3af; font-size: 14px;'>هذا الكود صالح لمدة 10 دقائق فقط.</p></div></div>"
158
  }
159
+
160
  try:
161
+ response = requests.post(url, json=payload, headers=headers, timeout=15)
162
+ if response.status_code in (200, 201, 202):
163
+ print(f"[Brevo Email Success] Status Code: {response.status_code}")
164
+ print(f"[Brevo Email Response Body]: {response.text}")
165
+ return True
166
+ else:
167
+ print(f"[Brevo Email Failure] Status Code: {response.status_code}")
168
+ print(f"[Brevo Email Response Body]: {response.text}")
169
+ print(f"[Brevo Email Response Headers]: {dict(response.headers)}")
170
+ print(f"[Brevo Email Exception Traceback]: None (HTTP Status {response.status_code})")
171
+ return False
172
  except Exception as e:
173
+ print(f"[Brevo Email Exception Failure]: {e}")
174
+ print(f"[Brevo Email Exception Traceback]:\n{traceback.format_exc()}")
175
+ return False
176
 
177
  @app.post("/api/v1/auth/request-verification")
178
  def request_verification(req: schemas.EmailVerificationRequest, db: Session = Depends(get_db)):