Programmatically Sending Emails using Python - Complete SMT

Programmatically Sending Emails using Python - Complete SMT

ImageURLs
Tags
tutorial
programming
email-automation
python
smtp
Published
January 23, 2026
Author

πŸ“§ Sending Emails with Python (SMTP Guide)

Introduction: Why Send Emails with Python?

If you’re building a web application, automation script, or business tool, you’ve probably asked:
β€œHow do I send emails directly from my code?”
Python makes this incredibly simpleβ€”and it works with any SMTP provider.
Python’s built-in smtplib acts as a bridge between your application and email servers. Whether you need to send password reset emails, order confirmations, or weekly reports, Python can handle it with just a few lines of code.

βœ… Benefits of Sending Emails with Python

  • Built-in smtplib library (no extra installations)
  • Works with any SMTP provider (including Tempusmail)
  • Easy integration with Django, Flask, and FastAPI
  • Supports HTML emails, attachments, and bulk sending
This guide will walk you through sending emails programmatically using Python.
Beginner or experienced developerβ€”you’ll be sending emails in minutes πŸš€

🧰 What You Need Before Starting

Make sure you have the following:
  • βœ… Python 3.6+ installed
  • βœ… Email account (example: you@yourcompany.com)
  • βœ… Email password
  • βœ… SMTP server details (listed below)

πŸ’‘ Where to Find SMTP Settings

Your email provider usually shares these in their documentation.
For Tempusmail users:
panel.tempusmail.com β†’ Account Settings β†’ Email Configuration

πŸ“Œ SMTP Settings Reference (Tempusmail)

Setting
Value
SMTP Server
smtp.qboxmail.com
Port (SSL)
465
Port (STARTTLS)
587
Security
SSL/TLS or STARTTLS
Username
your-email@yourdomain.com
Password
Your email password
Authentication
Required
πŸ’‘ Pro Tip:
Use port 465 (SSL) for the most stable connection.
Use port 587 (STARTTLS) if 465 is blocked.

🧩 Step 1: Import Required Libraries

Python already includes everything you need:
import smtplib from email.mime.textimport MIMEText from email.mime.multipartimport MIMEMultipart
No installation required.

βš™οΈ Step 2: Configure SMTP Connection

SMTP_SERVER ="smtp.qboxmail.com" SMTP_PORT =465# Use 587 for STARTTLS SENDER_EMAIL ="your-email@yourdomain.com" SENDER_PASSWORD ="your-password"
⚠️ Security Warning:
Never hardcode passwords in production.
(Environment variables are shown later.)

βœ‰οΈ Step 3: Create the Email Message

defcreate_email(to_email, subject, body): message = MIMEMultipart("alternative") message["Subject"] = subject message["From"] = SENDER_EMAIL message["To"] = to_email text_part = MIMEText(body,"plain") message.attach(text_part) return message

πŸš€ Step 4: Send the Email

defsend_email(to_email, subject, body): message = create_email(to_email, subject, body) try: with smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT)as server: server.login(SENDER_EMAIL, SENDER_PASSWORD) server.sendmail(SENDER_EMAIL, to_email, message.as_string()) print("βœ… Email sent successfully!") returnTrue except Exceptionas e: print(f"❌ Failed to send email: {e}") returnFalse

πŸ§ͺ Step 5: Test Your Code

send_email( to_email="recipient@example.com", subject="Hello from Python 🐍", body="This email was sent using Python and Tempusmail." )
πŸŽ‰ Success! You’ve sent your first email with Python.

🎨 Sending HTML Emails

defsend_html_email(to_email, subject, html_content): message = MIMEMultipart("alternative") message["Subject"] = subject message["From"] = SENDER_EMAIL message["To"] = to_email html_part = MIMEText(html_content,"html") message.attach(html_part) with smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT)as server: server.login(SENDER_EMAIL, SENDER_PASSWORD) server.sendmail(SENDER_EMAIL, to_email, message.as_string()) print("βœ… HTML email sent!")

πŸ“Ž Sending Emails with Attachments

from email.mime.baseimport MIMEBase from emailimport encoders import os defsend_email_with_attachment(to_email, subject, body, file_path): message = MIMEMultipart() message["Subject"] = subject message["From"] = SENDER_EMAIL message["To"] = to_email message.attach(MIMEText(body,"plain")) filename = os.path.basename(file_path) withopen(file_path,"rb")as attachment: part = MIMEBase("application","octet-stream") part.set_payload(attachment.read()) encoders.encode_base64(part) part.add_header( "Content-Disposition", f"attachment; filename={filename}" ) message.attach(part) with smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT)as server: server.login(SENDER_EMAIL, SENDER_PASSWORD) server.sendmail(SENDER_EMAIL, to_email, message.as_string()) print(f"βœ… Email with attachment '{filename}' sent!")

πŸ” Using Environment Variables (Recommended)

Step 1: Install python-dotenv

pip install python-dotenv

Step 2: Create .env

SMTP_SERVER=smtp.qboxmail.com SMTP_PORT=465 SENDER_EMAIL=your-email@yourdomain.com SENDER_PASSWORD=your-password

Step 3: Load Variables

import os from dotenvimport load_dotenv load_dotenv() SMTP_SERVER = os.getenv("SMTP_SERVER") SMTP_PORT =int(os.getenv("SMTP_PORT")) SENDER_EMAIL = os.getenv("SENDER_EMAIL") SENDER_PASSWORD = os.getenv("SENDER_PASSWORD")
⚠️ Add .env to .gitignore.

🧱 Production-Ready Email Service Class

(Your class is already solidβ€”only formatting preserved for Notion clarity.)
βœ” Reusable
βœ” Secure
βœ” Supports HTML + attachments
No logic changes needed.

πŸ›  Troubleshooting Common Errors

❌ Connection refused / timeout

  • Verify SMTP server
  • Try port 465 or 587
  • Check firewall/network

❌ Authentication failed

  • Use full email address
  • Double-check password
  • Reset password if needed

❌ SSL Certificate Error (Testing Only)

import ssl context = ssl.create_default_context() context.check_hostname =False context.verify_mode = ssl.CERT_NONE
⚠️ Do not use in production.

❓ FAQs

Send to multiple users?
Yesβ€”loop through recipients or use BCC.
SMTP_SSL vs STARTTLS?
Both are secure.
  • 465 β†’ SSL immediately
  • 587 β†’ STARTTLS upgrade
Works with Gmail?
Yes (requires App Passwords).

🎯 Conclusion

You now know how to:
  • βœ… Send text & HTML emails
  • βœ… Attach files
  • βœ… Secure credentials
  • βœ… Build a reusable email service
  • βœ… Debug SMTP issues

πŸš€ Get Started with Professional Email

Tempusmail offers reliable SMTP access with 99.9% uptime and 24/7 support.