# postino: MIME email over SMTP for D — full reference postino is a library for the D programming language that builds MIME emails (plain text, HTML, embedded images, attachments) and sends them over SMTP through libcurl (`std.net.curl`), or saves them as `.eml` files. One class, `Email`, with chainable setters. MIT license. `import postino;`. This file documents version 0.1.8; see "Versions" at the end for what older versions do differently. - Rules for agents: https://trikko.github.io/postino/AGENTS.md - API documentation: https://trikko.github.io/postino/ - Source: https://github.com/trikko/postino ## Installation `dub add postino`. dmd or ldc2. postino uses `std.net.curl`, which loads libcurl at run time: it must be installed where the program runs (it is on most Linux and macOS systems; on Windows it ships with dmd). ## Email ```d auto email = new Email(); ``` Every setter below returns the same `Email`, so calls can be chained. An `Email` is one message: there is no reset and no way to remove a recipient or an attachment. Build a new one for each message. ## Addresses ```d Email setFrom(string address, string name = string.init); Email addTo(string address, string name = string.init); Email addCc(string address, string name = string.init); Email addBcc(string address, string name = string.init); Email setReplyTo(string address, string name = string.init); ``` - `address` is only the address (`"alice@example.com"`); the display name is `name`. `"Alice "` as address is invalid. - Addresses are checked when they are added, and an invalid one throws `PostinoException` at once. Rejected: an empty address, more than 254 characters, spaces and control characters (CR and LF included: no header injection), any of `()<>[]\,;:"`, not exactly one `@`, a local part (before `@`) empty or longer than 64 characters, a local part that starts or ends with a dot or contains `..`, an empty domain, empty domain labels (`a@.com`, `a@b..com`), labels that start or end with `-`. Quoted local parts (`"john doe"@example.com`) are not supported. - Non-ASCII characters before `@` (`andrè@example.com`) throw: they need SMTPUTF8, which postino does not support. Internationalized domains are accepted and written as punycode: `info@città.it` becomes `info@xn--citt-3na.it`, in the headers and in the envelope. As browsers do (UTS #46), compatibility forms are mapped first (NFKC, lowercase): fullwidth `example.com` is `example.com`, the ideographic dot `。` separates labels. Invisible characters (soft hyphen, zero width space and joiner) and symbols in the domain throw. The 254-character limit is checked after the conversion. - Addresses and names must be valid UTF-8, or they throw. - `addTo`, `addCc` and `addBcc` can be called many times; `setFrom` and `setReplyTo` replace the previous value. - **To** and **Cc** recipients are listed in the headers. **Bcc** recipients receive the email but are never written in the message, not even in the file of `save`. All three are in the SMTP envelope (`RCPT TO`). - If there are no To recipients (only Cc or Bcc), the header is `To: undisclosed-recipients:;`. - Display names are UTF-8: names with non-ASCII characters are encoded as RFC 2047 encoded-words (`=?UTF-8?B?...?=`), names with `"\,;:<>@[]().` or `=?` are quoted and escaped (a name that looks like an encoded-word is shown as it is, not decoded into something else). Control characters (CR, LF, NUL, ESC, ...) are removed; tab is kept. ```d email.setFrom("noreply@example.com", "Example Srl") .addTo("alice@example.com", "Alice Rossi") .addTo("bob@example.com") .addCc("manager@example.com", "Dr. Manager") // quoted: "Dr. Manager" .addBcc("archive@example.com") // not in the headers .setReplyTo("support@example.com", "Supporto Clienti"); ``` ## Subject and body ```d Email setSubject(string subject); Email setPlainTextBody(string body); Email setHtmlBody(string body); ``` - All text must be valid UTF-8: invalid text throws `PostinoException`. The subject is RFC 2047 encoded if it contains non-ASCII characters or `=?`, split into words of at most 75 characters on folded lines; a long ASCII subject is folded at spaces. Control characters are removed, tab is kept. - Bodies are sent as `charset="UTF-8"` with `Content-Transfer-Encoding: quoted-printable`: lines end with CRLF and are at most 76 characters, whatever the input. `\n`, `\r\n` and `\r` line endings are all accepted; other separators (form feed, U+2028, ...) are content and arrive as they are. HTML on a single long line is fine. - With both bodies the email is `multipart/alternative`: the client shows the HTML and falls back on the text. Always set a plain text body too when sending HTML: spam filters and text-only clients use it. - With neither, the email has an empty text body. ## Embedded files (images in the HTML) ```d Email embedFile(string path, string cid, string mimeType = string.init); // a file Email addEmbeddedFile(const(ubyte)[] data, string cid, string mimeType); // data in memory ``` - The HTML shows the file with `cid:` and the same id: `embedFile("logo.png", "logo")` and ``. - `cid` is printable ASCII without spaces and without `<>()[]\,;:"`: letters, digits, `.`, `-`, `_`, `@` are safe. An invalid cid throws. The same cid added twice keeps the last. - `mimeType`: if empty, guessed from the extension of `path` (`image/png`, `image/jpeg`, `image/gif`, `image/svg+xml`, `image/webp`, ...); for `data` the default is `application/octet-stream`, so always give it (`"image/png"`). See "MIME types". - Embedded files make the email `multipart/related`, with `Content-Disposition: inline` (and the file name, for a file). ```d email.setHtmlBody(`

