惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Threatpost
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
S
Security Affairs
N
News and Events Feed by Topic
T
Tenable Blog
P
Proofpoint News Feed
W
WeLiveSecurity
Simon Willison's Weblog
Simon Willison's Weblog
Google DeepMind News
Google DeepMind News
C
CERT Recently Published Vulnerability Notes
Help Net Security
Help Net Security
I
Intezer
T
Threat Research - Cisco Blogs
S
Secure Thoughts
C
Cyber Attacks, Cyber Crime and Cyber Security
L
Lohrmann on Cybersecurity
AWS News Blog
AWS News Blog
Google Online Security Blog
Google Online Security Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Know Your Adversary
Know Your Adversary
Project Zero
Project Zero
The Hacker News
The Hacker News
Security Archives - TechRepublic
Security Archives - TechRepublic
T
Tor Project blog
N
News | PayPal Newsroom
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Hacker News - Newest:
Hacker News - Newest: "LLM"
A
Arctic Wolf
Forbes - Security
Forbes - Security
O
OpenAI News
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Security Latest
Security Latest
P
Palo Alto Networks Blog
S
Schneier on Security
S
Securelist
C
Cybersecurity and Infrastructure Security Agency CISA
H
Heimdal Security Blog
V
Vulnerabilities – Threatpost
www.infosecurity-magazine.com
www.infosecurity-magazine.com
博客园_首页
T
Troy Hunt's Blog
Latest news
Latest news
Recent Announcements
Recent Announcements
MyScale Blog
MyScale Blog
人人都是产品经理
人人都是产品经理
L
LINUX DO - 热门话题
M
MIT News - Artificial intelligence
N
Netflix TechBlog - Medium
V
Visual Studio Blog
H
Hacker News: Front Page

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work Top 15 Reinforcement Learning Questions That Will Appear in Exams The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design
Fernando Cel · 2026-04-18 · via DEV Community

The Problem

If you've ever tried to read or send emails with Python, you know the pain:

# The old way
import imaplib
import email

mail = imaplib.IMAP4_SSL("imap.gmail.com")
mail.login("user@gmail.com", "password")
mail.select("inbox")
_, data = mail.search(None, "UNSEEN")
for num in data[0].split():
    _, msg_data = mail.fetch(num, "(RFC822)")
    msg = email.message_from_bytes(msg_data[0][1])
    # now manually decode headers, parse body, handle attachments...

Low-level, verbose, and error-prone. You spend more time fighting the protocol than solving your actual problem.

And this is just for reading. If you want to send an HTML email with attachments, you're deep into MIMEMultipart, MIMEText, MIMEBase, encoders.encode_base64... pages of boilerplate before you even get to your actual logic.

Python's standard library gives you the building blocks, but it never gives you the house.

Why I Built This

I was working on a project that needed to automate email workflows — read incoming messages, extract attachments, reply programmatically, and back everything up. After writing the same IMAP boilerplate for the third time across different projects, I decided to build something better.

The goals were simple:

  • Zero configuration for common providers — just pass an email address and password
  • A Django ORM-like query API — composable, readable, Pythonic
  • Lazy evaluation — don't fetch 10,000 emails when you only need a count
  • Pydantic models everywhere — type-safe, serializable, predictable
  • One library for everything — read, send, search, reply, forward, backup

The result is email-profile.

Meet email-profile

pip install email-profile

from email_profile import Email

with Email("user@gmail.com", "app-password") as app:
    for msg in app.unread().messages():
        print(f"{msg.from_}: {msg.subject}")

That's it. 3 lines to read your unread emails. No server configuration, no manual connection handling, no protocol-level code.

Key Features

Auto-Discovery for 35+ Providers

No more googling "what's the IMAP server for Outlook?". Just pass your email address:

# Gmail, Outlook, Yahoo, iCloud, ProtonMail, Zoho...
# Server settings are auto-discovered
app = Email("user@outlook.com", "password")

It uses a 4-tier resolution strategy:

  1. Hard-coded provider map — Gmail, Outlook, Yahoo, iCloud, and 30+ others are mapped directly
  2. RFC 6186 SRV DNS lookups — standard service discovery for domains that support it
  3. MX record inference — extracts the provider from MX records and maps to known IMAP hosts
  4. Convention fallback — tries imap.<domain> and smtp.<domain> as a last resort

This means even custom domains hosted on known providers (like a company email on Google Workspace) are resolved automatically.

Powerful Search with Q & Query

If you've used Django's ORM, this will feel familiar. The Q class provides static methods that return composable expressions:

from email_profile import Q
from datetime import date

