π§ 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
smtpliblibrary (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
465or587
- 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.
