How to receive email in Python and Node.js

To receive email in Python or Node.js, read an existing mailbox over IMAP, accept mail on your own SMTP server, take webhooks from a mail service, or call an inbox API that waits for the next message. IMAP suits a mailbox you already have. An inbox API suits software that needs its own address.

Updated

Which way should you use to receive email?

WayYou needHow new mail reaches youBest for
IMAPA mailbox and its credentialsYou check, or hold an IDLE connectionMail that already goes to a mailbox
Your own SMTP receiverA domain, an MX record, a server open on port 25Other servers deliver to youFull control, and all the work with it
WebhookA public HTTPS endpointThe mail service posts to youA server that is always on
Inbox API long pollAn API keyOne request that waitsScripts, AI agents and tests

How do you receive email in Python over IMAP?

The standard library is enough. Set IMAP_HOST, IMAP_USER and IMAP_PASSWORD. Many providers want OAuth or an app password here, not your account password.

imap_receive.py
import email
import imaplib
import os
import ssl
from email.policy import default

HOST = os.environ["IMAP_HOST"]
PORT = int(os.environ.get("IMAP_PORT", "993"))
# Without this context, imaplib encrypts but does not check the server's certificate.
TLS = ssl.create_default_context()

with imaplib.IMAP4_SSL(HOST, PORT, ssl_context=TLS) as imap:
    imap.login(os.environ["IMAP_USER"], os.environ["IMAP_PASSWORD"])
    imap.select("INBOX")
    _, data = imap.uid("search", None, "UNSEEN")

    for uid in data[0].split():
        # BODY.PEEK reads the message without marking it as seen.
        _, parts = imap.uid("fetch", uid, "(BODY.PEEK[])")
        msg = email.message_from_bytes(parts[0][1], policy=default)
        body = msg.get_body(preferencelist=("plain", "html"))

        print(msg["from"], "|", msg["subject"])
        print(body.get_content() if body else "")

        imap.uid("store", uid, "+FLAGS", "(\\Seen)")  # only after you handled it

Pass the TLS context. Python's documentation says that with the default context, imaplib encrypts the connection but does not verify the server's certificate or hostname. ssl.create_default_context() turns both checks on. In our test it rejected a self-signed certificate.

How do you receive email in Node.js over IMAP?

Node has no built-in IMAP client. Install one and a parser with npm install imapflow mailparser. Save the file as .mjs. Tested with imapflow 2.12.2 and mailparser 3.15.2.

imap_receive.mjs
import { ImapFlow } from "imapflow";
import { simpleParser } from "mailparser";

const client = new ImapFlow({
  host: process.env.IMAP_HOST,
  port: Number(process.env.IMAP_PORT ?? 993),
  secure: true,
  auth: { user: process.env.IMAP_USER, pass: process.env.IMAP_PASSWORD },
  logger: false,
});

await client.connect();
const lock = await client.getMailboxLock("INBOX");
try {
  const unseen = (await client.search({ seen: false }, { uid: true })) || [];
  for (const uid of unseen) {
    const { source } = await client.fetchOne(uid, { source: true }, { uid: true });
    const msg = await simpleParser(source);

    console.log(msg.from?.text, "|", msg.subject);
    console.log(msg.text ?? "");

    await client.messageFlagsAdd(uid, ["\\Seen"], { uid: true });
  }
} finally {
  lock.release();
}
await client.logout();

How do you get new mail without polling IMAP?

IMAP has an IDLE command: the server tells you when the mailbox changes. Python gained IMAP4.idle() in version 3.14:

imap_idle.py
import imaplib
import os
import ssl

# Python 3.14 or newer.
with imaplib.IMAP4_SSL(os.environ["IMAP_HOST"], int(os.environ.get("IMAP_PORT", "993")),
                       ssl_context=ssl.create_default_context()) as imap:
    imap.login(os.environ["IMAP_USER"], os.environ["IMAP_PASSWORD"])
    imap.select("INBOX")
    with imap.idle(duration=25 * 60) as idler:  # start again before 29 minutes
        for kind, data in idler:
            if kind == "EXISTS":  # the mailbox grew
                print("new mail, message count:", data[0].decode())
                break

In Node, imapflow idles by itself while a mailbox is open. Call client.mailboxOpen("INBOX") and listen with client.on("exists", handler). Either way, reconnect when the connection drops and then search for unseen mail, so nothing that arrived in the gap is lost.

How do you read attachments?

In Python, add this inside the loop. In Node, msg.attachments holds the same files.

python
for part in msg.iter_attachments():
    data = part.get_payload(decode=True)
    print(part.get_filename(), part.get_content_type(), len(data))
    # The sender chose the filename. Never use it as a path.

How do you run your own SMTP receiver in Node.js?

Run npm install smtp-server mailparser. In production, point your domain's MX record at the machine and listen on port 25.

smtp_receive.mjs
import { readFileSync } from "node:fs";
import { SMTPServer } from "smtp-server";
import { simpleParser } from "mailparser";

