Implementing an email login system is a fundamental feature for many web applications, ensuring that users can securely access their accounts. By leveraging Twilio SendGrid alongside Python and the Flask framework, developers can create a reliable and scalable email verification process. This comprehensive guide will walk you through the steps to set up email login using Twilio SendGrid, providing detailed code examples and best practices to ensure a secure implementation.
To begin, you need to create accounts with Twilio and SendGrid. These platforms provide the necessary tools and APIs to send and verify emails.
Create a Twilio Account:
Create a SendGrid Account:
Install the necessary Python libraries using pip. These libraries include Flask for the web framework, SendGrid for sending emails, Twilio for verification services, and python-dotenv for managing environment variables.
pip install flask sendgrid twilio python-dotenv
Storing sensitive information such as API keys in environment variables is a best practice to enhance security.
# .env file
TWILIO_ACCOUNT_SID=your_twilio_account_sid
TWILIO_AUTH_TOKEN=your_twilio_auth_token
TWILIO_VERIFY_SERVICE_SID=your_twilio_verify_service_sid
SENDGRID_API_KEY=your_sendgrid_api_key
SECRET_KEY=your_flask_secret_key
Dynamic templates allow you to personalize verification emails. Set up a template in SendGrid for the verification process.
The Flask application will handle user registration, sending verification emails, and verifying the provided codes.
# app.py
import os
from flask import Flask, request, redirect, url_for, render_template, session
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
from twilio.rest import Client
import uuid
from dotenv import load_dotenv
from flask_sqlalchemy import SQLAlchemy
# Load environment variables
load_dotenv()
app = Flask(__name__)
app.secret_key = os.getenv('SECRET_KEY')
# Configure Database (Using SQLite for simplicity)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
db = SQLAlchemy(app)
# Twilio Client Setup
twilio_client = Client(os.getenv('TWILIO_ACCOUNT_SID'), os.getenv('TWILIO_AUTH_TOKEN'))
# SendGrid Client Setup
sendgrid_client = SendGridAPIClient(os.getenv('SENDGRID_API_KEY'))
# Database Model
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(120), unique=True, nullable=False)
verification_code = db.Column(db.String(6), nullable=False)
verified = db.Column(db.Boolean, default=False)
def __repr__(self):
return f''
# Initialize the database
with app.app_context():
db.create_all()
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
email = request.form['email']
existing_user = User.query.filter_by(email=email).first()
if existing_user:
return 'Email already registered. Please log in or use a different email.', 400
verification_code = str(uuid.uuid4().int)[:6]
new_user = User(email=email, verification_code=verification_code)
db.session.add(new_user)
db.session.commit()
# Send verification email
send_verification_email(email, verification_code)
return redirect(url_for('verify'))
return render_template('register.html')
def send_verification_email(to_email, code):
message = Mail(
from_email='no-reply@yourdomain.com',
to_emails=to_email,
subject='Verify Your Email Address',
html_content=f'''
Thank you for registering. Please verify your email by entering the following code:
{code}
If you did not request this, please ignore this email.
'''
)
try:
sendgrid_client.send(message)
print(f'Verification email sent to {to_email}')
except Exception as e:
print(f'Error sending email: {e}')
@app.route('/verify', methods=['GET', 'POST'])
def verify():
if request.method == 'POST':
email = request.form['email']
code = request.form['code']
user = User.query.filter_by(email=email).first()
if user and user.verification_code == code:
user.verified = True
db.session.commit()
return 'Email verified successfully!', 200
else:
return 'Invalid verification code. Please try again.', 400
return render_template('verify.html')
@app.route('/success')
def success():
return 'You have successfully logged in!', 200
<!-- templates/register.html -->
Register
Register
<!-- templates/verify.html -->
Verify Email
Verify Your Email
Start the Flask application and navigate to the registration page to begin the email verification process.
export FLASK_APP=app.py
flask run
Implementing an email login system using Twilio SendGrid and Python's Flask framework involves setting up necessary accounts, configuring environment variables, creating dynamic email templates, and developing secure routes for user registration and verification. By following the steps outlined in this guide and adhering to security best practices, you can create a reliable and user-friendly email authentication system for your website.