Want to send *emails from your Flask app* using Python? 📧 In this tutorial, I’ll show you *how to set up Flask-Mail* to send emails with Gmail SMTP, Outlook, or any custom mail server. Whether you're building a **contact form, password reset system, or notification emails**, this guide has you covered! 🚀
By the end of this video, you’ll know how to **configure Flask-Mail, send plain text and HTML emails, attach files, and use environment variables for security**.
---
*🔹 What You’ll Learn in This Video:*
✅ How to install and set up *Flask-Mail*
✅ How to configure Flask to send *emails via SMTP*
✅ How to send *plain text and HTML emails*
✅ How to attach *files and images* to emails
✅ How to use *environment variables* for secure email credentials
---
*🔹 Prerequisites*
✔️ *Python Installed* ([Download Python](https://www.python.org/downloads/))
✔️ *Flask Installed* (`pip install flask`)
✔️ *Basic Flask knowledge*
✔️ A *Gmail or any SMTP email account*
---
*🔹 Step 1: Install Flask and Flask-Mail*
First, install the required packages:
```bash
pip install flask flask-mail
```
---
*🔹 Step 2: Configure Flask-Mail*
Create a *Flask app* and set up the email configuration:
```python
from flask import Flask, render_template
from flask_mail import Mail, Message
app = Flask(__name__)
Email Configuration
app.config["MAIL_SERVER"] = "smtp.gmail.com" # SMTP Server
app.config["MAIL_PORT"] = 587 # Port for TLS
app.config["MAIL_USE_TLS"] = True
app.config["MAIL_USE_SSL"] = False
app.config["MAIL_USERNAME"] = "[email protected]" # Your email
app.config["MAIL_PASSWORD"] = "your_password" # App password or actual password
app.config["MAIL_DEFAULT_SENDER"] = "[email protected]"
mail = Mail(app)
@app.route("/send_email")
def send_email():
msg = Message(
"Hello from Flask",
recipients=["[email protected]"]
)
msg.body = "This is a test email sent from a Flask app!"
try:
mail.send(msg)
return "Email sent successfully!"
except Exception as e:
return str(e)
if _name_ == "__main__":
app.run(debug=True)
```
---
*🔹 Step 3: Secure Your Credentials with Environment Variables*
⚠️ **Never store email credentials in your code**. Use environment variables instead:
1️⃣ Create a *`.env` file* in your project folder:
```
[email protected]
MAIL_PASSWORD=your_secure_password
```
2️⃣ Install *python-dotenv* to load environment variables:
```bash
pip install python-dotenv
```
3️⃣ Modify your code to use these variables:
```python
import os
from dotenv import load_dotenv
load_dotenv()
app.config["MAIL_USERNAME"] = os.getenv("MAIL_USERNAME")
app.config["MAIL_PASSWORD"] = os.getenv("MAIL_PASSWORD")
```
---
*🔹 Step 4: Send HTML Emails*
Want to send **styled emails**? Modify the `msg.body` to `msg.html`:
---
*🔹 Step 5: Attach Files to Emails*
You can also send **attachments (PDFs, images, etc.)**:
```python
with app.open_resource("document.pdf") as attachment:
msg.attach("document.pdf", "application/pdf", attachment.read())
```
---
*🔹 Step 6: Send Emails via Outlook, Yahoo, or Custom SMTP*
Modify the **SMTP settings**:
🔹 *Gmail SMTP*
```
MAIL_SERVER = "smtp.gmail.com"
MAIL_PORT = 587
```
🔹 *Outlook SMTP*
```
MAIL_SERVER = "smtp.office365.com"
MAIL_PORT = 587
```
🔹 *Yahoo SMTP*
```
MAIL_SERVER = "smtp.mail.yahoo.com"
MAIL_PORT = 465
MAIL_USE_SSL = True
```
🔹 *Custom SMTP Server*
Replace `MAIL_SERVER` and `MAIL_PORT` with your **email provider's SMTP settings**.
---
*🔹 Common Issues & Fixes*
🔹 *SMTPAuthenticationError (535, ‘Incorrect password’)*
✅ *Fix:* Enable *App Passwords* in Gmail settings (Google may block less secure apps).
🔹 *smtplib.SMTPConnectError: (421, ‘Too many connections’)*
✅ *Fix:* Use a delay between emails or a mail queue like Celery.
🔹 *Email going to Spam?*
✅ *Fix:* Use a valid sender email and *avoid spammy keywords* in your subject line.
---
*🔹 Who Is This Tutorial For?*
✅ Developers building *Flask apps that send emails*
✅ Anyone creating *contact forms, notifications, or authentication systems*
✅ Python beginners looking to learn *SMTP and Flask-Mail*
---
*🔹 More Flask Tutorials:*
📌 *How to Build a Flask API* → [Watch Now]
📌 *How to Deploy a Flask App with Nginx & Gunicorn* → [Watch Now]
📌 *How to Connect Flask with MySQL* → [Watch Now]
---
*👍 Like, Share & Subscribe!*
If this tutorial helped you, please *LIKE, SHARE, and SUBSCRIBE* for more **Flask and Python tutorials**! 🚀
💬 Have questions? Drop them in the *comments* below!
---
*🔹 Hashtags:*
#Flask #Python #FlaskMail #EmailAutomation #SMTP #PythonSMTP #FlaskTutorial #GmailSMTP #FlaskAPI
Now you can *send emails from your Flask app* like a pro! 🚀🔥