I used Yagmail with a self-hosted SMTP server and slept like a privacy nerd.
What started as a routine email automation project quickly spiraled into a rabbit hole of data sovereignty and third-party tracking. I needed to send clean, formatted reports without giving Big Tech another peek at my content.
That’s when I stumbled across Yagmail—a Python package designed for simplicity—but with a twist: it defaults to Gmail’s OAuth2 flow.
As a FOSS advocate, that didn’t sit right. I wanted control. I wanted logs, headers, and a traceable trail that didn’t end in a Google data center. So I rolled up my sleeves, configured a custom SMTP server, and rewired Yagmail to respect my boundaries.
What happened next? Emails sent from a Raspberry Pi running Postfix—and a full night’s sleep, no tracking pixels included.
Here’s how to take Yagmail back into your own hands.
What Is a Custom SMTP Server (and Why You’d Want One)
By default, Yagmail is designed to work with Gmail’s SMTP service. It’s quick and convenient—but also limited. If you’re working in environments where Google isn’t welcome (like some air-gapped machines, censorship-heavy networks, or privacy-conscious setups), relying on Gmail can become a bottleneck—or worse, a liability.
A custom SMTP server lets you send email using services like Postmark, Sendinblue, Mailgun, or even your own Postfix installation. This gives you more control, better deliverability metrics, and, for the FOSS crowd, a sense of sovereignty. Whether you want better privacy or you’re automating from a self-hosted system, custom SMTP is the power move.
· · ─ ·𖥸· ─ · ·
Understanding SMTP Ports, SSL vs TLS, and Auth Basics
If you’re new to email protocols, SMTP can feel like a black box. But here’s the quick breakdown you need to understand what your config is doing:
- SMTP Ports:
465
: Uses implicit SSL encryption. The connection is encrypted from the start.587
: Starts unencrypted but upgrades to TLS encryption via STARTTLS.25
: Default SMTP port (often blocked by ISPs to prevent spam).
- SSL vs TLS:
Both secure your connection, but TLS is the modern standard and more flexible. Yagmail supports both, but your SMTP provider will dictate what to use. - SMTP Auth:
Most providers require a valid username/password pair to relay messages. This is where you’ll plug in your API keys or credentials.
Tip: For FOSS-friendly setups, avoid hardcoding these values. Use environment variables or .env
files to store sensitive info and load them using Python’s os.getenv()
.
· · ─ ·𖥸· ─ · ·
Installing Yagmail and SMTP Dependencies
Before you can send emails like a privacy-respecting pro, you’ll need to install Yagmail and a few supporting libraries. Whether you’re on a Raspberry Pi, a remote server, or your daily Linux machine, the process is refreshingly lightweight. Yagmail plays well with Python environments and works right out of the box—once you’ve got the right packages in place. We’ll also prep your system for secure SMTP connections, which is where the real fun (and freedom) begins.
Prerequisites
Python Installed: Ensure you have Python installed on your system.
Yagmail Installed: Install yagmail
using pip.
pip install yagmail
Install yagmail
First, install yagmail
if you haven’t already:
pip install yagmail
Set Up SMTP Configuration
To perform a yagmail custom SMTP setup, you need to configure yagmail
with your SMTP server details. You can either use environment variables or configure it directly in your Python script.
Option 1: Using Environment Variables
Set Environment Variables: Add the following lines to your shell profile (~/.bashrc
, ~/.zshrc
, etc.):
export YAGMAIL_SMTP_SERVER="smtp.yourprovider.com"
export YAGMAIL_SMTP_PORT=587 # or 465 for SSL
export YAGMAIL_SMTP_USER="your-email@yourprovider.com"
export YAGMAIL_SMTP_PASSWORD="your-password"
Reload Your Shell Profile
source ~/.bashrc
# OR
source ~/.zshrc
Directly in Python Script
You can configure yagmail
directly in your script by providing SMTP settings:
import yagmail
# Initialize yagmail with custom SMTP settings
yag = yagmail.SMTP(
user='your-email@yourprovider.com',
password='your-password',
host='smtp.yourprovider.com',
port=587, # or 465 for SSL
smtp_starttls=True # Use TLS (set to False for SSL)
)
Sending Emails
With yagmail
configured, you can now send emails. Here are examples for basic emails, emails with attachments, and HTML emails.
Basic Email
import yagmail
# Initialize yagmail
yag = yagmail.SMTP('your-email@yourprovider.com', 'your-password')
# Send a basic email
yag.send(
to='recipient@example.com',
subject='Test Subject',
contents='This is the email body'
)
Email with Attachments
import yagmail
# Initialize yagmail
yag = yagmail.SMTP('your-email@yourprovider.com', 'your-password')
# Send an email with attachments
yag.send(
to='recipient@example.com',
subject='Test Subject',
contents='This is the email body',
attachments='/path/to/attachment.file'
)
HTML Email
import yagmail
# Send an HTML email
yag.send(
to='recipient@example.com',
subject='Test Subject',
contents='<h1>This is an HTML email</h1>'
)
Using SSL/TLS
For SSL: Use port 465
and set smtp_starttls=False
.
yag = yagmail.SMTP(
user='your-email@yourprovider.com',
password='your-password',
host='smtp.yourprovider.com',
port=465, # SSL port
smtp_starttls=False
)
For TLS: Use port 587
and set smtp_starttls=True
.
yag = yagmail.SMTP(
user='your-email@yourprovider.com',
password='your-password',
host='smtp.yourprovider.com',
port=587, # TLS port
smtp_starttls=True
)
· · ─ ·𖥸· ─ · ·
Troubleshooting
If you encounter issues:
- Check SMTP Server Details: Verify that the SMTP server address, port, and credentials are correct.
- Test Connectivity: Use tools like
openssl
to ensure you can connect to the SMTP server. - Review Errors: Check error messages for details and adjust configuration as needed.
· · ─ ·𖥸· ─ · ·
Example Python Script
Here’s a complete example that uses custom SMTP settings with yagmail
:
import yagmail
# Initialize yagmail with custom SMTP settings
yag = yagmail.SMTP(
user='your-email@yourprovider.com',
password='your-password',
host='smtp.yourprovider.com',
port=587, # TLS port
smtp_starttls=True
)
# Send an email
try:
yag.send(
to='recipient@example.com',
subject='Test Subject',
contents='This is the email body'
)
print("Email sent successfully!")
except Exception as e:
print(f"Failed to send email: {e}")
A Simple Automation Use Case: Sending System Reports via Yagmail
Once you’ve configured Yagmail with a custom SMTP server, it opens up a world of useful automation possibilities. Here’s one that hits close to home for sysadmins and student devs running self-hosted projects: automated reports.
Say you’re managing a local web server, and you want a weekly uptime summary, error log, or backup notification sent to your inbox. With a cron job and a few lines of Python, Yagmail becomes your silent but dependable courier.
Imagine getting this every Monday:
Subject: Backup Report — All Systems Go ✅
Body: Your server completed the weekly backup successfully.
Logs attached. Next backup scheduled: Monday, 2AM.
No dashboard, no manual check-ins. Just email doing what it was meant to do—efficiently, privately, and on your terms.
· · ─ ·𖥸· ─ · ·
Keep Your SMTP Credentials Out of Sight (and Scripts)
Here’s something every student developer learns the hard way: don’t hardcode passwords. Ever. Putting SMTP login details directly in your Python script is like taping your house key to the front door. It might work fine—until it doesn’t.
Instead, use environment variables or a .env
file to store your credentials safely and access them using Python’s built-in os
module. Tools like python-dotenv
make this process even smoother by allowing you to load environment variables from a file during development.
import os
from dotenv import load_dotenv
load_dotenv()
user = os.getenv("SMTP_USER")
password = os.getenv("SMTP_PASSWORD")
This small change instantly makes your script safer to share, publish, or scale—and keeps it aligned with best practices in any FOSS project.
· · ─ ·𖥸· ─ · ·
Take Back Control of Your Email Stack
There’s freedom in knowing exactly where your messages go—and who isn’t reading them.
This guide showed how to unchain Yagmail from Gmail, using your own SMTP archive to send fully customized, automation-ready emails from local or cloud-based environments. Whether you’re scripting reports, building internal tools, or simply tired of OAuth hoops, a self-hosted approach gives you both power and peace of mind.
Ready to build more tools that put privacy first?
Subscribe to the DevDigest newsletter and get practical FOSS walkthroughs straight to your inbox—no surveillance, no spam, just tools that work for people, not platforms.
Leave a Reply