Skip to main content

Command Palette

Search for a command to run...

Python Email SMTP

Published
2 min read

To implement an email sending functionality in Python using SMTP, you can use the built-in smtplib library to send emails through an SMTP server. Here's a simple Flask application that includes a POST /send-email route to send an email with a custom message to a specified recipient.

Steps for Implementing Email Sending in Flask with SMTP

1. Install Flask (if not installed yet):

pip install Flask

2. Code Implementation:

In the example below, the Flask app will have a POST /send-email endpoint. When a message and email (recipient email) are sent in the request body, it will send an email using Python's SMTP.

SMTP.

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)

Explanation:

  • SMTP Server Configuration: The example uses Gmail’s SMTP server (smtp.gmail.com) on port 587. You need to enable less secure apps or use an App Password for Gmail if you are using 2FA. It's a good practice to use environment variables for sensitive data like passwords.

  • send_email function: This function creates and sends the email. It uses the smtplib.SMTP library to connect to the SMTP server, log in, and send the email.

  • POST /send-email: The route accepts a JSON payload with two fields:

    • message: The body of the email.

    • email: The recipient's email address.

  • Error Handling: The application checks if both the message and email fields are provided and responds accordingly.

Running on http://127.0.0.1:5000