Hello

`) .embedFile("/srv/app/banner.jpg", "banner"); ubyte[] png = renderChart(); email.addEmbeddedFile(png, "chart", "image/png"); ``` ## Attachments ```d Email attachFile(string path, string mimeType = string.init, string name = string.init); // a file Email addAttachment(const(ubyte)[] data, string mimeType, string name = string.init); // data in memory ``` - `attachFile`: `name` defaults to the file name of `path` (`baseName`), `mimeType` to the type guessed from the extension. An empty path throws. - `addAttachment`: give a `name`, or the recipient sees a random UUID as file name. If `mimeType` is empty it is guessed from the extension of `name`. For text use `text.representation` (`import std.string : representation;`). - The file name can be any UTF-8: non-ASCII names are written as RFC 2231 `filename*=UTF-8''...` with an ASCII `filename="..."` fallback (non-ASCII characters replaced by `_`). Quotes and backslashes are escaped, control characters removed. - Attachments make the email `multipart/mixed`. Content is base64. ```d import std.string : representation; email.attachFile("/tmp/report.pdf") // application/pdf, "report.pdf" .attachFile("/tmp/export-1234.bin", "text/csv", "data.csv") // type and name given .addAttachment(csv.representation, "text/csv", "orders.csv"); ``` ### Files and data - `attachFile` and `embedFile` store the path only. The file is read by the first `send` or `save`; later ones reuse the built message until a setter changes the email or `renew()` is called. A missing file, a directory or an unreadable file throws `PostinoException` then. Do not delete the file before sending. - `addAttachment` and `addEmbeddedFile` copy the data when they are called: changing the array afterwards changes nothing in the email, and `clone()` copies cannot leak each other's data. - Never pass text from users to `attachFile` or `embedFile`: it is a path, and the file it names would be sent. - `addAttachment(string path, ...)` and `addEmbeddedFile(string path, cid, ...)` of 0.1.6 still exist, deprecated: they are `attachFile` and `embedFile`, a string is always read as a path. ## MIME types A given `mimeType` must be `type/subtype` made of RFC 2045 token characters, with no parameters: `"image/png"`, `"application/vnd.ms-excel"`. `"text/plain; charset=utf-8"`, `"png"` or anything with CR/LF throws `PostinoException`. The extension table covers common text, image, font, archive, office, audio and video formats; unknown extensions are `application/octet-stream`. ## Custom headers ```d Email addHeader(string name, string value); Email clearHeaders(); ``` - For the headers postino has no setter for: `List-Unsubscribe`, `List-Unsubscribe-Post`, `In-Reply-To`, `References`, `X-Mailer`, `X-...`. Written after `Subject`, in the order they are added; the same name can be added more than once. - Throws `PostinoException` for the headers postino writes itself: `MIME-Version`, `Date`, `Message-ID`, `From`, `To`, `Cc`, `Bcc`, `Reply-To`, `Subject` and every `Content-*` (case-insensitive). Use the setters for those. - The name is printable ASCII without spaces and `:`; the value can't contain control characters other than tab, nor invalid UTF-8 (it throws: values are never cleaned silently), and an ASCII value can't make the line longer than 998 characters. - Non-ASCII values, and values containing `=?`, are RFC 2047 encoded: right for unstructured headers (`X-...`, `Comments`). Structured headers (`List-Unsubscribe`, `In-Reply-To`, `References`) must be ASCII: percent-encode the URLs. - Values are written as given: the syntax of structured headers (`<...>` around URLs and Message-IDs) is up to you. ```d // One-click unsubscribe, required by Gmail and Yahoo for bulk senders email.addHeader("List-Unsubscribe", ", ") .addHeader("List-Unsubscribe-Post", "List-Unsubscribe=One-Click"); // A reply in the same thread email.setSubject("Re: Order 1234") .addHeader("In-Reply-To", "") .addHeader("References", ""); ``` ## Copying and clearing ```d Email clone(); Email clearTo(); Email clearCc(); Email clearBcc(); Email clearHeaders(); Email clearAttachments(); Email clearEmbeddedFiles(); Email renew(); ``` - `clone()` returns an independent copy: sender, recipients, Reply-To, subject, bodies, headers, embedded files and attachments. Changing the copy does not change the original. Attachments added from memory share the same `ubyte[]`: do not modify it. - Each `clear*` empties what the matching `add*` added. There is no way to remove a single recipient. - `setFrom`, `setReplyTo`, `setSubject` and the bodies are replaced by calling them again. - `renew()` makes the next `send` or `save` build a new message (new Date, Message-ID and boundaries, files of `attachFile`/`embedFile` read again). Without it, `send` and `save` reuse the message built the first time until a setter changes the email. ## Sending ```d bool send(string smtpServerUrl, string username = string.init, string password = string.init, SMTP smtp = SMTP()); ``` - Blocking: connects (or reuses the connection of the `SMTP` passed, see "Many emails"), authenticates if `username` and `password` are both non-empty, and sends to every To, Cc and Bcc recipient. Returns `true`; every error is an exception, never `false`. - Throws `PostinoException` if there is no sender (`setFrom`), no recipient at all, or a file to attach is missing, before connecting; `CurlException` for connection, TLS, authentication or server errors (a rejected recipient included). - The envelope sender (`MAIL FROM`) is the `setFrom` address. ### SMTP URL and TLS | URL | Port | Security | |---|---|---| | `smtps://smtp.example.com:465` | 465 | implicit TLS: encrypted from the start | | `smtp://smtp.example.com:587` + credentials | 587 | STARTTLS, required: fails if the server does not offer it | | `smtp://smtp.example.com:25`, no credentials | 25 | plain, as the server allows (relays) | | `smtp://localhost:1025` | any | plain, also with credentials (local test servers) | - `smtps://` with port 587 does **not** work: the server on 587 expects plain SMTP followed by STARTTLS. Use `smtp://host:587`. - With `smtp://`, a username and a password, postino sets `CURLOPT_USE_SSL` to `CURLUSESSL_ALL`: the connection must switch to TLS with STARTTLS before authenticating, so the password never travels in clear. A server, or someone in the middle, that does not offer STARTTLS makes `send` throw. The exception is a server on this machine: `localhost`, `127.x.x.x`, `[::1]`. - Without credentials `smtp://` is left as it is (no STARTTLS), so relays on port 25 with self-signed certificates keep working. - Certificates are verified by libcurl. For a self-signed server certificate, configure an `SMTP` (see below), e.g. `smtp.handle.set(CurlOption.ssl_verifypeer, 0)` (with `import etc.c.curl : CurlOption;`), only for tests. - An optional path in the URL is the name sent with EHLO: `smtp://smtp.example.com:587/client.example.com`. - Credentials in the URL (`smtp://user:pass@host`), `?` and `#` are refused with `PostinoException`, before connecting: pass the credentials to `send`, so the STARTTLS rule always applies. Read `SMTP_URL`, `SMTP_USER` and `SMTP_PASSWORD` separately. - Local means `localhost` or a loopback IP address (`127.0.0.0/8`, `::1`). Names are never resolved for this: `127.example.com` is a remote host. - The STARTTLS setting is decided at every `send`, also on a reused `SMTP` object. Common providers: ```d email.send("smtps://smtp.gmail.com:465", "user@gmail.com", "app-password"); // Gmail: app password email.send("smtp://smtp.gmail.com:587", "user@gmail.com", "app-password"); // same, STARTTLS email.send("smtp://smtp-mail.outlook.com:587", "user@outlook.com", "password"); // Outlook (if basic auth is enabled) email.send("smtp://localhost:25"); // local MTA email.send("smtp://localhost:1025"); // Mailpit, MailHog ``` ### OAuth2 ```d struct OAuth2 { string accessToken; } bool send(string smtpServerUrl, string username, OAuth2 auth, SMTP smtp = SMTP()); ``` - Authenticates with SASL XOAUTH2: what Gmail and Microsoft 365 (Exchange Online, Outlook) use instead of passwords. - `username` is the account the token belongs to, usually its email address; the OAuth 2.0 access token goes inside `OAuth2(...)`. A plain string as third argument is a password: `OAuth2` is a type of its own so that the two can't be mixed up. Both username and token are required: an empty one throws `PostinoException`. - postino does not get, store or refresh tokens: use the provider's OAuth flow (an authorization code or a service account) and pass a token that is still valid; access tokens usually last one hour. A refused or expired token is a `CurlException`. - Same TLS rules as `send`: `smtps://` is TLS, `smtp://` requires STARTTLS (except on localhost). ```d email.send("smtp://smtp.office365.com:587", "user@example.com", OAuth2(accessToken)); // Microsoft 365 email.send("smtps://smtp.gmail.com:465", "user@gmail.com", OAuth2(accessToken)); // Gmail ``` ### A configured SMTP The last argument is a `std.net.curl.SMTP`, for timeouts, proxies and other curl options. postino sets its URL, authentication, recipients and message, then performs it. ```d import std.net.curl : SMTP; import core.time : seconds; auto smtp = SMTP(); smtp.connectTimeout = 10.seconds; smtp.dataTimeout = 30.seconds; email.send("smtp://smtp.example.com:587", "user", "password", smtp); ``` Read the credentials from the environment or a secrets store, not from the source code. ### Many emails A new `SMTP` (the default argument) opens a new connection for every `send`. Pass the same `SMTP` object to every `send` and the connection is reused: one connection, one TLS handshake and one login for all the emails, as long as the server keeps it open. Each `send` sets its own credentials on the `SMTP` object: a password, a token, or none. Those of a previous `send` are cleared, never reused. With different credentials (another user, a new password or token, none) libcurl opens a new connection and logs in again, so one `SMTP` object can serve many accounts safely. Credentials set on the `SMTP` object by hand are replaced too: pass them to `send`. For newsletters, build the message once and send a `clone()` to each recipient with `addTo` (not a long `addBcc` list, and not `addTo` on the same object in a loop: recipients accumulate): ```d import std.net.curl : SMTP; auto newsletter = new Email() .setFrom("news@example.com", "Example News") .setSubject("November news") .setPlainTextBody(text) .setHtmlBody(html); auto smtp = SMTP(); // shared: one connection for all foreach (s; subscribers) newsletter.clone() .addTo(s.email, s.name) .addHeader("List-Unsubscribe", "") .addHeader("List-Unsubscribe-Post", "List-Unsubscribe=One-Click") .send("smtp://smtp.example.com:587", "user", "password", smtp); ``` `send` still waits for the server: keep sending out of the request path of a web server, hand the job to a queue (for example pacchettino) and send from a worker. ## Saving ```d Email save(string path); ``` Writes the message as an `.eml` file (RFC 5322, CRLF line endings) that mail clients open. It is exactly what `send` would deliver: same headers, Bcc excluded. The message is built once, so `send` followed by `save` (or the other way around) gives the same Date, Message-ID and boundaries, for example to keep a copy of what was sent in a Sent folder. Any setter, or `renew()`, makes the next `send` or `save` build a new message; `clone()` always does. Nothing is sent. Throws like `send` for a missing sender, missing recipients or a missing file, and if the file cannot be written. Use it in tests and to preview an email. ```d email.save("/tmp/preview.eml"); ``` ## The message Headers, in order: `MIME-Version: 1.0`, `Date` (local time, RFC 5322), `Message-ID` (``), `From`, `To`, `Cc`, `Reply-To`, `Subject`. Then the body, nested only as needed: ``` multipart/mixed (only with attachments) ├── multipart/related (only with embedded files) │ ├── multipart/alternative (only with both text and html) │ │ ├── text/plain │ │ └── text/html │ └── embedded files (inline, Content-ID) └── attachments (attachment, filename) ``` Boundaries, Date and Message-ID are new every time the message is built: sending or saving the same `Email` twice gives two distinct messages. ## Errors | When | Exception | |---|---| | `setFrom`, `addTo`, `addCc`, `addBcc`, `setReplyTo` with an invalid address | `PostinoException` | | `addEmbeddedFile` with an invalid cid or MIME type, `addAttachment` with an invalid MIME type | `PostinoException` | | `addHeader` with an invalid or reserved name, or a value with CR/LF | `PostinoException` | | `send`/`save` without sender or without recipients | `PostinoException` | | `send`/`save` with a missing or unreadable file, or a directory | `PostinoException` | | `send` with credentials in the URL, `?` or `#`, or a scheme other than `smtp://`/`smtps://` | `PostinoException` | | text that is not valid UTF-8 (subject, bodies, names, header values, file names) | `PostinoException` | | `attachFile`/`embedFile` with an empty path | `PostinoException` | | `send` with `OAuth2` and an empty username or token | `PostinoException` | | `save` cannot write the file | `FileException` | | `send`: connection, TLS, STARTTLS missing, authentication, rejected recipient | `CurlException` | `PostinoException` derives from `Exception`; `CurlException` comes from `std.net.curl`. Catch `PostinoException` to tell invalid input (often from users: a wrong address) from delivery problems. ## Worked example: a report with a chart ```d import postino; import std.process : environment; import std.string : representation; void sendReport(string[] recipients, ubyte[] chartPng, string csv) { auto email = new Email() .setFrom("reports@example.com", "Reports") .setReplyTo("data-team@example.com", "Data Team") .setSubject("Report settimanale: è pronto") .setPlainTextBody("The weekly report is attached.\nThe chart is in the HTML version.") .setHtmlBody(`

