Skip to main content

ocre/
mail.rs

1//! Email: send with adapters (log, Resend, Cloudflare), receive from Email Routing.
2//!
3//! Sending is Rails' Action Mailer without the class: build an [`Email`]
4//! (several recipients, cc, bcc, headers, attachments and inline images) and
5//! hand it to [`send`], or to [`deliver_later`] / [`deliver_in`] to send it
6//! from the background jobs queue (see [`jobs`](crate::jobs)) so the request
7//! does not wait for the provider and a failed delivery is retried.
8//! Receiving is Action Mailbox: [`receive`] is the Worker's `email` entry
9//! point and hands each message to the app as an [`InboundEmail`]. In
10//! `ocre dev`, [`dev_routes`] serves mailer previews, the emails sent, and a
11//! form that delivers test email to the mailbox.
12//!
13//! ```no_run
14//! use axum::extract::State;
15//! use ocre::mail::{self, Email};
16//! use ocre::{Ctx, Result};
17//!
18//! async fn welcome(State(ctx): State<Ctx>) -> Result<&'static str> {
19//!     let email = Email::new("ada@example.com", "Welcome", "Hello Ada,\n\nhttps://example.com/start\n")
20//!         .html("<p>Hello Ada,</p><p><a href=\"https://example.com/start\">Start</a></p>");
21//!     mail::send(&ctx, email).await?;
22//!     Ok("sent")
23//! }
24//! ```
25//!
26//! # Configuration
27//!
28//! The [`MAIL_ADAPTER`] Worker variable picks how
29//! mail leaves the Worker, with no guessing from which keys happen to be set,
30//! so a development machine holding a real API key never sends by accident:
31//!
32//! - `log`: prints the whole email (headers, text, HTML, attachments) to the
33//!   Worker console between [`LOG_PREFIX`] lines, like Rails'
34//!   letter_opener, and in debug builds keeps the last 20 for
35//!   `/ocre/dev/mailers` (see [`dev_routes`]). `ocre new` writes
36//!   `MAIL_ADAPTER=log` to `.dev.vars`, which overrides the
37//!   `bindings.text` variables in `ocre dev`. No configuration, no limits.
38//! - `resend`: `POST https://api.resend.com/emails` with the
39//!   [`RESEND_API_KEY`] secret, `MAIL_FROM` on a
40//!   domain verified in Resend. Free plan (September 2026): 100 emails a day,
41//!   3,000 a month, one domain; any recipient.
42//! - `cloudflare`: Cloudflare Email Service through the
43//!   [`EMAIL_BINDING`] `bindings.sendEmail()` binding,
44//!   `MAIL_FROM` on a domain onboarded to Email Service. Workers Free
45//!   (September 2026) only delivers to verified destination addresses of the
46//!   account; any recipient needs Workers Paid (3,000 a month included).
47//!
48//! The sender is the email's own [`from`](Email::from), else the
49//! [`MAIL_FROM`] variable, `noreply@example.com` or
50//! `Name <noreply@example.com>`. With `MAIL_ADAPTER`
51//! unset, sending fails with an [`Error::Internal`]
52//! naming the fix, so a production Worker never drops mail silently. For
53//! sign-up and password-reset mail on the free plan, use Resend.
54//!
55//! Receiving uses Cloudflare Email Routing, free and unlimited on every plan.
56//! Every line Ocre logs about mail starts with [`LOG_PREFIX`].
57//!
58//! [`intercept`] registers a function every outgoing email goes through
59//! first (Rails' interceptors): rewrite recipients on a staging copy, or
60//! drop automated mail behind a switch.
61
62mod dev;
63mod intercept;
64mod parse;
65
66use serde::{Deserialize, Serialize};
67use serde_json::{Value, json};
68
69pub use crate::runtime::mail::{InboundEmail, deliver_in, deliver_later, receive, send, url};
70pub(crate) use dev::capture;
71pub use dev::{Preview, dev_routes};
72pub use intercept::intercept;
73pub(crate) use intercept::{dropped_line, intercepted};
74pub(crate) use parse::Message;
75
76use crate::{Error, Result, validate::is_email};
77
78/// Name of the Worker variable that chooses the adapter: `log`, `resend` or `cloudflare`.
79///
80/// Read on every [`send`] and [`deliver_later`]; unset or any other value is
81/// an [`Error::Internal`] that names the fix. Set it as
82/// `MAIL_ADAPTER: bindings.text("resend")` in cloudflare.config.ts, or in `.dev.vars` for
83/// `ocre dev` (which overrides it).
84///
85/// # Examples
86///
87/// ```
88/// assert_eq!(ocre::mail::MAIL_ADAPTER, "MAIL_ADAPTER");
89/// ```
90pub const MAIL_ADAPTER: &str = "MAIL_ADAPTER";
91/// Name of the Worker variable holding the sender address.
92///
93/// Either `noreply@example.com` or `Name <noreply@example.com>` (the name
94/// may be quoted). Missing or unparsable is an
95/// [`Error::Internal`] when sending. With Resend or
96/// Cloudflare the domain must be verified with that provider.
97///
98/// # Examples
99///
100/// ```
101/// assert_eq!(ocre::mail::MAIL_FROM, "MAIL_FROM");
102/// ```
103pub const MAIL_FROM: &str = "MAIL_FROM";
104/// Name of the Worker secret holding the Resend API key, used when `MAIL_ADAPTER = "resend"`.
105///
106/// Set it with `ocre secrets push RESEND_API_KEY --file .prod.vars` (and in `.dev.vars`
107/// to send for real from `ocre dev`). Missing or blank is an
108/// [`Error::Internal`] when sending.
109///
110/// # Examples
111///
112/// ```
113/// assert_eq!(ocre::mail::RESEND_API_KEY, "RESEND_API_KEY");
114/// ```
115pub const RESEND_API_KEY: &str = "RESEND_API_KEY";
116/// Name of the `bindings.sendEmail()` binding used when `MAIL_ADAPTER = "cloudflare"`.
117///
118/// `ocre new` leaves the entry commented out in cloudflare.config.ts; a missing
119/// binding is an [`Error::Internal`] naming the entry to add.
120///
121/// # Examples
122///
123/// ```
124/// assert_eq!(ocre::mail::EMAIL_BINDING, "EMAIL");
125/// ```
126pub const EMAIL_BINDING: &str = "EMAIL";
127/// Prefix of every line Ocre logs about mail, e.g. in `ocre dev` output.
128///
129/// The `log` adapter frames each email between lines with this prefix, and
130/// [`receive`] logs `[ocre mail] received from ... to ...: <subject>`.
131///
132/// # Examples
133///
134/// ```
135/// assert!("[ocre mail] end".starts_with(ocre::mail::LOG_PREFIX));
136/// ```
137pub const LOG_PREFIX: &str = "[ocre mail]";
138
139/// Name of the Worker variable holding the app's public address, `https://shop.example.com`, for links in emails.
140///
141/// Rails' `default_url_options[:host]` (and `asset_host`): [`url`] joins it
142/// with a path, so mailers and jobs, which may run outside any request,
143/// build absolute links and image URLs. Set it as
144/// `APP_URL: bindings.text("https://shop.example.com")` in worker.env of
145/// cloudflare.config.ts, and `APP_URL=http://localhost:8787` in `.dev.vars`.
146///
147/// # Examples
148///
149/// ```
150/// assert_eq!(ocre::mail::APP_URL, "APP_URL");
151/// ```
152pub const APP_URL: &str = "APP_URL";
153
154/// `base` (the `APP_URL` value) joined with `path`; an absolute `path` is kept.
155pub(crate) fn absolute_url(base: Option<String>, path: &str) -> Result<String> {
156    if path.starts_with("https://") || path.starts_with("http://") {
157        return Ok(path.to_owned());
158    }
159    let base = base
160        .map(|base| base.trim().trim_end_matches('/').to_owned())
161        .filter(|base| base.starts_with("https://") || base.starts_with("http://"))
162        .ok_or_else(|| {
163            Error::internal(format!(
164                "cannot build an absolute URL: {APP_URL} is not set to an http(s) address. Fix: add \
165                 {APP_URL}: bindings.text(\"https://your.domain\") to worker.env in cloudflare.config.ts and \
166                 {APP_URL}=http://localhost:8787 to .dev.vars"
167            ))
168        })?;
169    let slash = if path.starts_with('/') { "" } else { "/" };
170    Ok(format!("{base}{slash}{path}"))
171}
172
173/// An outgoing email: recipients, a subject, a plain-text body, and optionally HTML, headers and attachments.
174///
175/// Build it with [`Email::new`] (one recipient), then add more with
176/// [`also_to`](Self::also_to), [`cc`](Self::cc) and [`bcc`](Self::bcc), an
177/// HTML version with [`html`](Self::html), a `Reply-To` with
178/// [`reply_to`](Self::reply_to), another sender with [`from`](Self::from),
179/// custom headers with [`header`](Self::header), and files with
180/// [`attach`](Self::attach) and [`inline`](Self::inline); send it with
181/// [`send`] or [`deliver_later`]. Nothing is checked while building:
182/// addresses, headers, attachments and the subject are checked when sending
183/// (an invalid recipient is a 400, the rest a 500 naming the fix). Every
184/// address may carry a display name, `Ada <ada@example.com>` (see
185/// [`address_with_name`]). Generated mailers (`ocre g mailer`) return one per
186/// action, rendered from `templates/mailers/<name>/<action>.{txt,html}`.
187///
188/// It is serde-serializable because [`deliver_later`] puts it in a queue
189/// message (128 KB at most, attachments included, base64-encoded).
190///
191/// # Examples
192///
193/// ```
194/// use ocre::mail::Email;
195///
196/// let email = Email::new("ada@example.com", "Reset your password", "Open https://example.com/reset/abc")
197///     .html("<a href=\"https://example.com/reset/abc\">Reset your password</a>")
198///     .reply_to("support@example.com");
199/// assert_eq!(email.to, ["ada@example.com"]);
200/// assert_eq!(email.subject, "Reset your password");
201/// assert_eq!(email.text, "Open https://example.com/reset/abc");
202/// assert_eq!(email.html.as_deref(), Some("<a href=\"https://example.com/reset/abc\">Reset your password</a>"));
203/// assert_eq!(email.reply_to.as_deref(), Some("support@example.com"));
204/// ```
205#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
206pub struct Email {
207    /// Sender, when not `MAIL_FROM`: `billing@example.com` or `Billing <billing@example.com>`,
208    /// on a domain verified with the provider.
209    #[serde(default, skip_serializing_if = "Option::is_none")]
210    pub from: Option<String>,
211    /// `To` recipients, `ada@example.com` or `Ada <ada@example.com>`; an invalid one makes sending a 400.
212    #[serde(deserialize_with = "one_or_many")]
213    pub to: Vec<String>,
214    /// `Cc` recipients, checked like `to`.
215    #[serde(default, skip_serializing_if = "Vec::is_empty")]
216    pub cc: Vec<String>,
217    /// `Bcc` recipients, checked like `to`; the other recipients do not see them.
218    #[serde(default, skip_serializing_if = "Vec::is_empty")]
219    pub bcc: Vec<String>,
220    /// Subject line: one non-empty line of text.
221    pub subject: String,
222    /// Plain-text body; always sent, so every mail client can read it.
223    pub text: String,
224    /// Optional HTML body, shown instead of `text` by clients that render HTML.
225    pub html: Option<String>,
226    /// Where replies go, when not to the sender; checked like `to`.
227    pub reply_to: Option<String>,
228    /// Extra headers, `(name, value)`: threading (`In-Reply-To`, `References`), `List-Unsubscribe`, `X-...`.
229    #[serde(default, skip_serializing_if = "Vec::is_empty")]
230    pub headers: Vec<(String, String)>,
231    /// Files attached to the email, and inline images the HTML shows with `cid:`.
232    #[serde(default, skip_serializing_if = "Vec::is_empty")]
233    pub attachments: Vec<Attachment>,
234    /// Adapter for this email instead of `MAIL_ADAPTER` (`resend` or `cloudflare`), set by
235    /// [`delivery_method`](Email::delivery_method); ignored while `MAIL_ADAPTER` is `log`.
236    #[serde(default, skip_serializing_if = "Option::is_none")]
237    pub delivery_method: Option<String>,
238}
239
240/// A file attached to an [`Email`], or an inline image shown by its HTML.
241///
242/// Built by [`Email::attach`] and [`Email::inline`]; also what
243/// [`InboundEmail::attachments`] returns for received mail. In a queue
244/// message the content travels base64-encoded.
245///
246/// # Examples
247///
248/// ```
249/// let email = ocre::mail::Email::new("ada@example.com", "Invoice", "Attached.")
250///     .attach("invoice.pdf", "application/pdf", b"%PDF-1.7".to_vec());
251/// let file = &email.attachments[0];
252/// assert_eq!((file.filename.as_str(), file.content_type.as_str(), file.content_id.as_deref()),
253///            ("invoice.pdf", "application/pdf", None));
254/// ```
255#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
256pub struct Attachment {
257    /// File name shown by mail clients, `invoice.pdf`.
258    pub filename: String,
259    /// MIME type, `application/pdf` or `image/png`.
260    pub content_type: String,
261    /// The file's bytes.
262    #[serde(with = "base64_bytes")]
263    pub content: Vec<u8>,
264    /// For inline images: the id the HTML refers to as `cid:<id>`.
265    #[serde(default, skip_serializing_if = "Option::is_none")]
266    pub content_id: Option<String>,
267}
268
269impl Email {
270    /// Creates a text-only email to one recipient.
271    ///
272    /// Everything else starts empty. Nothing is validated here.
273    ///
274    /// # Examples
275    ///
276    /// ```
277    /// let email = ocre::mail::Email::new("ada@example.com", "Hi", "Hello Ada");
278    /// assert_eq!((email.subject.as_str(), email.html, email.reply_to), ("Hi", None, None));
279    /// ```
280    pub fn new(to: impl Into<String>, subject: impl Into<String>, text: impl Into<String>) -> Self {
281        Self {
282            from: None,
283            to: vec![to.into()],
284            cc: Vec::new(),
285            bcc: Vec::new(),
286            subject: subject.into(),
287            text: text.into(),
288            html: None,
289            reply_to: None,
290            headers: Vec::new(),
291            attachments: Vec::new(),
292            delivery_method: None,
293        }
294    }
295
296    /// Adds another `To` recipient.
297    ///
298    /// All `To` and `Cc` recipients see each other; use [`bcc`](Self::bcc)
299    /// or one email each to keep addresses private. 50 recipients at most
300    /// (`to`, `cc` and `bcc` together), Resend's limit.
301    ///
302    /// # Examples
303    ///
304    /// ```
305    /// let email = ocre::mail::Email::new("ada@example.com", "Hi", "Hello").also_to("Grace <grace@example.com>");
306    /// assert_eq!(email.to, ["ada@example.com", "Grace <grace@example.com>"]);
307    /// ```
308    pub fn also_to(mut self, address: impl Into<String>) -> Self {
309        self.to.push(address.into());
310        self
311    }
312
313    /// Adds a `Cc` recipient.
314    ///
315    /// # Examples
316    ///
317    /// ```
318    /// let email = ocre::mail::Email::new("ada@example.com", "Hi", "Hello").cc("team@example.com");
319    /// assert_eq!(email.cc, ["team@example.com"]);
320    /// ```
321    pub fn cc(mut self, address: impl Into<String>) -> Self {
322        self.cc.push(address.into());
323        self
324    }
325
326    /// Adds a `Bcc` recipient: it gets the email, the other recipients do not see it.
327    ///
328    /// # Examples
329    ///
330    /// ```
331    /// let email = ocre::mail::Email::new("ada@example.com", "Hi", "Hello").bcc("archive@example.com");
332    /// assert_eq!(email.bcc, ["archive@example.com"]);
333    /// ```
334    pub fn bcc(mut self, address: impl Into<String>) -> Self {
335        self.bcc.push(address.into());
336        self
337    }
338
339    /// Sends from `address` instead of the `MAIL_FROM` variable.
340    ///
341    /// Like Rails' `mail(from: ...)`; the domain must be verified with the
342    /// provider, like `MAIL_FROM`'s. An unparsable sender is a 500.
343    ///
344    /// # Examples
345    ///
346    /// ```
347    /// let email = ocre::mail::Email::new("ada@example.com", "Invoice", "...").from("Billing <billing@example.com>");
348    /// assert_eq!(email.from.as_deref(), Some("Billing <billing@example.com>"));
349    /// ```
350    pub fn from(mut self, address: impl Into<String>) -> Self {
351        self.from = Some(address.into());
352        self
353    }
354
355    /// Sends this email with another adapter than `MAIL_ADAPTER`: `"resend"` or `"cloudflare"` (Rails' `delivery_method`).
356    ///
357    /// For an app that uses both providers, e.g. Cloudflare Email Service
358    /// (free, to the team's verified addresses) for internal alerts and
359    /// Resend for customer mail. The adapter's own configuration applies
360    /// (the `RESEND_API_KEY` secret or the `EMAIL` binding). While
361    /// `MAIL_ADAPTER` is `log` (development), the email is still only
362    /// logged, so a development machine never sends by accident. An unknown
363    /// name is a 500 when sending, naming the fix.
364    ///
365    /// # Examples
366    ///
367    /// ```
368    /// let alert = ocre::mail::Email::new("ops@example.com", "Disk almost full", "...").delivery_method("cloudflare");
369    /// assert_eq!(alert.delivery_method.as_deref(), Some("cloudflare"));
370    /// ```
371    pub fn delivery_method(mut self, adapter: impl Into<String>) -> Self {
372        self.delivery_method = Some(adapter.into());
373        self
374    }
375
376    /// Adds the HTML version of the body, replacing any previous one.
377    ///
378    /// The text body is still sent alongside it. The HTML is sent as given:
379    /// escape user input when building it (askama templates do).
380    ///
381    /// # Examples
382    ///
383    /// ```
384    /// let email = ocre::mail::Email::new("ada@example.com", "Hi", "Hello").html("<p>Hello</p>");
385    /// assert_eq!(email.html.as_deref(), Some("<p>Hello</p>"));
386    /// ```
387    pub fn html(mut self, html: impl Into<String>) -> Self {
388        self.html = Some(html.into());
389        self
390    }
391
392    /// Sets the `Reply-To` address, so replies go there instead of to the sender.
393    ///
394    /// Checked when sending: an invalid address is a 400, like the recipient.
395    ///
396    /// # Examples
397    ///
398    /// ```
399    /// let email = ocre::mail::Email::new("ada@example.com", "Hi", "Hello").reply_to("team@example.com");
400    /// assert_eq!(email.reply_to.as_deref(), Some("team@example.com"));
401    /// ```
402    pub fn reply_to(mut self, address: impl Into<String>) -> Self {
403        self.reply_to = Some(address.into());
404        self
405    }
406
407    /// Adds a header, e.g. `In-Reply-To` and `References` to thread a reply, or `List-Unsubscribe`.
408    ///
409    /// When sending, the name must be letters, digits and `-`, the value one
410    /// line, and the name not one Ocre sets itself (`From`, `To`, `Cc`,
411    /// `Bcc`, `Subject`, `Reply-To`, `Content-Type`, ...); otherwise sending
412    /// is a 500 naming the header.
413    ///
414    /// # Examples
415    ///
416    /// ```
417    /// let reply = ocre::mail::Email::new("ada@example.com", "Re: Order 42", "Shipped today.")
418    ///     .header("In-Reply-To", "<order-42@example.com>")
419    ///     .header("References", "<order-42@example.com>");
420    /// assert_eq!(reply.headers[0], ("In-Reply-To".to_owned(), "<order-42@example.com>".to_owned()));
421    /// ```
422    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
423        self.headers.push((name.into(), value.into()));
424        self
425    }
426
427    /// Attaches a file, like Rails' `attachments["invoice.pdf"] = bytes`.
428    ///
429    /// The whole email must fit the provider's limit (Resend: 40 MB), and
430    /// 128 KB for [`deliver_later`] (base64 makes files a third larger):
431    /// store big files in R2 and send a link instead.
432    ///
433    /// # Examples
434    ///
435    /// ```
436    /// let csv = "id,total\n1,42\n".as_bytes().to_vec();
437    /// let email = ocre::mail::Email::new("ada@example.com", "Report", "Attached.").attach("report.csv", "text/csv", csv);
438    /// assert_eq!(email.attachments[0].content, b"id,total\n1,42\n");
439    /// ```
440    pub fn attach(mut self, filename: impl Into<String>, content_type: impl Into<String>, content: Vec<u8>) -> Self {
441        self.attachments.push(Attachment {
442            filename: filename.into(),
443            content_type: content_type.into(),
444            content,
445            content_id: None,
446        });
447        self
448    }
449
450    /// Embeds an image that the HTML shows with `<img src="cid:<content_id>">`, like Rails' `attachments.inline`.
451    ///
452    /// `content_id` is letters, digits and `.-_` (checked when sending).
453    /// Mail clients show inline images without loading anything remote;
454    /// the text body cannot show them.
455    ///
456    /// # Examples
457    ///
458    /// ```
459    /// let logo = vec![0x89, b'P', b'N', b'G'];
460    /// let email = ocre::mail::Email::new("ada@example.com", "Welcome", "Welcome!")
461    ///     .html("<img src=\"cid:logo\" alt=\"Shop\"><p>Welcome!</p>")
462    ///     .inline("logo", "logo.png", "image/png", logo);
463    /// assert_eq!(email.attachments[0].content_id.as_deref(), Some("logo"));
464    /// ```
465    pub fn inline(
466        mut self,
467        content_id: impl Into<String>,
468        filename: impl Into<String>,
469        content_type: impl Into<String>,
470        content: Vec<u8>,
471    ) -> Self {
472        self.attachments.push(Attachment {
473            filename: filename.into(),
474            content_type: content_type.into(),
475            content,
476            content_id: Some(content_id.into()),
477        });
478        self
479    }
480}
481
482/// Formats `Name <address>`, quoting the name when needed, like Rails' `email_address_with_name`.
483///
484/// Double quotes and line breaks in `name` become spaces, so a user-typed
485/// name cannot break the header. An empty name gives the bare address.
486///
487/// # Examples
488///
489/// ```
490/// use ocre::mail::address_with_name;
491///
492/// assert_eq!(address_with_name("Ada Lovelace", "ada@example.com"), "Ada Lovelace <ada@example.com>");
493/// assert_eq!(address_with_name("Acme, Inc.", "x@acme.test"), "\"Acme, Inc.\" <x@acme.test>");
494/// assert_eq!(address_with_name(" ", "ada@example.com"), "ada@example.com");
495/// ```
496pub fn address_with_name(name: &str, address: &str) -> String {
497    let name: String = name.chars().map(|c| if c == '"' || c.is_control() { ' ' } else { c }).collect();
498    let name = name.split_whitespace().collect::<Vec<_>>().join(" ");
499    Mailbox { name: Some(name).filter(|n| !n.is_empty()), address: address.trim().to_owned() }.to_string()
500}
501
502/// `to` as a list, or as one address (messages queued before `to` became a list).
503fn one_or_many<'de, D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result<Vec<String>, D::Error> {
504    #[derive(Deserialize)]
505    #[serde(untagged)]
506    enum OneOrMany {
507        One(String),
508        Many(Vec<String>),
509    }
510    Ok(match OneOrMany::deserialize(deserializer)? {
511        OneOrMany::One(address) => vec![address],
512        OneOrMany::Many(addresses) => addresses,
513    })
514}
515
516/// Attachment bytes as base64 text in JSON.
517mod base64_bytes {
518    use base64::{Engine, engine::general_purpose::STANDARD};
519    use serde::{Deserialize, Deserializer, Serializer, de::Error};
520
521    pub fn serialize<S: Serializer>(bytes: &[u8], serializer: S) -> Result<S::Ok, S::Error> {
522        serializer.serialize_str(&STANDARD.encode(bytes))
523    }
524
525    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<u8>, D::Error> {
526        STANDARD.decode(String::deserialize(deserializer)?).map_err(D::Error::custom)
527    }
528}
529
530/// How [`send`] delivers mail, from `MAIL_ADAPTER`.
531#[derive(Debug, Clone, Copy, PartialEq)]
532pub(crate) enum Adapter {
533    Log,
534    Resend,
535    Cloudflare,
536}
537
538const ADAPTER_FIX: &str = "Fix: set MAIL_ADAPTER to \"resend\" (with the RESEND_API_KEY secret) or \"cloudflare\" \
539                           (with the EMAIL: bindings.sendEmail() binding) in worker.env of cloudflare.config.ts, \
540                           as MAIL_ADAPTER: bindings.text(\"resend\"); \
541                           `ocre new` puts MAIL_ADAPTER=log in .dev.vars so `ocre dev` only logs mail";
542
543/// Reads `MAIL_ADAPTER`. Unset is an error: production must choose, and
544/// development gets `log` from `.dev.vars`.
545pub(crate) fn adapter(value: Option<&str>) -> Result<Adapter> {
546    match value.map(str::trim) {
547        Some("log") => Ok(Adapter::Log),
548        Some("resend") => Ok(Adapter::Resend),
549        Some("cloudflare") => Ok(Adapter::Cloudflare),
550        None => Err(Error::internal(format!("cannot send email: {MAIL_ADAPTER} is not set. {ADAPTER_FIX}"))),
551        Some(other) => Err(Error::internal(format!(
552            "cannot send email: unknown {MAIL_ADAPTER} \"{other}\" (expected log, resend or cloudflare). {ADAPTER_FIX}"
553        ))),
554    }
555}
556
557/// The adapter for `email`: `MAIL_ADAPTER`, or the email's own
558/// [`delivery_method`](Email::delivery_method) unless `MAIL_ADAPTER` is `log`.
559pub(crate) fn adapter_for(configured: Option<&str>, email: &Email) -> Result<Adapter> {
560    let configured = adapter(configured)?;
561    let own = match email.delivery_method.as_deref().map(str::trim) {
562        None => None,
563        Some(name @ ("resend" | "cloudflare")) => Some(adapter(Some(name))?),
564        Some(other) => {
565            return Err(Error::internal(format!(
566                "cannot send email: unknown delivery_method \"{other}\" (expected resend or cloudflare). Fix: \
567                 call `.delivery_method(\"resend\")` or `.delivery_method(\"cloudflare\")` on the Email"
568            )));
569        }
570    };
571    Ok(if configured == Adapter::Log { Adapter::Log } else { own.unwrap_or(configured) })
572}
573
574/// The Resend key, from the `RESEND_API_KEY` secret.
575pub(crate) fn resend_key(secret: Option<String>) -> Result<String> {
576    secret.filter(|key| !key.trim().is_empty()).ok_or_else(|| {
577        Error::internal(format!(
578            "cannot send email: the {RESEND_API_KEY} secret is not set. Fix: create a key at \
579             https://resend.com/api-keys and run `ocre secrets push {RESEND_API_KEY} --file .prod.vars` \
580             (and put it in .dev.vars to send from `ocre dev`)"
581        ))
582    })
583}
584
585/// An address with an optional display name: `Ada <ada@example.com>`.
586#[derive(Debug, Clone, PartialEq)]
587pub(crate) struct Mailbox {
588    pub name: Option<String>,
589    pub address: String,
590}
591
592impl Mailbox {
593    /// `ada@example.com` or `Ada Lovelace <ada@example.com>` (the name may be quoted).
594    pub fn parse(text: &str) -> Option<Self> {
595        let text = text.trim();
596        let (name, address) = match text.strip_suffix('>').and_then(|rest| rest.rsplit_once('<')) {
597            Some((name, address)) => {
598                let name = name.trim();
599                let name = name.strip_prefix('"').and_then(|n| n.strip_suffix('"')).unwrap_or(name).trim();
600                (Some(name.to_owned()).filter(|n| !n.is_empty()), address.trim())
601            }
602            None => (None, text),
603        };
604        let clean = name.as_deref().is_none_or(|n| !n.contains(|c: char| c.is_control() || c == '"'));
605        (clean && is_email(address)).then(|| Self { name, address: address.to_owned() })
606    }
607}
608
609impl std::fmt::Display for Mailbox {
610    /// `ada@example.com`, `Ada <ada@example.com>`, or `"Acme, Inc." <x@acme.test>`
611    /// when the name has characters that would split the header.
612    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
613        match &self.name {
614            None => f.write_str(&self.address),
615            Some(name) if name.contains(|c| ",;:<>@()[]\\.".contains(c)) => write!(f, "\"{name}\" <{}>", self.address),
616            Some(name) => write!(f, "{name} <{}>", self.address),
617        }
618    }
619}
620
621/// Most recipients per email (`to`, `cc` and `bcc` together): Resend's limit.
622pub(crate) const MAX_RECIPIENTS: usize = 50;
623
624/// Headers Ocre writes itself; [`Email::header`] refuses them.
625const RESERVED_HEADERS: [&str; 10] = [
626    "from",
627    "to",
628    "cc",
629    "bcc",
630    "subject",
631    "reply-to",
632    "content-type",
633    "content-transfer-encoding",
634    "mime-version",
635    "date",
636];
637
638/// A checked [`Email`] with its sender, ready for an adapter.
639#[derive(Debug, Clone, PartialEq)]
640pub(crate) struct Outgoing {
641    pub from: Mailbox,
642    pub email: Email,
643}
644
645impl Outgoing {
646    /// Checks the sender (the email's own, else `MAIL_FROM`) and the email.
647    /// Bad configuration or code is an internal error; a bad recipient is a
648    /// 400, since it usually comes from a form.
649    pub fn new(mail_from: Option<String>, email: Email) -> Result<Self> {
650        let (from, source) = match &email.from {
651            Some(from) => (from.clone(), "the email's `from`"),
652            None => (
653                mail_from.ok_or_else(|| {
654                    Error::internal(format!(
655                        "cannot send email: {MAIL_FROM} is not set. Fix: add {MAIL_FROM}: bindings.text(\"App \
656                         <noreply@yourdomain.com>\") to worker.env in cloudflare.config.ts"
657                    ))
658                })?,
659                MAIL_FROM,
660            ),
661        };
662        let from = Mailbox::parse(&from).ok_or_else(|| {
663            Error::internal(format!(
664                "cannot send email: {source} \"{from}\" is not an address. Fix: use \"noreply@yourdomain.com\" \
665                 or \"App <noreply@yourdomain.com>\""
666            ))
667        })?;
668        if email.to.is_empty() {
669            return Err(Error::internal("cannot send email: it has no `to` recipient"));
670        }
671        let recipients = email.to.iter().chain(&email.cc).chain(&email.bcc);
672        for address in recipients.clone().chain(&email.reply_to) {
673            if Mailbox::parse(address).is_none() {
674                return Err(Error::bad_request(format!("invalid email address: {address}")));
675            }
676        }
677        let count = recipients.count();
678        if count > MAX_RECIPIENTS {
679            return Err(Error::internal(format!(
680                "cannot send email to {count} recipients: {MAX_RECIPIENTS} at most (to, cc and bcc). Fix: send \
681                 one email per recipient, e.g. one `deliver_later` each"
682            )));
683        }
684        if email.subject.trim().is_empty() || email.subject.contains(['\r', '\n']) {
685            return Err(Error::internal(format!(
686                "cannot send email: the subject must be one non-empty line, got {:?}",
687                email.subject
688            )));
689        }
690        for (name, value) in &email.headers {
691            let token = !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-');
692            if !token || value.contains(['\r', '\n']) || RESERVED_HEADERS.contains(&name.to_ascii_lowercase().as_str())
693            {
694                return Err(Error::internal(format!(
695                    "cannot send email: header {name:?}: {value:?} is not allowed. Fix: use a name of letters, \
696                     digits and `-` that Ocre does not set itself (use `.cc`, `.reply_to`, ... for those), and a \
697                     one-line value"
698                )));
699            }
700        }
701        for file in &email.attachments {
702            let filename = !file.filename.trim().is_empty() && !file.filename.contains(|c: char| c.is_control());
703            let content_type = file.content_type.split_once('/').is_some_and(|(kind, sub)| {
704                !kind.is_empty() && !sub.is_empty() && !file.content_type.contains(|c: char| c.is_whitespace())
705            });
706            let content_id = file
707                .content_id
708                .as_deref()
709                .is_none_or(|id| !id.is_empty() && id.chars().all(|c| c.is_ascii_alphanumeric() || ".-_".contains(c)));
710            if !(filename && content_type && content_id) {
711                return Err(Error::internal(format!(
712                    "cannot send email: attachment {:?} ({:?}, content id {:?}) is invalid. Fix: give a file \
713                     name, a MIME type such as \"application/pdf\", and a content id of letters, digits and .-_",
714                    file.filename, file.content_type, file.content_id
715                )));
716            }
717        }
718        Ok(Self { from, email })
719    }
720
721    /// Addresses of `list`, without display names (the Cloudflare binding takes bare addresses).
722    pub fn addresses(list: &[String]) -> Vec<String> {
723        list.iter().filter_map(|address| Mailbox::parse(address)).map(|mailbox| mailbox.address).collect()
724    }
725
726    /// What the `log` adapter prints: headers, text, HTML and attachments,
727    /// framed by [`LOG_PREFIX`] lines.
728    pub fn log_text(&self) -> String {
729        let email = &self.email;
730        let mut out = format!(
731            "{LOG_PREFIX} not sent ({MAIL_ADAPTER} = \"log\")\nFrom: {}\nTo: {}\n",
732            self.from,
733            email.to.join(", ")
734        );
735        for (name, list) in [("Cc", &email.cc), ("Bcc", &email.bcc)] {
736            if !list.is_empty() {
737                out.push_str(&format!("{name}: {}\n", list.join(", ")));
738            }
739        }
740        if let Some(reply_to) = &email.reply_to {
741            out.push_str(&format!("Reply-To: {reply_to}\n"));
742        }
743        for (name, value) in &email.headers {
744            out.push_str(&format!("{name}: {value}\n"));
745        }
746        out.push_str(&format!("Subject: {}\n\n{}\n", email.subject, email.text));
747        if let Some(html) = &email.html {
748            out.push_str(&format!("{LOG_PREFIX} HTML version:\n{html}\n"));
749        }
750        for file in &email.attachments {
751            let kind = match &file.content_id {
752                Some(id) => format!("inline cid:{id}"),
753                None => "attachment".to_owned(),
754            };
755            out.push_str(&format!(
756                "{LOG_PREFIX} {kind}: {} ({}, {} bytes)\n",
757                file.filename,
758                file.content_type,
759                file.content.len()
760            ));
761        }
762        out.push_str(&format!("{LOG_PREFIX} end"));
763        out
764    }
765
766    /// Body of `POST https://api.resend.com/emails`.
767    pub fn resend_json(&self) -> Value {
768        use base64::{Engine, engine::general_purpose::STANDARD};
769        let email = &self.email;
770        let mut body =
771            json!({ "from": self.from.to_string(), "to": email.to, "subject": email.subject, "text": email.text });
772        for (key, list) in [("cc", &email.cc), ("bcc", &email.bcc)] {
773            if !list.is_empty() {
774                body[key] = json!(list);
775            }
776        }
777        if let Some(html) = &email.html {
778            body["html"] = json!(html);
779        }
780        if let Some(reply_to) = &email.reply_to {
781            body["reply_to"] = json!(reply_to);
782        }
783        if !email.headers.is_empty() {
784            body["headers"] = email.headers.iter().map(|(name, value)| (name.clone(), json!(value))).collect();
785        }
786        if !email.attachments.is_empty() {
787            let files = email.attachments.iter().map(|file| {
788                let mut entry = json!({
789                    "filename": file.filename,
790                    "content": STANDARD.encode(&file.content),
791                    "content_type": file.content_type,
792                });
793                if let Some(id) = &file.content_id {
794                    entry["content_id"] = json!(id);
795                }
796                entry
797            });
798            body["attachments"] = files.collect();
799        }
800        body
801    }
802}
803
804/// Resend's endpoint for sending one email.
805pub(crate) const RESEND_URL: &str = "https://api.resend.com/emails";
806
807/// Error for a non-2xx Resend answer (`{"statusCode", "name", "message"}`).
808pub(crate) fn resend_error(status: u16, body: &str) -> Error {
809    let parsed: Value = serde_json::from_str(body).unwrap_or(Value::Null);
810    let message = parsed["message"].as_str().unwrap_or(body);
811    let fix = match status {
812        401 | 403 => {
813            "check the RESEND_API_KEY secret, and that MAIL_FROM uses a domain verified at https://resend.com/domains"
814        }
815        429 => "Resend's rate or daily quota was reached (free plan: 100 emails a day, 3,000 a month)",
816        _ => "see https://resend.com/docs/api-reference/errors",
817    };
818    Error::internal(format!("Resend did not send the email ({status}: {message}). Fix: {fix}"))
819}
820
821/// Error for a failed `send_email` binding call.
822pub(crate) fn cloudflare_error(detail: &str) -> Error {
823    Error::internal(format!(
824        "Cloudflare Email Service did not send the email ({detail}). Fix: MAIL_FROM must use a domain onboarded to \
825         Email Service; sending to any recipient needs the Workers Paid plan, while the free plan can only send \
826         to verified destination addresses of the account (or use MAIL_ADAPTER = \"resend\")"
827    ))
828}
829
830#[cfg(test)]
831#[path = "../tests/mail.rs"]
832mod tests;