Email with Jennifer: SMTP, IMAP and POP3

Jennifer

Composing, sending, reading and filtering mail with the modules that ship with the interpreter: mime, smtp, imap and pop.

November 2026, by @mplx.
Based on Jennifer 0.27.0

Powered by Jennifer's Cantrip - Markdown into slide decks, https://github.com/jennifer-language/cantrip
1 / 20

How email moves

StepProtocolPortsModule
Your program hands mail to its serverSMTP submission465 TLS, 587 STARTTLSsmtp.j
Server to serverSMTP relay25not your job
Read it, mail stays on the serverIMAP993 TLS, 143 STARTTLSimap.j
Download it, then delete itPOP3995 TLS, 110 STARTTLSpop.j

Bundled, imported by file name: import "imap.j" as imap;, plus transport.j for the Security values.

2 / 20

TLS, STARTTLS and certificates

def s as imap.Session init imap.connect(imap.Options{host: "localhost",
    port: 3993, security: transport.Security.Tls,
    user: "ada@example.org", pass: "changeme", auth: ""});
$ jennifer run parse.j      # test CA not trusted (shortened)
net.NetError{kind: "net", op: "handshake", reason: "tls",
  message: "...: x509: certificate signed by unknown authority"}
3 / 20

Passwords, app passwords, XOAUTH2

def cfg as oauth.Config;
$cfg.tokenUrl = "http://127.0.0.1:18080/token";
$cfg.clientId = "mail-filter";
def tok as oauth.Token init oauth.refresh($cfg,
    os.getEnv("MAIL_REFRESH_TOKEN"));
def s as imap.Session init imap.connect(imap.Options{host: "localhost",
    port: 4143, security: transport.Security.Starttls,
    user: "ada@example.org", pass: $tok.accessToken, auth: "xoauth2"});
token ya29.dem..., expires 1795094622
logged in, INBOX has 0
dovecot: Login: user=<ada@example.org>, method=XOAUTH2, TLS
4 / 20

Composing: a tree of parts

def alt as mime.Part init mime.multipart("alternative", "alt-7f3a", [
    mime.text("text/plain", "The invoice for November is attached."),
    mime.text("text/html", "<p>The invoice for <b>November</b>.</p>")]);
def pdf as mime.Part init mime.attachmentBytes("invoice-2026-11.pdf",
    "application/pdf", fs.readBytes("invoice-2026-11.pdf"));
def msg as mime.Part init mime.multipart("mixed", "mix-91c2", [$alt, $pdf]);
multipart/mixed
  multipart/alternative     plain text and HTML: the reader picks one
    text/plain
    text/html
  application/pdf           base64, Content-Disposition: attachment
5 / 20

Headers and encoded words

$msg = mime.withHeader($msg, "From",
    mime.address("Ada Müller", "ada@example.org"));
$msg = mime.withHeader($msg, "To", "bob@example.com");
$msg = mime.withHeader($msg, "Subject", "Rechnung für November");
$msg = mime.withHeader($msg, "Date",
    time.format(time.now(), "%a, %d %b %Y %H:%M:%S %z"));
$msg = mime.withHeader($msg, "Message-ID", messageId());
$msg = mime.withHeader($msg, "MIME-Version", "1.0");
From: =?UTF-8?B?QWRhIE3DvGxsZXI=?= <ada@example.org>
Subject: =?UTF-8?B?UmVjaG51bmcgZsO8ciBOb3ZlbWJlcg==?=
Date: Thu, 19 Nov 2026 13:23:32 +0100
Message-ID: <7f225df017205d770d7c3b66@example.org>
6 / 20

Sending: envelope and headers

def opts as smtp.Options init smtp.Options{host: "localhost", port: 1587,
    security: transport.Security.Starttls, clientName: "app.example.org",
    user: "ada@example.org", pass: "changeme", auth: "auto",
    allowInsecureAuth: false};
# envelope: the bounce address and every recipient, Bcc included
smtp.send($opts, "bounces@example.org",
    ["bob@example.com", "carol@example.com"], mime.encode($msg));
headers:  From: Ada <ada@example.org>   To: Bob <bob@example.com>
Mailpit:  Return-Path: <bounces@example.org>   Bcc: carol@example.com
7 / 20

One session, many mails

def s as smtp.Session init smtp.open($opts);
for (def m in $mails) {
    smtp.sendOn($s, "bob@example.com", ["ada@example.org"], build($m));
    io.printf("queued: %s\n", $m.subject);
}
smtp.close($s);
queued: Black Friday: 30% off
queued: Board meeting moved to 3 pm
queued: Invoice 2026-11
queued: You have won
queued: Weekly digest #47
queued: Lunch on Friday?
8 / 20

IMAP: select, search, fetch headers

io.printf("INBOX: %d messages\n", imap.selectFolder($s, "INBOX"));
def c as imap.Criteria init imap.criteria();
$c.unseen = true;
for (def uid in imap.search($s, $c)) {
    def h as mime.Part init mime.parse(
        imap.fetchHeaders($s, $uid, "FROM SUBJECT"));
    io.printf("%d  %s|pad=22 %s\n", $uid, mime.headerValue($h, "From"),
        mime.headerValue($h, "Subject"));
}
INBOX: 7 messages
1  news@shop.example.com  Black Friday: 30% off
2  boss@example.org       Board meeting moved to 3 pm
9 / 20

Whole messages, flags, move, delete

