Commit ·
014e180
1
Parent(s): 66fc53f
Replace email verification with Brevo REST API using requests
Browse files16 unmodified lines1718192021222324101 unmodified lines12612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816916 unmodified linesfrom app.security import get_password_hash, verify_password, create_access_token, get_current_user, ACCESS_TOKEN_EXPIRE_MINUTESfrom datetime import timedelta, datetimeimport randomimport smtplibfrom email.mime.text import MIMETextfrom fastapi.security import OAuth2PasswordRequestForm# Load environment variables from .env file101 unmodified lines# --- Auth Endpoints ---def send_verification_email(to_email: str, code: str):# For development, just print the code.print(f"\n{'='*40}")print(f"VERIFICATION CODE FOR {to_email}: {code}")print(f"{'='*40}\n")resend_api_key = os.environ.get("RESEND_API_KEY", "re_QUveyqc3_MtpKbD1avSzp9Q9pq7tfnEMN")# Send email via Resend HTTPS REST API (Port 443 - 100% reliable on Cloud)import urllib.requestimport urllib.errorimport jsonurl = "https://api.resend.com/emails"headers = {"Authorization": f"Bearer {resend_api_key}","Content-Type": "application/json"}payload = {"from": "Smart Reader <onboarding@resend.dev>","to": [to_email],"subject": "كود تفعيل حسابك - Smart Reader","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>"}try:req = urllib.request.Request(url, data=json.dumps(payload).encode('utf-8'), headers=headers, method='POST')with urllib.request.urlopen(req, timeout=10) as response:res_data = response.read().decode('utf-8')print(f"SUCCESS: Email sent to {to_email} via Resend. Response: {res_data}")except urllib.error.HTTPError as e:try:err_body = e.read().decode('utf-8')except Exception:err_body = "<unable to read body>"print(f"Resend Email HTTPError {e.code} for {to_email}: Body={err_body}")except Exception as e:print(f"Resend Email Error for {to_email}: {e}")@app.post("/api/v1/auth/request-verification")def request_verification(req: schemas.EmailVerificationRequest, db: Session = Depends(get_db)):16 unmodified lines1718192021222324101 unmodified lines12612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717816 unmodified linesfrom app.security import get_password_hash, verify_password, create_access_token, get_current_user, ACCESS_TOKEN_EXPIRE_MINUTESfrom datetime import timedelta, datetimeimport randomimport requestsimport tracebackfrom fastapi.security import OAuth2PasswordRequestForm# Load environment variables from .env file101 unmodified lines# --- Auth Endpoints ---def send_verification_email(to_email: str, code: str) -> bool:# For development, just print the code.print(f"\n{'='*40}")print(f"VERIFICATION CODE FOR {to_email}: {code}")print(f"{'='*40}\n")api_key = os.environ.get("BREVO_API_KEY")if not api_key:print("[Brevo Email Error]: BREVO_API_KEY environment variable is not set.")return Falseurl = "https://api.brevo.com/v3/smtp/email"headers = {"accept": "application/json","api-key": api_key,"content-type": "application/json"}payload = {"sender": {"name": "Smart Reader","email": "smartreadercommunity1@gmail.com"},"to": [{"email": to_email}],"subject": "كود تفعيل حسابك - Smart Reader","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>"}try:response = requests.post(url, json=payload, headers=headers, timeout=15)if response.status_code in (200, 201, 202):print(f"[Brevo Email Success] Status Code: {response.status_code}")print(f"[Brevo Email Response Body]: {response.text}")return Trueelse:print(f"[Brevo Email Failure] Status Code: {response.status_code}")print(f"[Brevo Email Response Body]: {response.text}")print(f"[Brevo Email Response Headers]: {dict(response.headers)}")print(f"[Brevo Email Exception Traceback]: None (HTTP Status {response.status_code})")return Falseexcept Exception as e:print(f"[Brevo Email Exception Failure]: {e}")print(f"[Brevo Email Exception Traceback]:\n{traceback.format_exc()}")return False@app.post("/api/v1/auth/request-verification")def request_verification(req: schemas.EmailVerificationRequest, db: Session = Depends(get_db)):
app/main.py+37-28