An IMAP library for Rust clients and servers
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
bubblegum f7f7cf1139 docs: rewrite README
Drop the "moved" banner. Add a recorded memstore session, a quick start that actually compiles against the current API (Server::new/with_defaults, listen_tls), and honest support/limits tables: STARTTLS stub, ENVELOPE/BODYSTRUCTURE not returned, MIME part paths, literal cap behaviour.
2026-11-17 14:48:13 +03:00
imap-core fix: make clippy -D warnings pass 2026-11-17 14:41:53 +03:00
imap-server fix(memstore): allow plaintext login 2026-11-17 14:48:13 +03:00
.gitignore chore: ignore local AI-tool files 2026-11-02 23:52:47 +03:00
Cargo.lock Initial Release 2026-07-10 15:48:59 +03:00
Cargo.toml Initial Release 2026-07-10 15:48:59 +03:00
LICENSE Initial commit 2026-07-10 12:43:46 +00:00
README.md docs: rewrite README 2026-11-17 14:48:13 +03:00

imap-rs

An IMAP4rev1 server library for Tokio. You supply the mail storage, and imap-rs handles the protocol.

Quick start · Writing a backend · Protocol support · Limits · Building

imap-rs is a port of the server half of go-imap v2. It has two crates:

Crate What it does Depends on
imap-core Protocol types and a hand-written wire codec tokio only
imap-server Connection state machine and the Backend / UserSession traits imap-core, tokio-rustls, async-trait, tracing

It was written for yggmail-ng, and its regression tests replay the request patterns of real clients (DeltaChat, Tyr).

A real session

The repository includes an in-memory server with five messages in INBOX:

$ cargo run --example memstore
Starting in-memory IMAP server on 127.0.0.1:11443

Here is what a client sees. C: lines are sent by the client and S: lines come from the server (recorded from the example above, unedited):

S: * OK [CAPABILITY CHILDREN ENABLE ID IDLE IMAP4rev1 LITERAL+ MOVE NAMESPACE SASL-IR UIDPLUS UNSELECT] IMAP server ready
C: a1 LOGIN alice secret
S: a1 OK [CAPABILITY CHILDREN ENABLE ID IDLE IMAP4rev1 LITERAL+ MOVE NAMESPACE SASL-IR UIDPLUS UNSELECT] Logged in
C: a2 SELECT INBOX
S: * 5 EXISTS
S: * 0 RECENT
S: * OK [UNSEEN 1] Message(s) unseen
S: * OK [UIDVALIDITY 1] UIDs valid
S: * OK [UIDNEXT 6] Predicted next UID
S: * FLAGS (\Seen \Answered \Flagged \Deleted \Draft \Recent)
S: * OK [PERMANENTFLAGS (\Seen \Answered \Flagged \Deleted \Draft)] Permanent flags
S: a2 OK [READ-WRITE] SELECT completed
C: a3 UID FETCH 1:2 (FLAGS BODY.PEEK[HEADER.FIELDS (SUBJECT)])
S: * 1 FETCH (FLAGS () UID 1 BODY[HEADER.FIELDS (SUBJECT)] {27}
S: Subject: Test Message 1
S:
S: )
S: * 2 FETCH (FLAGS (\Seen) UID 2 BODY[HEADER.FIELDS (SUBJECT)] {27}
S: Subject: Test Message 2
S:
S: )
S: a3 OK FETCH completed
C: a4 LOGOUT
S: * BYE Logging out
S: a4 OK LOGOUT completed

The server answers a BODY.PEEK[...] request with BODY[...], as RFC 3501 §7.4.2 requires. Some clients silently drop messages when this is wrong.

Quick start

imap-rs is not on crates.io. Depend on it from git:

[dependencies]
imap-server = { git = "https://git.shd.company/bubblegum/imap-rs" }
imap-core   = { git = "https://git.shd.company/bubblegum/imap-rs" }
tokio       = { version = "1", features = ["full"] }
rustls      = "0.23"

Serve implicit TLS on port 993:

use std::sync::Arc;
use imap_server::Server;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let tls: Arc<rustls::ServerConfig> = load_certs()?;     // your rustls config
    Server::with_defaults(MyBackend::new())
        .listen_tls("0.0.0.0:993", tls)
        .await
}

Plaintext LOGIN is refused by default: the server advertises LOGINDISABLED and answers NO [PRIVACYREQUIRED]. To allow it on a trusted link such as localhost or an encrypted overlay network, set Options { insecure_auth: true, .. } and use Server::new(backend, options) with listen. To run over any other transport, pass the read and write halves to Server::serve_conn.

Writing a backend

Two traits sit between the protocol and your storage:

#[async_trait]
pub trait Backend: Send + Sync + 'static {
    async fn login(&self, conn: &ConnInfo, username: &str, password: &str)
        -> Result<Box<dyn UserSession>, ImapError>;
}

#[async_trait]
pub trait UserSession: Send + 'static {
    // list, create, delete, rename, status, select, close,
    // fetch, store, search, copy, expunge, append, ...
}
  • Backend is shared by every connection. login checks credentials and returns a session. Reject a login with ImapError::No.
  • UserSession handles one authenticated connection. move_messages (COPY then EXPUNGE), idle, namespace and poll have default implementations.
  • IDLE push: return Some(n) from current_message_count and the server sends * n EXISTS while a client idles. If you return None, IDLE still works but pushes nothing.
  • FETCH bodies: put the whole RFC 5322 message in FetchedMessage.body. The server cuts HEADER, HEADER.FIELDS, TEXT and <offset.size> itself, so do not pre-filter.
  • Errors: ImapError::No and ImapError::Bad become tagged NO and BAD responses. Internal becomes NO [SERVERBUG]. Closed ends the connection.

examples/memstore.rs is a complete backend in about 650 lines.

Protocol support

Status
IMAP4rev1 core: LOGIN, SELECT/EXAMINE, LIST, STATUS, FETCH, STORE, SEARCH, COPY, EXPUNGE, APPEND Supported
AUTHENTICATE PLAIN, with or without an initial response (SASL-IR) Supported
IDLE, MOVE, UIDPLUS, LITERAL+, NAMESPACE, UNSELECT, ENABLE, ID, CHILDREN Supported
Implicit TLS (Server::listen_tls) Supported
STARTTLS Advertised when the backend returns a TLS config, but answers BAD. Not implemented yet
FETCH ENVELOPE, BODYSTRUCTURE Parsed but not returned
FETCH MIME part paths such as BODY[1.2] Return the whole message
IMAP4rev2 No

Limits

Command line 50 KiB
Literal 35 MiB. A larger or negative size closes the connection instead of returning BAD: with LITERAL+ the payload is already on the wire, so the stream cannot be resynced
Read / write timeout 30 s
IDLE timeout 35 min
Any command not allowed before login BYE and disconnect, against cross-protocol attacks

Design notes

  • Hand-written codec. The encoder and decoder in imap-core/src/codec.rs follow go-imap v2. There is no nom and no parser generator.
  • Plain error types. ImapError is an ordinary enum with manual Display, Error and From impls. The crates use neither thiserror nor anyhow.
  • imap-core stays small. Its only dependency is tokio with io-util and sync. Test-only runtime features live in dev-dependencies.

Building

You need stable Rust. imap-server uses rustls, whose default aws-lc-rs backend compiles C code, so you also need a C compiler and CMake (and NASM on Windows). imap-core alone needs none of these.

$ cargo build
$ cargo test
$ cargo clippy --all-targets -- -D warnings

The tests run a real server on a random localhost port. They need no network or external services.

License

MIT