imap.addFlags($s, $uid, "\\Seen \\Answered");
io.printf("flags: %s\n", imap.flags($s, $uid));
imap.removeFlags($s, $uid, "\\Seen");              # unread again
imap.move($s, $uid, "Archive");                     # atomic MOVE
imap.addFlags($s, 3, "\\Deleted");                  # mark ...
imap.expunge($s);                                   # ... then remove
imap.appendWith($s, "Sent", "\\Seen", mime.encode($reply));
flags: \Answered \Seen
flags: \Answered
Archive      1 messages, 1 unseen, next uid 2
Sent         1 messages, 0 unseen, next uid 2
10 / 20

IDLE: wait for new mail

while ($rounds < 3) {
    imap.idle($s);
    def n as imap.Notification init imap.pollNotification($s, 20000);
    imap.done($s);
    if ($n.kind == "exists") {
        io.printf("push: %d messages\n", $n.number);
        newMail($s);       # search unseen, fetch headers, mark seen
    }
    $rounds = $rounds + 1;
}
IDLE supported: true
push: 3 messages
new: 8 ping 1
11 / 20

POP3: download, delete, remember UIDL

for (def m in pop.uidl($s)) {
    if (lists.contains($seen, $m.id)) { continue; }
    def msg as mime.Part init mime.parse(pop.retrieve($s, $m.number));
    io.printf("#%d %s  %s\n", $m.number, $m.id,
        mime.headerValue($msg, "Subject"));
    fs.appendString(SEEN_FILE, $m.id + "\n");
    if (strings.startsWith(mime.headerValue($msg, "Subject"), "old")) {
        pop.deleteMessage($s, $m.number);
    }
}
pop.quit($s);   # deletions happen here
run 2: #3 5 old report  #4 6 status update  #5 7 old newsletter
12 / 20

Parsing a received message

def msg as mime.Part init imap.fetchMessage($s, $uid);
io.printf("Subject: %s\n", mime.headerValue($msg, "Subject"));
for (def p in mime.walk($msg)) {
    io.printf("  %s|pad=18 %s|pad=10 %d bytes %s\n", mime.contentType($p),
        mime.disposition($p), len(mime.data($p)), mime.filename($p));
}
def plain as list of mime.Part init mime.findParts($msg, "text/plain");
Subject: Rechnung für November
  text/plain                    37 bytes
  text/html                     39 bytes
  application/pdf    attachment 193 bytes invoice-2026-11.pdf
text: The invoice for November is attached.
13 / 20

Attachments: never trust the name

func safeName(raw as string) {
    def n as string init regex.replace('[^A-Za-z0-9._-]', $raw, "_");
    $n = regex.replace('^[._]+', $n, "");
    if (len($n) > 80) { $n = $n[len($n) - 80..]; }
    if ($n == "") { $n = "attachment"; }
    return $n;
}
"../../.config/autostart/run.pdf"  -> config_autostart_run.pdf
"C:\Windows\evil.pdf"              -> C__Windows_evil.pdf
".bashrc"                          -> bashrc
"Rechnung März.pdf"                -> Rechnung_M_rz.pdf
""                                 -> attachment
14 / 20

Saving invoices with caps

func saveInvoices(s as imap.Session, uid as int) {
    for (def att in mime.attachments(imap.fetchMessage($s, $uid))) {
        def data as bytes init mime.data($att);
        if (not isPdf($data) or len($data) > MAX_PDF) {
            io.printf("    skipped %s\n", mime.filename($att));
            continue;
        }
        def name as string init "{DIR}/{$uid}-" +
            safeName(mime.filename($att));
        fs.writeNew($name, $data);   # throws instead of overwriting
        io.printf("    saved %s\n", $name);
    }
}
15 / 20

An inbox filter: the rules

func action(s as imap.Session, uid as int, tooBig as list of int) {
    def h as mime.Part init mime.parse(imap.fetchHeaders($s, $uid,
        "FROM LIST-ID X-SPAM-FLAG"));
    def from as string init addrOf(mime.headerValue($h, "From"));
    def spam as string init mime.headerValue($h, "X-Spam-Flag");
    if (strings.upper($spam) == "YES") { return "spam"; }
    if (mime.headerValue($h, "List-Id") != "") { return "newsletter"; }
    if (lists.contains(VIPS, $from)) { return "vip"; }
    if ($from == BILLING and not lists.contains($tooBig, $uid)) {
        return "invoice";
    }
    return "keep";
}
16 / 20

An inbox filter: the run

for (def uid in imap.search($s, imap.criteria())) {
    def what as string init action($s, $uid, $tooBig);
    io.printf("%d  %s\n", $uid, $what);
    match ($what) {
        when "spam" { imap.addFlags($s, $uid, "\\Deleted"); }
        when "newsletter" { imap.move($s, $uid, "Newsletters"); }
        when "vip" { imap.addFlags($s, $uid, "\\Flagged"); }
        when "invoice" { saveInvoices($s, $uid); }
    }
}
imap.expunge($s);
1 newsletter  2 vip  3 invoice (saved)  4 spam  5 newsletter  6 keep
7 invoice: skipped ../../.config/autostart/run.pdf
17 / 20

Errors you will actually see

CaseKindFields worth reading
SMTP wrong passwordsmtpcode 535, command AUTH PLAIN
SMTP auth over Nonesmtpcode 0: refused before sending
No STARTTLS offeredsmtpcode 0
IMAP move, no folderimapstatus NO, TRYCREATE
POP3 wrong passwordpop3command PASS
Server downnetreason refused
18 / 20

Security and limits

Subject: HelloBcc: everyone@example.com
19 / 20

Wrap-up

Docs: smtp, imap, pop, mime, sasl

20 / 20