Skip to main content

Command Palette

Search for a command to run...

Activity 48: Documentation of Python SMTP

Published
•4 min read•View as Markdown

Understanding SMTP and Its Importance

SMTP (Simple Mail Transfer Protocol) is a communication protocol used to send emails across the internet. It's responsible for the process of transferring emails from the sender's email client to the recipient's mail server or between mail servers. SMTP operates primarily for sending messages, not receiving them (which is done via protocols like POP3 or IMAP).

SMTP is important for several reasons:

  • Universal standard for email sending: SMTP is the most widely used protocol for email communication. It ensures that emails can be sent from one server to another seamlessly.

  • Reliability: SMTP is designed to ensure the reliable delivery of emails.

  • Compatibility: Almost all email clients (Gmail, Outlook, etc.) and servers support SMTP.

  • Security: Secure versions of SMTP (e.g., SMTPS or SMTP with TLS/SSL) ensure that email data is transferred safely.

Step-by-Step Guide to Set Up Python Flask to Send Emails Using SMTP

Let's walk through the steps to create a simple Flask application that will send an email using SMTP. This application will have a POST route (/send-email) where you can send a message and email address to trigger an email.

1. Install Required Libraries

You need to install Flask (for creating the web application) and Flask-Mail (for handling email sending). You can also use smtplib which is built into Python.

To install the necessary libraries:

pip install Flask Flask-Mail

  • Install python-dotenv: If you haven't already, you need to install the python-dotenv package:

      pip install python-dotenv
    

Create a .env file: In the root of your project, create a .env file to store your sensitive information like the SMTP configuration:

MAIL_SERVER=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=your_email@gmail.com
MAIL_PASSWORD=your_password
MAIL_DEFAULT_SENDER=your_email@gmail.com

2. Create the Flask Application

Here is a step-by-step breakdown of the Python Flask application:

app.py
from flask import Flask, request, jsonify
from flask_mail import Mail, Message
import smtplib
import os
from dotenv import load_dotenv

# Load environment variables from the .env file
load_dotenv()

# Initialize Flask application
app = Flask(__name__)

# Configure Flask-Mail (SMTP server settings)
app.config['MAIL_SERVER'] = os.getenv('MAIL_SERVER')  # Load from environment
app.config['MAIL_PORT'] = int(os.getenv('MAIL_PORT', 587))  # Load from environment, default to 587 if not set
app.config['MAIL_USERNAME'] = os.getenv('MAIL_USERNAME')  # Load from environment
app.config['MAIL_PASSWORD'] = os.getenv('MAIL_PASSWORD')  # Load from environment
app.config['MAIL_DEFAULT_SENDER'] = os.getenv('MAIL_DEFAULT_SENDER')  # Load from environment

# Initialize Flask-Mail
mail = Mail(app)

# POST route for sending email
@app.route('/send-email', methods=['POST'])
def send_email():
    # Get message and email from the request JSON
    data = request.get_json()
    message_body = data.get('message')
    recipient_email = data.get('email')

    # Validate input data
    if not message_body or not recipient_email:
        return jsonify({'error': 'Message and email are required.'}), 400

    try:
        # Create the email message
        msg = Message(
            'Subject: Your Flask Email',  # Subject of the email
            recipients=[recipient_email]  # List of recipients
        )
        msg.body = message_body  # The body of the email

        # Send the email
        mail.send(msg)
        return jsonify({'success': True, 'message': 'Email sent successfully!'}), 200
    except smtplib.SMTPException as e:
        return jsonify({'error': f'Failed to send email: {str(e)}'}), 500

if __name__ == '__main__':
    app.run(debug=True)

3. Explanation of Code

Flask Setup:

    1. Flask Application Initialization: A Flask app is initialized to define routes and configurations.

      1. Loading Environment Variables: The python-dotenv package loads environment variables from a .env file, keeping sensitive information like email credentials secure.

      2. SMTP Configuration: The Flask-Mail extension is configured to use Gmail's SMTP server. Configuration details like MAIL_SERVER, MAIL_PORT, MAIL_USERNAME, MAIL_PASSWORD, and MAIL_DEFAULT_SENDER are retrieved from environment variables.

      3. Mail Object Initialization: The Mail object is initialized with the app’s configuration to handle email sending.

      4. Route Definition: The /send-email route handles POST requests, expecting a JSON object with message and email fields. It validates the input and returns a 400 error if fields are missing.

      5. Sending the Email: A Message object is created with a static subject, recipient, and body. The mail.send(msg) method sends the email, returning a success message if successful.

      6. Error Handling: SMTP errors are caught, and a 500 error is returned with details.

      7. Security Considerations: Environment variables protect sensitive data, and .env files should be in .gitignore. App-specific passwords are recommended for services with 2-factor authentication.

4. Testing the API

To test this API:

  1. Run the Flask app:

     python app.py
    
  2. Use curl or Postman to send a POST request to http://127.0.0.1:5000/send-email with a JSON body:

    Example using curl:

     {
     "message": "Hello, jov.", 
     "email": "recipient_email@example.com"
     }
    

    If everything is configured correctly, you should get a response like:

    
     {
     "success": true, 
     "message": "Email sent successfully!"
     }
    

https://github.com/JovRoncal/roncal_python_flask_email_smtp

More from this blog

Jov's Blog

48 posts