Activity 48: Documentation of Python SMTP
Introduction to SMTP and its Importance
In this section, you will explain SMTP (Simple Mail Transfer Protocol), its role in email communication, and its significance.
SMTP (Simple Mail Transfer Protocol) is a protocol used for sending emails across the internet. It is an application-layer protocol that facilitates the process of email transmission between email servers. SMTP is commonly used for sending messages from a client (like Gmail or Outlook) to a mail server, or between servers to deliver messages.
Importance of SMTP:
Email Sending: SMTP is crucial for sending emails from one server to another. It defines the rules for email transmission between servers.
Reliability: It is widely used and trusted, making it a stable choice for email communication.
Universal Support: Most email services (such as Gmail, Yahoo, etc.) support SMTP, making it easy to send emails from various applications or devices.
Security: When used with SSL/TLS encryption, SMTP allows secure sending of emails, protecting sensitive information like login credentials and message contents.
Step-by-Step Guide for Sending Emails Using Python Flask with SMTP
Step 1: Set Up Your Flask Project
Create a Project Directory
First, create a new directory to store your project files.mkdir nicolas_python_flask_email_smtp cd nicolas_python_flask_email_smtp
Create a Virtual Environment
It's recommended to use a virtual environment to keep the project dependencies isolated.python -m venv env
Activate the Virtual Environment
On Windows:
env\Scripts\activate
Install Flask
Flask is the main framework for building your API. Install Flask usingpip
:pip install flask
Step 2: Set Up Email Configuration
To send emails, you'll need to configure the SMTP server settings. These settings are specific to your email provider (e.g., Gmail, Outlook, etc.).
SMTP Configuration Variables
Add the following configuration variables to the Flask app. Replace these placeholders with the correct information for your email provider:EMAIL_HOST
: The SMTP server (e.g., for Gmail usesmtp.gmail.com
).EMAIL_PORT
: The SMTP server port (usually 587 for secure connections).EMAIL_HOST_USER
: Your email address (e.g.,monettenicolas069@gmail.com
).EMAIL_HOST_PASSWORD
: Your email password (or app-specific password if using Gmail with 2FA enabled).
For example:
EMAIL_HOST = "smtp.gmail.com" # For Gmail
EMAIL_PORT = 587
EMAIL_HOST_USER = "monettenicolas069@gmail.com" # your gmail
EMAIL_HOST_PASSWORD = "your app password" # Replace with your app password
You should not put your Gmail password directly into your code, especially if you plan to place it in public repositories It is indeed dangerous. Instead, there are safer ways to handle your email credentials.
How to Handle Passwords Securely?
- Use Google App Passwords (if 2-step verification is enabled) When your Gmail account has 2-step verification (2FA) enabled, you need to use an App Password. You don't need to enter your main Gmail password; instead, Google provides a special password for apps that cannot handle 2-step verification.
How to Create an App Password in Gmail:
Go to your Google Account Security settings.
Enable 2-step verification if it is not already enabled.
Click on App Passwords.
Just type your App name and then create
Select Mail and the device you will be using (e.g., "Windows Computer").
You will receive a 16-character password, and you should use this password in your Flask app instead of your Gmail password.
This app password provided by Google is the one you will use and place in your code.
Step 3: Create app.py
Create a file named app.py
in your project directory and add the following Python code:
from flask import Flask, request, jsonify
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
app = Flask(__name__)
# Configure SMTP server settings
EMAIL_HOST = "smtp.gmail.com"
EMAIL_PORT = 587
EMAIL_HOST_USER = "monettenicolas069@gmail.com" # your gamil
EMAIL_HOST_PASSWORD = "your app password" # replace with your app password provided by Google
@app.route('/send-email', methods=['POST'])
def send_email():
# Get data from request body
data = request.json
recipient_email = data.get('email')
message_body = data.get('message')
# Check if the required fields are provided
if not recipient_email or not message_body:
return jsonify({"error": "Email and message are required!"}), 400
try:
# Create email message
msg = MIMEMultipart()
msg['From'] = EMAIL_HOST_USER
msg['To'] = recipient_email
msg['Subject'] = "Automated Email from Flask App" # Subject of the email
# Attach the message body
msg.attach(MIMEText(message_body, 'plain'))
# Send the email using SMTP
with smtplib.SMTP(EMAIL_HOST, EMAIL_PORT) as server:
server.starttls() # Secure the connection
server.login(EMAIL_HOST_USER, EMAIL_HOST_PASSWORD)
server.sendmail(EMAIL_HOST_USER, recipient_email, msg.as_string())
return jsonify({"message": "Email sent successfully!"}), 200
except Exception as e:
# Handle errors
return jsonify({"error": str(e)}), 500
if __name__ == '__main__':
app.run(debug=True)
Step 4: Run the Flask Application
Now that you’ve set up your Flask application, you can run it.
Run the Application
In your terminal, execute the following command:python app.py
Your Flask application is now live and can handle incoming requests at
http://127.0.0.1:5000/
.
Step 5: Test the /send-email
Endpoint
To test the /send-email
endpoint, you can use Postman or curl to send a POST request to the Flask server.
Open Postman
Set the Request Type to POST.
http://127.0.0.1:5000/send-email
Set the Request Body to JSON format:
Choose the Body tab.
Select raw.
Choose JSON format from the dropdown.
Add the following JSON:
{ "email": "monettenicolas069@gmail.com", "message": "Hello, this is a test email from Flask!" }
Send the Request
Automated Email from Flask App (Gmail)
Step 7: Push to GitHub
git init
git add .
git commit -m "Initial commit"
git remote add origin https://github.com/MonetForProgrammingPurposes/nicolas_python_flask_email_smtp.git
git push -u origin master