📧 Send Email Using Python (SMTP) — Simple and Powerful Script
Want to send emails directly from Python using SMTP? This simple script lets you send an email with:
- ✉ A subject
- 📝 Body content (HTML supported)
- 📎 Attachments (optional)
- 🔗 Links & inline images
Perfect for automation, newsletters, alerts, notifications, or bulk tools.
📦 Step 1: Install Required Module (Optional)
Python comes with smtplib built-in, so no installation needed.
But if you want to use HTML formatting safely, install:
pip install email-validator
🔐 Step 2: Enable App Password (Gmail)
To send emails using Python, Gmail requires you to create an App Password. Follow these steps:
-
Open your Google Account:
https://myaccount.google.com - Go to the Security section:
https://myaccount.google.com/security - Turn on 2-Step Verification (if not already enabled).
https://myaccount.google.com/signinoptions/two-step-verification - Scroll down to App Passwords.
https://myaccount.google.com/apppasswords - Select Mail as the app.
- Select your device name, or choose Other.
- Click Generate.
- Copy the 16-digit password shown.
-
Use this password in your Python script:
GMAIL_PASS = "your-16-digit-app-password"
⚠️ Note: App Passwords only work if you have 2-Step Verification enabled.
For Outlook, Yahoo, Hotmail — same process.
💻 Step 3: Python Email Script
Create a file named: send_mail.py and paste this code 👇
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
sender_email = "your_email@gmail.com"
receiver_email = "receiver@example.com"
app_password = "your_app_password"
subject = "Test Email from Python"
body = """
<h2>Hello from Python! 👋</h2>
<p>This is an automated email sent using <strong>Python SMTP</strong>.</p>
<p>You can add:</p>
<ul>
<li>Images 🖼️</li>
<li>Links 🔗</li>
<li>HTML formatting 🎨</li>
</ul>
<p>Visit: <a href='https://example.com'>Click Here</a></p>
"""
msg = MIMEMultipart()
msg["From"] = sender_email
msg["To"] = receiver_email
msg["Subject"] = subject
msg.attach(MIMEText(body, "html"))
try:
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login(sender_email, app_password)
server.sendmail(sender_email, receiver_email, msg.as_string())
server.quit()
print("✅ Email Sent Successfully!")
except Exception as e:
print("❌ Error:", e)
⚙️ Step 4: Run the Script
python send_mail.py
Your email will be sent instantly 🚀
🧠 How It Works
- Connects to Gmail SMTP server (587)
- Logs in using secure App Password
- Formats your email using HTML
- Sends the mail once and prints success
💡 Extra Features You Can Add
- 📎 Attachments (PDF, Excel, Images)
- 📮 CC & BCC
- 📑 HTML Templates
- 🤖 Automated email bots
🎯 Quick Summary
- Language: Python
- Protocol: SMTP
- Output: Sends email successfully
📢 Join the Community
- Join our WhatsApp channel for more automation scripts.
❤️ If this tutorial helped you, share it with the community and help others learn automation!
