File size: 1,410 Bytes
96986d4
8d6997d
96986d4
dcdede2
8d6997d
 
96986d4
 
8d6997d
 
 
 
 
96986d4
8d6997d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f174d71
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import os
import requests
from dotenv import load_dotenv


# Load variables from .env file
load_dotenv()


SENDGRID_API_KEY = os.getenv("SENDGRID_API_KEY")
SENDER_EMAIL = os.getenv("SENDER_EMAIL")


def send_otp_email(receiver_email, otp):
   """
   Sends an OTP email using SendGrid API v3.
   """
   url = "https://api.sendgrid.com/v3/mail/send"
  
   headers = {
       "Authorization": f"Bearer {SENDGRID_API_KEY}",
       "Content-Type": "application/json"
   }
  
   data = {
       "personalizations": [{
           "to": [{"email": receiver_email}]
       }],
       "from": {
           "email": SENDER_EMAIL,
           "name": "FitPlan AI"
       },
       "subject": "Your FitPlan AI Verification Code",
       "content": [{
           "type": "text/plain",
           "value": f"Welcome to FitPlan AI! Your one-time password (OTP) is: {otp}. This code will expire in 1 hour."
       }]
   }


   try:
       response = requests.post(url, headers=headers, json=data)
      
       # Log status to terminal for debugging
       print(f"DEBUG: SendGrid Response Status: {response.status_code}")
      
       if response.status_code != 202:
           print(f"DEBUG: SendGrid Error Detail: {response.text}")
           raise Exception(f"Failed to send email: {response.text}")
      
       return True
      
   except Exception as e:
       print(f"DEBUG: Exception occurred: {e}")
       raise e