Ithy Logo

Implementing Email Login with Twilio SendGrid in Python

Secure and efficient email authentication for your website using Python

email verification process

Key Takeaways

  • Seamless Integration: Utilize Twilio SendGrid and Flask to create a robust email verification system.
  • Security Best Practices: Protect sensitive data by using environment variables and secure storage for verification codes.
  • Scalable Implementation: Implement dynamic templates and database storage to handle user verifications efficiently.

Introduction

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.


Step-by-Step Guide to Implement Email Login with Twilio SendGrid and Python

1. Setting Up Twilio and SendGrid Accounts

To begin, you need to create accounts with Twilio and SendGrid. These platforms provide the necessary tools and APIs to send and verify emails.

  1. Create a Twilio Account:

    • Sign up for a Twilio account.
    • Obtain your Account SID, Auth Token, and Verify Service SID from the Twilio dashboard.
  2. Create a SendGrid Account:

    • Sign up for a SendGrid account.
    • Generate an API Key from the SendGrid dashboard with Full Access permissions.

2. Installing Required Python Libraries

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
    

3. Configuring Environment Variables

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

    

4. Creating Dynamic Email Templates in SendGrid

Dynamic templates allow you to personalize verification emails. Set up a template in SendGrid for the verification process.

  • Navigate to the SendGrid dashboard and go to "Email API" > "Dynamic Templates".
  • Create a new template for email verification.
  • Design the email content, including placeholders for verification links or codes.

5. Developing the Flask Application

The Flask application will handle user registration, sending verification emails, and verifying the provided codes.

a. Setting Up the Flask Application

# 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()

    

b. Creating Routes for Registration and Verification

i. User Registration
@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')

    
ii. Sending Verification Email
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}')
iii. Verification Page
@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')

    
iv. Success Page
@app.route('/success')
def success():
    return 'You have successfully logged in!', 200

    

c. Creating HTML Templates

i. Registration Template
<!-- templates/register.html -->



    
    Register


    

Register

ii. Verification Template
<!-- templates/verify.html -->



    
    Verify Email


    

Verify Your Email

6. Running the Application

Start the Flask application and navigate to the registration page to begin the email verification process.

export FLASK_APP=app.py
flask run
    

7. Security Best Practices

  • Secure API Keys: Always store API keys in environment variables and never hardcode them in your codebase.
  • Use HTTPS: Ensure your application uses HTTPS to encrypt data transmitted between the client and server.
  • Rate Limiting: Implement rate limiting to prevent brute-force attacks on the verification endpoint.
  • Data Validation: Validate and sanitize all user inputs to protect against injection attacks.
  • Use a Persistent Database: For production, use a robust database system to store user data and verification codes securely.

Recap

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.


References


Last updated January 11, 2025
Ask me more