Activity #48: Documentation of Python SMTP

Step-by-Step Guide for Sending Emails via SMTP in Python Flask

Set Up Project Directory

1. Create a directory for your Flask app:

2. Create a virtual environment to isolate dependencies

 python -m venv venv
 venv\Scripts\activate

3. Install Dependencies

You'll need to install Flask for the web server and Flask-Mail for handling email tasks. Optionally, you can also install python-dotenv for managing environment variables (like SMTP credentials).

pip install Flask Flask-Mail python-dotenv

Create a .env file

For security, we will store sensitive information like email credentials in a .env file. Create a .env file in your project directory:

nul > .env

4. Create the Flask App

Now, create a Python file for the Flask app, app.py.

from flask import Flask, request, jsonify
from flask_mail import Mail, Message
import os
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

app = Flask(__name__)

# Configure the Flask-Mail extension
app.config['MAIL_SERVER'] = os.getenv('EMAIL_HOST')
app.config['MAIL_PORT'] = int(os.getenv('EMAIL_PORT'))
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USERNAME'] = os.getenv('EMAIL_USER')
app.config['MAIL_PASSWORD'] = os.getenv('EMAIL_PASSWORD')
app.config['MAIL_DEFAULT_SENDER'] = os.getenv('EMAIL_SENDER')

# Initialize Mail object
mail = Mail(app)

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

        if not message_body or not recipient_email:
            return jsonify({'error': 'Missing message or email'}), 400

        # Compose the email message
        msg = Message(subject="Message from Flask App",
                      recipients=[recipient_email],
                      body=message_body)

        # Send the email
        mail.send(msg)

        return jsonify({'success': True, 'message': 'Email sent successfully'}), 200

    except Exception as e:
        return jsonify({'error': str(e)}), 500

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

5. Run the Flask Application

Now that the app is set up, run it:

python app.py

6. Explanation:

Flask Configuration: We load email credentials from the .env file using the python-dotenv library and set up Flask-Mail to send emails via an SMTP server.

POST Route /send-email:

http://127.0.0.1:5000/send-email

This route expects a JSON request body with two fields:

message: The body/content of the email.

email: The recipient email address.

{
    "message": "Hello, this is a test email from Flask!!",
    "email": "romel.usigan25@gmail.com"
}

It uses smtplib to send the email via SMTP.

If something is missing or goes wrong, we send an error message in the response.

Sending Email:

We create a Message object from Flask-Mail, passing the subject, recipient, and body content.

The email is sent using mail.send(msg).