# Combine with & (AND), | (OR), ~ (NOT)
q = Q.from_("boss@company.com") & Q.subject("urgent") & Q.since(date(2025, 1, 1))

for msg in app.inbox.where(q).messages():
    print(msg.subject)

Available Q methods include Q.from_(), Q.subject(), Q.unseen(), Q.seen(), Q.since(), Q.before(), Q.larger(), and more. They can be combined freely with &, |, and ~ operators.

For simpler cases, use kwargs-style queries with Query:

from email_profile import Query

results = app.inbox.where(Query(subject="invoice", unseen=True))
print(f"Found {results.count()} unread invoices")

Query also supports chaining with .exclude() and .or_():

q = Query(subject="report").exclude(from_who="spam@example.com").or_(subject="invoice")
messages = app.inbox.where(q).list()

Send Emails (Plain Text, HTML, Attachments)

Sending is just as clean. Plain text, HTML, attachments, CC, BCC — all in one call:

app.send(
    to="team@company.com",
    subject="Weekly Report",
    html="<h1>Report</h1><p>All systems operational.</p>",
    attachments=["report.pdf", "metrics.csv"]
)

You can also send both plain text and HTML as a multipart message:

app.send(
    to="recipient@example.com",
    subject="Update",
    body="Plain text fallback for clients that don't render HTML.",
    html="<h1>Update</h1><p>Rich version of the same content.</p>"
)

Note that html is a string parameter (the HTML content itself), not a boolean flag. This is a deliberate design choice — it keeps the API explicit and avoids ambiguity.

Reply & Forward

Reply and forward are methods on the Email object, not on the message. This keeps Message as a pure data object (Pydantic model) with no side effects:

# Reply to sender only
app.reply(msg, body="Thanks, I'll review it today!")

# Reply all
app.reply(msg, body="Acknowledged.", reply_all=True)

# Forward
app.forward(msg, to="colleague@company.com", body="FYI - please take a look")

Mailbox Management

Access standard folders via properties, or reach any custom folder by path:

# Built-in shortcuts
app.inbox
app.sent
app.spam
app.trash
app.drafts
app.archive

# Custom folders
reports = app.mailbox("Projects/Reports")

Flag operations live on the mailbox, not the message. They accept a Message, a UID string, or an integer:

app.inbox.mark_seen(msg)
app.inbox.mark_unseen(msg)
app.inbox.flag(msg)
app.inbox.unflag(msg)
app.inbox.move(msg, "Archive")
app.inbox.copy(msg, "Backup")
app.inbox.delete(msg)

This design means you can operate on messages from any context — even messages loaded from a backup — without needing an active connection reference on the message object itself.

Sync & Backup to SQLite

Back up your entire mailbox to a local SQLite database with incremental sync:

from email_profile import StorageSQLite

app = Email("user@gmail.com", "password")
app.storage = StorageSQLite("backup.db")

with app:
    result = app.sync()  # incremental — only downloads new emails
    print(f"{result.inserted} new, {result.skipped} skipped")

The SyncResult object gives you full visibility: inserted, updated, deleted, skipped, and errors. Restore is just as simple:

with app:
    count = app.restore()  # returns int (count of restored messages)
    print(f"Restored {count} messages")

Lazy Evaluation

Queries return a Where object — nothing hits the server until you explicitly ask for data. This is critical for performance when working with large mailboxes:

query = app.inbox.where(Q.unseen())

# No IMAP call yet — the query is just a description
query.count()       # hits the server, returns int
query.exists()      # bool — cheaper than count for "any unread?" checks
query.first()       # Message or None — fetches only one
query.last()        # Message or None — fetches only one
query.list()        # list[Message] — materializes everything
query.messages()    # iterator — memory-efficient for large result sets

This means app.inbox.where(Q.unseen()).count() only asks the server "how many?", without downloading a single message body.

Fetch Modes

Control how much data you pull per message. This makes a huge difference when you're scanning thousands of emails:

# Full message + attachments (default)
app.inbox.where().messages(mode="full")

# Headers + body, skip attachments (faster)
app.inbox.where().messages(mode="text")

# Headers only (cheapest — great for building an index)
app.inbox.where().messages(mode="headers")

For example, if you're building a dashboard that shows subject lines and dates, use mode="headers" and save 90%+ of bandwidth.

Message as a Pydantic Model

Every message is a Message object — a Pydantic BaseModel with typed fields:

from email_profile import Message

