Email confirmation is a common practice in web applications to verify user accounts and prevent spam. In this guide, we’ll demonstrate how to send confirmation emails during the user registration process in a FastAPI application.
Creating a Confirmation Email Function
Python
from fastapi import APIRouter
from app.utils import send_email
router = APIRouter()
def send_confirmation_email(recipient_email, confirmation_token):
subject = "Please Confirm Your Email"
body = f"Click the following link to confirm your email: http://your-app-url/confirm/{confirmation_token}"
send_email(recipient_email, subject, body)
Sending the Confirmation Email
In your user registration endpoint, call the send_confirmation_email
function after creating the user:
Python
@router.post("/register", response_model=UserSchema)
async def register_user(user: UserCreate, db: Session = Depends(get_db)):
# ... (rest of the registration logic)
confirmation_token = create_confirmation_token(user.id)
send_confirmation_email(user.email, confirmation_token)
return {"message": "Registration successful. Please check your email for confirmation."}
Creating a Confirmation Endpoint
Create an endpoint to handle confirmation requests:
Python
@app.get("/confirm/{token}")
async def confirm_email(token: str, db: Session = Depends(get_db)):
try:
user_id = decode_confirmation_token(token)
user = await db.query(User).filter(User.id == user_id).first()
if not user:
raise HTTPException(status_code=404, detail="User not found")
user.is_verified = True
db.add(user)
await db.commit()
return {"message": "Email confirmed"}
except HTTPException as e:
raise e
By following these steps, you can effectively implement email confirmation in your FastAPI application, enhancing the security and reliability of your user registration process.