Activity #48: Documentation of Python SMTP

Documentation of Activity#47

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

1. Set Up Project Directory

  1. Create a directory for your Flask app:

     mkdir Python-Email-SMTP
     cd Python-Email-SMTP
    
  2. Create a virtual environment to isolate dependencies (optional but recommended):

     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:

EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_USER=your_email@gmail.com
EMAIL_PASSWORD=your_email_password
EMAIL_SENDER=your_email@gmail.com

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. 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:

    • This route expects a JSON request body with two fields:

      • message: The body/content of the email.

      • email: The recipient email address.

  • 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).

6. Run the Flask Application

Now that the app is set up, run it:

python app.py