for msg in app.inbox.where(unseen=True).messages():
    msg.subject          # str
    msg.from_            # str
    msg.to_              # str
    msg.date             # datetime
    msg.uid              # str
    msg.message_id       # str
    msg.body_text_plain  # Optional[str]
    msg.body_text_html   # Optional[str]
    msg.cc               # Optional[str]
    msg.bcc              # Optional[str]
    msg.reply_to         # Optional[str]
    msg.in_reply_to      # Optional[str]
    msg.references        # Optional[str]
    msg.content_type     # str
    msg.attachments      # list[Attachment]
    msg.headers          # dict
    msg.list_id          # Optional[str]
    msg.list_unsubscribe # Optional[str]

Because it's Pydantic, you get .model_dump(), .model_dump_json(), validation, and serialization for free. This makes it trivial to pipe email data into APIs, databases, or AI workflows.

Real-World Recipes

Monitor inbox for new messages

with Email.from_env() as app:
    for msg in app.unread().messages():
        print(f"From: {msg.from_} | Subject: {msg.subject}")
        app.inbox.mark_seen(msg)

Download PDF attachments from invoices

with Email("user@gmail.com", "password") as app:
    for msg in app.search("invoice").messages():
        for att in msg.attachments:
            if att.content_type == "application/pdf":
                att.save("./invoices/")

Backup all emails to SQLite

from email_profile import StorageSQLite

app = Email("user@gmail.com", "password")
app.storage = StorageSQLite("full_backup.db")

with app:
    result = app.sync()
    print(f"Backed up {result.inserted} new emails")

Clean up spam folder

with Email.from_env() as app:
    for msg in app.spam.where().messages():
        app.spam.delete(msg)

Search across date ranges

from datetime import date
from email_profile import Q

with Email.from_env() as app:
    q = Q.since(date(2025, 1, 1)) & Q.before(date(2025, 4, 1)) & Q.from_("client@company.com")
    messages = app.inbox.where(q).list()
    print(f"Found {len(messages)} emails from client in Q1 2025")

Use environment variables

# .env
EMAIL_SERVER=imap.gmail.com
EMAIL_USERNAME=user@gmail.com
EMAIL_PASSWORD=app-password

with Email.from_env() as app:
    print(f"Connected as {app.user}")

You can also customize the variable names:

app = Email.from_env(
    server_var="MY_IMAP_HOST",
    user_var="MY_EMAIL",
    password_var="MY_EMAIL_PW"
)

Built-in Error Handling & Retry

The library provides specific exception classes so you can handle failures gracefully:

from email_profile import ConnectionFailure, NotConnected, QuotaExceeded, RateLimited

try:
    app.connect()
except ConnectionFailure:
    print("Could not connect to server")
except QuotaExceeded:
    print("Mailbox quota exceeded")
except RateLimited:
    print("Too many requests — back off and retry")

For automated workflows, use the built-in retry decorator:

from email_profile.retry import with_retry

@with_retry(attempts=3, initial_delay=1.0, max_delay=30.0)
def fetch_unread():
    with Email.from_env() as app:
        return app.unread().list()

It handles exponential backoff automatically, so your scripts survive transient network issues without custom retry logic.

Why email-profile?

Auto-discovery No 35+ providers Context manager No Yes Search API Raw IMAP commands Q objects & Query kwargs Send HTML Manual MIME building html="<h1>..." Attachments Manual encoding attachments=["file.pdf"] Reply/Forward Build from scratch app.reply(msg, body="...") Backup/Sync DIY StorageSQLite built-in Lazy evaluation No Where objects Retry logic DIY @with_retry decorator Pydantic models No Message DTO Fetch modes Manual flags mode="full/text/headers"
Feature imaplib/smtplib email-profile

Design Principles

A few decisions that shape the library:

  • Message is data, not behavior. Message is a pure Pydantic model. It has no methods that mutate state or require a connection. Operations like mark_seen(), move(), and delete() live on the mailbox. This keeps the model serializable and testable.

  • Lazy by default. .where() returns a Where object, not a list. You choose when and how to materialize: .count(), .first(), .list(), or .messages(). This prevents accidentally downloading thousands of emails.

  • One import, one object. For most use cases, from email_profile import Email is all you need. The Email class is the entry point for connecting, reading, sending, replying, forwarding, and syncing.

  • Fail explicitly. Instead of generic exceptions, the library provides ConnectionFailure, NotConnected, QuotaExceeded, and RateLimited — so you can handle each case differently.

Getting Started

pip install email-profile

from email_profile import Email

with Email("your@email.com", "app-password") as app:
    # Read
    for msg in app.unread().messages():
        print(msg.subject)

    # Send
    app.send(to="friend@email.com", subject="Hello!", body="Sent with email-profile")

Links

The library is in active development and we'd love your feedback. Star the repo, open issues, or contribute — every bit helps!

What do you think? Would you use this in your projects? Drop a comment below!