The weekly report is attached.

chart`) .addEmbeddedFile(chartPng, "chart", "image/png") .addAttachment(csv.representation, "text/csv", "report.csv"); foreach (r; recipients) email.addBcc(r); // throws for an invalid address: validate before if it comes from users email.send("smtp://smtp.example.com:587", environment["SMTP_USER"], environment["SMTP_PASSWORD"]); } ``` ## Worked example: testing without a server ```d unittest { import std.file : readText, remove, tempDir; import std.path : buildPath; import std.algorithm : canFind; auto path = buildPath(tempDir, "welcome.eml"); scope(exit) remove(path); new Email() .setFrom("noreply@example.com") .addTo("new.user@example.com") .setSubject("Welcome") .setPlainTextBody("Hello!") .save(path); auto eml = readText(path); assert(eml.canFind("\r\nSubject: Welcome\r\n")); assert(eml.canFind("\r\nTo: new.user@example.com\r\n")); } ``` For an end-to-end test, run Mailpit (`smtp://localhost:1025`) and read the messages from its web UI or API: postino's own `tests/mailpit.sh` does this in docker. ## Limits - Blocking, no async API. - The Message-ID is generated and can't be set or read; the envelope sender (bounce address) is always the `setFrom` address. - No DKIM signing (let the SMTP server sign), no S/MIME or PGP. - No templates: build the strings yourself. - OAuth2 tokens are sent, not obtained or refreshed. - Quoted local parts and non-ASCII characters before `@` (SMTPUTF8) are not supported. - No receiving mail (IMAP, POP3). ## Versions 0.1.7 has everything in this file except `renew()`, and every `send` and `save` builds a new message, with a new Date, Message-ID and boundaries: a `save` after a `send` does not write the message that was sent, and `attachFile`/`embedFile` files are read at every call. 0.1.6 has everything in this file except `PostinoException` (errors are plain `Exception`), `addHeader`, `clearHeaders`, `OAuth2`, `clone`, the other `clear*` methods, `attachFile` and `embedFile` (there, `addAttachment(path)` and `addEmbeddedFile(path, cid)`), and punycode domains (non-ASCII addresses are accepted as they are). In 0.1.6 the data of `addAttachment`/`addEmbeddedFile` is not copied, credentials in the URL and some URLs skip the STARTTLS rule (never put credentials in the URL there), and control characters other than CR/LF/NUL reach the headers. Up to 0.1.5: only To recipients received the email (Cc and Bcc were in the headers but not in the SMTP envelope), Bcc recipients were written in the headers, `smtp://` never used STARTTLS (credentials in clear), invalid addresses threw only at `send`, CR/LF in addresses were removed instead of rejected, the cid was not checked, the `mimeType` argument of the path overloads was ignored, bodies were sent as 8-bit without Content-Transfer-Encoding, attachments were in `multipart/related`, a missing file was sent empty, and `Date`/`Message-ID` were missing. `save` came with 0.1.5. On those versions do not use `addCc`/`addBcc` and do not send credentials over `smtp://`; upgrade.