const server = new SMTPServer({
  // Without your own files the library uses a built-in certificate whose key is public.
  key: readFileSync(process.env.TLS_KEY),
  cert: readFileSync(process.env.TLS_CERT),
  authOptional: true, // mail from other servers arrives without a login
  disabledCommands: ["AUTH"],
  size: 10 * 1024 * 1024,
  onRcptTo(address, session, done) {
    // Accept your own addresses and nothing else, or you become an open relay.
    if (address.address.toLowerCase() === "riley@trotta.io") return done();
    done(Object.assign(new Error("No such mailbox"), { responseCode: 550 }));
  },
  onData(stream, session, done) {
    simpleParser(stream)
      .then((msg) => {
        if (stream.sizeExceeded) throw Object.assign(new Error("Too big"), { responseCode: 552 });
        console.log(msg.from?.text, "|", msg.subject);
        console.log(msg.text ?? "");
        done();
      })
      .catch(done);
  },
});

server.listen(Number(process.env.PORT ?? 2525));

Set TLS_KEY and TLS_CERT to your key and certificate files. Then send it a message from Python:

python
import smtplib
from email.message import EmailMessage

m = EmailMessage()
m["From"], m["To"], m["Subject"] = "jordan@trotta.email", "riley@trotta.io", "Test"
m.set_content("Hello over SMTP.")

with smtplib.SMTP("127.0.0.1", 2525) as smtp:
    smtp.starttls()
    smtp.send_message(m)

This receives and nothing more. It does not check SPF, DKIM or DMARC, filter spam or scan attachments, and anyone on the internet can reach it. Those jobs are now yours, along with uptime and backups.

How do you wait for new email with an inbox API?

The service runs the mail server, and you make a request that returns when a message arrives. With Trotta Mail, run pip install trottamail, then set TROTTA_MAIL_API_KEY and INBOX_ID. One call creates both.

wait_loop.py
import os
from datetime import datetime, timezone

from trottamail import MessageHeldError, TrottaMail

mail = TrottaMail()  # reads TROTTA_MAIL_API_KEY
inbox_id = os.environ["INBOX_ID"]
after = datetime.now(timezone.utc).isoformat()

while True:
    try:
        msg = mail.inboxes.wait(inbox_id, timeout=60, after=after)
    except MessageHeldError as err:
        print("held for a human:", err.held["id"])
        after = err.held["id"]
        continue
    if msg is None:
        continue  # nothing yet, wait again
    print(msg["from"]["address"], "|", msg["subject"])
    print(msg["extracted_text"] or msg["text"])
    after = msg["id"]  # store this to resume after a restart

The same loop in Node.js 18 or newer needs no packages:

wait_loop.mjs
const API = "https://api.trotta.email/v1";
const headers = { authorization: `Bearer ${process.env.TROTTA_MAIL_API_KEY}` };
const inbox = process.env.INBOX_ID;
let after = new Date().toISOString();

for (;;) {
  const query = new URLSearchParams({ timeout: "60", after });
  const res = await fetch(`${API}/inboxes/${inbox}/wait?${query}`, { headers });
  if (!res.ok) throw new Error(`wait failed: ${res.status} ${await res.text()}`);

  const { message, held } = await res.json();
  if (held) {
    console.log("held for a human:", held.id);
    after = held.id;
  } else if (message) {
    console.log(message.from.address, "|", message.subject);
    console.log(message.extracted_text ?? message.text);
    after = message.id; // store this to resume after a restart
  }
}

One request holds for up to 60 seconds. A message the guard is holding comes back as a notice with no content, so both loops skip past it and tell you. extracted_text is the new part, without quoted history or signature. Trotta Mail does not offer IMAP.

What about webhooks?

A webhook posts each new message to your HTTPS URL, so nothing has to wait. Verify the signature over the raw body before you trust it, and expect the same event more than once. Webhooks vs polling has receivers in TypeScript and Python and the retry schedule.

What goes wrong when software reads email?

  • Handling a message twice. Mark it only after you processed it, and make processing safe to repeat.
  • Reading the wrong part. Plain and HTML parts can say different things. See email to LLM-ready text.
  • Trusting the From line. The sender types it.
  • Unbounded size. Cap what you load and what you pass on.
  • Duplicates. The same message can reach you twice, from a retried webhook or a restarted loop. Remember the IDs you finished.
  • Answering machines. An automatic reply to an autoresponder can start a loop. Skip automated mail and cap replies per thread.
  • Losing your place. Store the last message ID or UID you handled, so a restart neither skips mail nor starts from the top.
  • Feeding mail to a model. Incoming text can carry instructions. See prompt injection in email agents.

Questions

Can Python receive email without IMAP?

Yes. Run your own SMTP receiver, take webhooks from a mail service, or call an inbox API that waits for messages.

What is the difference between IMAP and SMTP for receiving?

SMTP delivers mail from one server to another. IMAP lets a program read mail already delivered to a mailbox.

Can I receive email on localhost?

Your SMTP receiver accepts local test messages, as above. Mail from the internet needs a public address, an MX record and an open port 25.

How do I get notified of new mail in real time?

Use IMAP IDLE on a mailbox, or a webhook, event stream or waiting call from a mail service.

Sources

Give your agent an inbox of its own. Free for three agent inboxes and you. No card.