Rust

SMTP

An async SMTP client: STARTTLS and implicit TLS, PLAIN, LOGIN and XOAUTH2, partial recipient refusal, and MIME messages with attachments built for the wire.
Rust 3,402 lines (2,083 code)split
PartCodeCommentsBlankTotalFiles
Rust source2,0831,0352843,40216

Comments include doc comments. Rust tests are tests/ and #[cfg(test)] modules.

Install#

The crate lives in the Appwrite repository; depend on it from Git.

Cargo.toml
[dependencies]
utopia-smtp = { git = "https://github.com/appwrite/appwrite" }

Getting started#

Common tasks with SMTP, each a complete program you can copy and run.

utopia-smtp submits mail to a server you configure: it builds the message (headers, MIME tree, attachments, encodings), opens the session (STARTTLS or implicit TLS, then authentication), and reports which recipients the server took. One Client is one connection, reopened after it is dropped.

Build a message

A message picks its MIME structure from what you give it: one text part, multipart/alternative for text and HTML, multipart/related for inline images and multipart/mixed for attachments. Blind recipients go in the envelope, never in a header.

Rust
use utopia_smtp::{Address, Attachment, Date, Message};

let message = Message::builder(Address::new("jane@example.test", "Jane Doe")?, "Quarterly report")
    .to(Address::new("john@example.test", "John")?)
    .bcc(Address::new("audit@example.test", "")?)
    .text("The numbers are in.")
    .html("<p>The numbers are in.</p>")
    .attachment(Attachment::from_bytes(b"1,2,3".to_vec(), "numbers.csv", Some("text/csv"))?)
    .date(Date::new(1_786_613_400, 0))
    .build()?;

let rendered = String::from_utf8(message.to_bytes()?).unwrap();
assert!(rendered.contains("Content-Type: multipart/mixed;"));
assert!(!rendered.contains("audit@example.test"));

Send it

A Client over a TcpTransport connects on first use. Encryption::StartTls refuses a server without STARTTLS; authenticators are tried in order against the mechanisms the server offers. A server may refuse some recipients and take the others: the Delivery says which.

Rust
use utopia_smtp::auth::Plain;
use utopia_smtp::{Address, Client, Encryption, Message, TcpTransport, Tls};

let transport = TcpTransport::new("smtp.example.test", 587, Tls::default());
let mut client = Client::new(transport)
    .with_domain("app.example.test")
    .with_authenticator(Plain::new("jane", "secret"))
    .with_encryption(Encryption::StartTls);

let message = Message::builder(Address::new("jane@example.test", "")?, "Hello")
    .to(Address::new("john@example.test", "")?)
    .text("Hi John")
    .build()?;

let delivery = client.send(&message).await?;
for (recipient, reply) in &delivery.rejected {
    eprintln!("{recipient} refused: {reply}");
}
client.close().await;
Compiles in CI; needs a running service to execute.

Plug in your own transport

Transport moves bytes and nothing else; line assembly and the reply grammar live in the client. Implement it to tunnel SMTP through something else, or to script a server in a test.

Rust
use std::time::Duration;
use utopia_smtp::{Client, Encryption, Envelope, Error, Transport};

#[derive(Default)]
struct Scripted {
    replies: Vec<u8>,
    written: Vec<u8>,
}

impl Transport for Scripted {
    async fn connect(&mut self, _: Duration, _: bool) -> Result<(), Error> {
        Ok(())
    }
    async fn read(&mut self, buffer: &mut Vec<u8>, length: usize, _: Duration) -> Result<usize, Error> {
        let n = length.min(self.replies.len());
        if n == 0 {
            return Err(Error::Connection("The server closed the connection".into()));
        }
        buffer.extend(self.replies.drain(..n));
        Ok(n)
    }
    async fn write(&mut self, data: &[u8], _: Duration) -> Result<(), Error> {
        self.written.extend_from_slice(data);
        Ok(())
    }
    async fn start_tls(&mut self, _: Duration) -> Result<(), Error> {
        Ok(())
    }
    fn is_tls(&self) -> bool {
        false
    }
    fn close(&mut self) {}
}

let server = Scripted {
    replies: b"220 hi\r\n250 hello\r\n250 ok\r\n250 ok\r\n354 go\r\n250 Ok: queued as ABC\r\n".to_vec(),
    ..Scripted::default()
};
let mut client = Client::new(server).with_encryption(Encryption::None);
let envelope = Envelope::new("jane@example.test", ["john@example.test"])?;

let delivery = client.send_raw(&envelope, b"Subject: Hi\r\n\r\n.Body").await?;
assert_eq!(delivery.message_id, "ABC");
assert!(client.transport().written.ends_with(b"DATA\r\nSubject: Hi\r\n\r\n..Body\r\n.\r\n"));

Read what the server says

Replies carry their class and enhanced status code, and a refused transaction keeps the reply (and each recipient's refusal) on the error, so a caller can tell a retry from a bounce.

Rust
use utopia_smtp::{Capabilities, Outcome, Reply};

let ehlo = Reply::new(250, ["mail.example.test", "SIZE 35882577", "AUTH PLAIN LOGIN", "STARTTLS"])?;
let capabilities = Capabilities::from_reply(&ehlo);
assert!(capabilities.has("starttls"));
assert_eq!(capabilities.max_size(), Some(35_882_577));

let busy = Reply::new(450, ["4.2.1 Mailbox busy"])?;
assert_eq!(busy.outcome(), Outcome::Transient);
assert_eq!(busy.status(), Some("4.2.1"));

Reference#

An async SMTP client for submitting mail to a configured server: STARTTLS and implicit TLS, PLAIN, LOGIN and XOAUTH2, partial recipient refusal, and MIME messages (text, HTML, attachments, inline images) built for the wire.

One Client is one connection, over a [Transport]: TcpTransport (tokio and rustls), or any implementation of the trait. Messages are streamed: an attachment read from disk is encoded block by block while it is sent.

Modules#

Each module groups one concept of the library. Internal ones hold items the crate re-exports at its root.

API#

What utopia_smtp exports at its root.

Structs

AddressA mailbox: an address with an optional display name.AttachmentA file to carry along, either held in memory or read from disk when the message is written, so a large file is never held twice.CapabilitiesWhat the server advertised in its EHLO reply: each keyword, upper-cased, with its parameters.ClientAn RFC 5321 client submitting mail to one server, over one connection, opened on first use and reopened after it was dropped.DateA point in time with the UTC offset it is written in, for the `Date` header.DeliveryWhat one send achieved. RFC 5321 lets a server refuse some recipients and accept others, and the message still reaches the rest.EnvelopeWhere the bytes go, which is not the same question as what the headers say: the reverse-path (`MAIL FROM`) and the forward-paths (`RCPT TO`).MessageAn RFC 5322 message, with the MIME structure chosen from what was set: one text part, or `multipart/alternative` for text and HTML, inside `multipart/related` with inline attachments, inside `multipart/mixed` with the others.MessageBuilderCollects what a `Message` carries; `MessageBuilder::build` checks it.RefusalA refused envelope or message: the server's reply, and each recipient's own refusal when every recipient was refused.ReplyOne server response: a three digit code, the text of each line, and the enhanced status code of RFC 3463 when the server sends one.TcpTransportTCP on tokio, with TLS by rustls.TimeoutsHow long each kind of wait may last. Reaching a server and hearing back from it deserve different patience; each bounds one operation, not a session.TlsHow the TLS handshake is checked.