⚡ Python Power Shots – 📧 Send Emails with Attachments
Posted on: December 8, 2025
Description:
📌 Introduction
Sending emails manually is slow — especially when you need to attach documents, screenshots, logs, or reports.
This Power Shot uses Python’s built-in smtplib and email libraries to send fully formatted emails with attachments. No external packages needed, and works with any SMTP provider (Gmail, Outlook, custom domain mail, etc.).
🔎 Explanation
- MIMEMultipart → builds a structured email container.
- MIMEText → adds body text.
- MIMEBase + encoders → loads and attaches files using Base64.
- smtplib.SMTP() → connects to your mail server and sends the message.
You can automate:
- daily reports
- log exports
- dataset files
- screenshots
- alerts and notifications
✅ Key Takeaways
- 📧 Send automated emails with attachments from Python.
- 🔒 Works with Gmail, Outlook, or any SMTP server.
- 🧰 Uses only built-in modules — no third-party dependencies.
Code Snippet:
try:
with open(filename, "rb") as attachment:
mime_base = MIMEBase("application", "octet-stream")
mime_base.set_payload(attachment.read())
# Encode file in base64
encoders.encode_base64(mime_base)
mime_base.add_header("Content-Disposition", f"attachment; filename={filename}")
# Attach to email
message.attach(mime_base)
except FileNotFoundError:
print(f"❌ File '{filename}' not found.")
exit()
# --- Step 5: Connect to SMTP server and send email ---
try:
# Gmail example (uses TLS)
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls() # Secure the connection
server.login(sender_email, sender_password)
server.send_message(message)
server.quit()
print("✅ Email sent successfully!")
except Exception as e:
print("❌ Error sending email:", e)
Link copied!
Comments
Add Your Comment
Comment Added!
No comments yet. Be the first to comment!