Skip to main content

ocre/runtime/
mail.rs

1use std::time::Duration;
2
3use wasm_bindgen::{JsCast, JsValue};
4use worker::{
5    EmailAddress, EmailAttachment, Env, Fetch, ForwardableEmailMessage, Headers, Method, Request, RequestInit,
6    SendEmailBuilder, send::SendFuture,
7};
8
9use super::Ctx;
10use crate::{
11    Error, Result,
12    jobs::{DEFAULT_QUEUE, Payload},
13    mail::{
14        APP_URL, Adapter, Attachment, EMAIL_BINDING, Email, LOG_PREFIX, MAIL_ADAPTER, MAIL_FROM, Message, Outgoing,
15        RESEND_API_KEY, RESEND_URL, absolute_url, adapter_for, cloudflare_error, resend_error, resend_key,
16    },
17};
18
19/// Sends `email` now, from `MAIL_FROM`, with the adapter named by `MAIL_ADAPTER`.
20///
21/// `log` prints the whole email to the Worker console between
22/// [`LOG_PREFIX`](crate::mail::LOG_PREFIX) lines and sends nothing; `resend`
23/// makes one `POST https://api.resend.com/emails` subrequest; `cloudflare`
24/// calls the [`EMAIL_BINDING`](crate::mail::EMAIL_BINDING) send_email
25/// binding. The request waits for the provider; use
26/// [`deliver_later`](crate::mail::deliver_later) to answer first and retry failures.
27///
28/// The returned future is `Send`, so axum handlers can await it.
29///
30/// Free-plan limits (September 2026): Resend sends 100 emails a day and 3,000
31/// a month from one domain, to any recipient; Cloudflare Email Service on
32/// Workers Free only delivers to verified destination addresses of the account.
33///
34/// # Errors
35///
36/// - [`Error::BadRequest`](crate::Error::BadRequest) (400): a recipient (`to`, `cc`, `bcc`) or `reply_to` is not an email address.
37/// - [`Error::Internal`](crate::Error::Internal) (500), with a log message naming the fix:
38///   `MAIL_ADAPTER` unset or unknown; `MAIL_FROM` unset or not an address; a
39///   subject that is empty or spans several lines; the `RESEND_API_KEY`
40///   secret or the `EMAIL: bindings.sendEmail()` binding missing; the
41///   provider refused the email (e.g. Resend's quota reached, an unverified
42///   domain or recipient) or could not be reached.
43///
44/// # Examples
45///
46/// ```no_run
47/// use axum::extract::State;
48/// use ocre::mail::Email;
49/// use ocre::{Ctx, Result};
50///
51/// async fn invite(State(ctx): State<Ctx>) -> Result<&'static str> {
52///     let email = Email::new("ada@example.com", "You're invited", "Join us: https://example.com/join");
53///     ocre::mail::send(&ctx, email).await?;
54///     Ok("invited")
55/// }
56/// ```
57pub fn send(ctx: &Ctx, email: Email) -> impl Future<Output = Result<()>> + Send + use<> {
58    let env = ctx.env().clone();
59    SendFuture::new(async move { deliver(&env, email).await })
60}
61
62/// Checks `email` now and sends it later from the background jobs queue, like Rails' `deliver_later`.
63///
64/// The address, `MAIL_FROM` and `MAIL_ADAPTER` are checked right away, like
65/// [`send`](crate::mail::send), so a bad address is still a 400 for the
66/// request. The email is then put on the `JOBS` queue and the handler answers
67/// without waiting for the provider; [`consume`](crate::jobs::consume) sends
68/// it with [`send`](crate::mail::send), logs `[ocre jobs] mail done`, and on
69/// failure retries it with the jobs backoff (30 s, 1 min, 3 min, 9 min, 27
70/// min) before the dead-letter queue. The Resend key and the send_email
71/// binding are only looked up when the consumer sends.
72///
73/// Needs the `JOBS` queue: run `ocre g job <Name>` once to wire it.
74///
75/// Free-plan cost: one queue message, i.e. 3 of the 10,000 daily Queues
76/// operations (write, read, delete), one more read per retry and one more
77/// write if it is dead-lettered; plus the provider's limits of
78/// [`send`](crate::mail::send).
79///
80/// # Errors
81///
82/// - [`Error::BadRequest`](crate::Error::BadRequest) (400): a recipient or `reply_to` is not an email address.
83/// - [`Error::Internal`](crate::Error::Internal) (500): `MAIL_ADAPTER` unset or
84///   unknown, `MAIL_FROM` unset or not an address, a subject that is empty or
85///   spans several lines, an email over the 128 KB queue message limit, the
86///   `JOBS` queue binding missing from cloudflare.config.ts, or
87///   Queues refusing the message.
88///
89/// # Examples
90///
91/// ```no_run
92/// use axum::extract::State;
93/// use ocre::mail::Email;
94/// use ocre::{Ctx, Result};
95///
96/// async fn sign_up(State(ctx): State<Ctx>) -> Result<&'static str> {
97///     let email = Email::new("ada@example.com", "Welcome", "Hello Ada");
98///     ocre::mail::deliver_later(&ctx, email).await?;
99///     Ok("check your inbox")
100/// }
101/// ```
102pub fn deliver_later(ctx: &Ctx, email: Email) -> impl Future<Output = Result<()>> + Send + use<> {
103    deliver_in(ctx, email, Duration::ZERO)
104}
105
106/// Checks `email` now and sends it from the jobs queue after `delay`, like Rails' `deliver_later(wait:)`.
107///
108/// Works like [`deliver_later`](crate::mail::deliver_later), with the
109/// message due after `delay` (whole seconds, 24 hours at most, Queues'
110/// limit): a reminder an hour after sign-up, a digest at the end of the
111/// day. Same free-plan cost as [`deliver_later`](crate::mail::deliver_later).
112///
113/// # Errors
114///
115/// Those of [`deliver_later`](crate::mail::deliver_later), plus an
116/// [`Error::Internal`](crate::Error::Internal) when `delay` is over 24 hours.
117///
118/// # Examples
119///
120/// ```no_run
121/// use std::time::Duration;
122///
123/// use ocre::mail::Email;
124///
125/// async fn remind(ctx: &ocre::Ctx) -> ocre::Result<()> {
126///     let email = Email::new("ada@example.com", "Finish setting up your shop", "https://example.com/setup");
127///     ocre::mail::deliver_in(ctx, email, Duration::from_secs(3600)).await
128/// }
129/// ```
130pub fn deliver_in(ctx: &Ctx, email: Email, delay: Duration) -> impl Future<Output = Result<()>> + Send + use<> {
131    let env = ctx.env();
132    let checked = adapter_for(var(env, MAIL_ADAPTER).as_deref(), &email)
133        .and_then(|_| Outgoing::new(var(env, MAIL_FROM), email))
134        .map(|outgoing| Payload::Mail(Box::new(outgoing.email)));
135    super::jobs::send(env.clone(), DEFAULT_QUEUE, checked, delay)
136}
137
138fn var(env: &Env, name: &str) -> Option<String> {
139    env.var(name).ok().map(|value| value.to_string())
140}
141
142/// An absolute URL for `path` on the app's public address, the [`APP_URL`](crate::mail::APP_URL) variable (Rails' `_url` helpers in mailers).
143///
144/// For links and images in emails, which mail clients open outside the app:
145/// `url(ctx, "/posts/1")` is `https://shop.example.com/posts/1`. A `path`
146/// that is already absolute is returned as is. It reads a variable, no
147/// binding call, so mailers and jobs can use it outside any request.
148///
149/// # Errors
150///
151/// [`Error::Internal`](crate::Error::Internal) (500) when `APP_URL` is unset
152/// or not an `http(s)` address, naming the fix.
153///
154/// # Examples
155///
156/// ```no_run
157/// use ocre::{Ctx, Result, mail::{self, Email}};
158///
159/// fn reset_email(ctx: &Ctx, to: &str, token: &str) -> Result<Email> {
160///     let link = mail::url(ctx, &format!("/password/reset/{token}"))?;
161///     let logo = mail::url(ctx, "/images/logo.png")?;
162///     Ok(Email::new(to, "Reset your password", format!("Open {link}"))
163///         .html(format!("<img src=\"{logo}\" alt=\"\"><p><a href=\"{link}\">Reset your password</a></p>")))
164/// }
165/// # let _ = reset_email;
166/// ```
167pub fn url(ctx: &Ctx, path: &str) -> Result<String> {
168    absolute_url(var(ctx.env(), APP_URL), path)
169}
170
171pub(crate) async fn deliver(env: &Env, email: Email) -> Result<()> {
172    let dropped = crate::mail::dropped_line(&email);
173    let Some(email) = crate::mail::intercepted(email, &|name| var(env, name)) else {
174        worker::console_log!("{dropped}");
175        return Ok(());
176    };
177    let adapter = adapter_for(var(env, MAIL_ADAPTER).as_deref(), &email)?;
178    let outgoing = Outgoing::new(var(env, MAIL_FROM), email)?;
179    match adapter {
180        Adapter::Log => {
181            worker::console_log!("{}", outgoing.log_text());
182            crate::mail::capture(outgoing);
183            Ok(())
184        }
185        Adapter::Resend => resend(env, &outgoing).await,
186        Adapter::Cloudflare => cloudflare(env, &outgoing).await,
187    }
188}
189
190async fn resend(env: &Env, outgoing: &Outgoing) -> Result<()> {
191    let key = resend_key(super::secrets::lookup(env, RESEND_API_KEY).await?)?;
192    let headers = Headers::new();
193    headers.set("Authorization", &format!("Bearer {key}"))?;
194    headers.set("Content-Type", "application/json")?;
195    let mut init = RequestInit::new();
196    init.with_method(Method::Post)
197        .with_headers(headers)
198        .with_body(Some(JsValue::from_str(&outgoing.resend_json().to_string())));
199    let mut response = Fetch::Request(Request::new_with_init(RESEND_URL, &init)?).send().await?;
200    let status = response.status_code();
201    if (200..300).contains(&status) {
202        Ok(())
203    } else {
204        Err(resend_error(status, &response.text().await.unwrap_or_default()))
205    }
206}
207
208async fn cloudflare(env: &Env, outgoing: &Outgoing) -> Result<()> {
209    let binding = env.send_email(EMAIL_BINDING).map_err(|err| {
210        Error::internal(format!(
211            "cannot send email: the send_email binding `{EMAIL_BINDING}` is missing ({err}). Fix: add \
212             `{EMAIL_BINDING}: bindings.sendEmail(),` to worker.env in cloudflare.config.ts"
213        ))
214    })?;
215    let Outgoing { from, email } = outgoing;
216    let to = Outgoing::addresses(&email.to);
217    let builder = match &from.name {
218        Some(name) => SendEmailBuilder::builder_with_email_address_and_slice(
219            &EmailAddress::new(name, &from.address),
220            &to,
221            &email.subject,
222        ),
223        None => SendEmailBuilder::builder_with_str_and_slice(&from.address, &to, &email.subject),
224    };
225    let mut builder = builder.text(&email.text);
226    if let Some(html) = &email.html {
227        builder = builder.html(html);
228    }
229    if let Some(reply_to) = &email.reply_to {
230        builder = builder.reply_to(reply_to);
231    }
232    if !email.cc.is_empty() {
233        builder = builder.cc_with_slice(&Outgoing::addresses(&email.cc));
234    }
235    if !email.bcc.is_empty() {
236        builder = builder.bcc_with_slice(&Outgoing::addresses(&email.bcc));
237    }
238    if !email.headers.is_empty() {
239        let headers = worker::js_sys::Object::new();
240        for (name, value) in &email.headers {
241            // Setting a property on a plain object cannot fail.
242            let _ = worker::js_sys::Reflect::set(&headers, &JsValue::from_str(name), &JsValue::from_str(value));
243        }
244        builder = builder.headers(headers.unchecked_ref());
245    }
246    if !email.attachments.is_empty() {
247        let files: Vec<EmailAttachment> = email
248            .attachments
249            .iter()
250            .map(|file| {
251                let bytes = worker::js_sys::Uint8Array::from(file.content.as_slice());
252                match &file.content_id {
253                    Some(id) => {
254                        EmailAttachment::new_inline_with_typed_array(id, &file.filename, &file.content_type, &bytes)
255                    }
256                    None => {
257                        EmailAttachment::new_attachment_with_typed_array(&file.filename, &file.content_type, &bytes)
258                    }
259                }
260            })
261            .collect();
262        builder = builder.attachments(&files);
263    }
264    binding.send_with_builder(&builder.build()).await.map_err(|err| cloudflare_error(&js_error(&err)))?;
265    Ok(())
266}
267
268/// `message` of a JS error, plus its `code` (`E_SENDER_NOT_VERIFIED`, ...) when set.
269fn js_error(err: &worker::js_sys::Error) -> String {
270    let message = String::from(err.message());
271    match worker::js_sys::Reflect::get(err, &JsValue::from_str("code")).ok().and_then(|code| code.as_string()) {
272        Some(code) => format!("{code}: {message}"),
273        None => message,
274    }
275}
276
277/// An email that Cloudflare Email Routing delivered to the Worker, handed to the app's mailbox.
278///
279/// [`receive`](crate::mail::receive) builds it. The envelope ([`from`](Self::from), [`to`](Self::to)) comes from
280/// Cloudflare; headers and bodies are parsed from the raw message
281/// (multipart, quoted-printable, base64, RFC 2047 encoded words; files in
282/// [`attachments`](Self::attachments), the bytes in [`raw`](Self::raw)). Bounce it with
283/// [`reject`](Self::reject) or pass it on with [`forward`](Self::forward).
284/// Receiving is free and unlimited on every plan.
285///
286/// # Examples
287///
288/// ```no_run
289/// use ocre::mail::InboundEmail;
290/// use ocre::{Ctx, Result};
291///
292/// // src/mailbox.rs
293/// pub async fn receive(_ctx: Ctx, email: InboundEmail) -> Result<()> {
294///     match email.to() {
295///         "support@example.com" => email.forward("team@example.com").await?,
296///         _ => email.reject("Unknown address"),
297///     }
298///     Ok(())
299/// }
300/// ```
301pub struct InboundEmail {
302    inner: ForwardableEmailMessage,
303    from: String,
304    to: String,
305    raw: Vec<u8>,
306    message: Message,
307}
308
309impl InboundEmail {
310    /// Returns the envelope sender (SMTP `MAIL FROM`), checked by Cloudflare.
311    ///
312    /// The `From` header may differ: read it with `email.header("From")`.
313    ///
314    /// # Examples
315    ///
316    /// ```no_run
317    /// # async fn mailbox(email: ocre::mail::InboundEmail) {
318    /// if email.from().ends_with("@example.com") {
319    ///     // a colleague
320    /// }
321    /// # }
322    /// ```
323    pub fn from(&self) -> &str {
324        &self.from
325    }
326
327    /// Returns the envelope recipient: the address of this app that received the email.
328    ///
329    /// Match on it to route several addresses to one Worker.
330    ///
331    /// # Examples
332    ///
333    /// ```no_run
334    /// # async fn mailbox(email: ocre::mail::InboundEmail) {
335    /// let team = email.to().starts_with("support@");
336    /// # let _ = team;
337    /// # }
338    /// ```
339    pub fn to(&self) -> &str {
340        &self.to
341    }
342
343    /// Returns the decoded `Subject` header, or `""` when it is missing.
344    ///
345    /// # Examples
346    ///
347    /// ```no_run
348    /// # async fn mailbox(email: ocre::mail::InboundEmail) {
349    /// let urgent = email.subject().contains("URGENT");
350    /// # let _ = urgent;
351    /// # }
352    /// ```
353    pub fn subject(&self) -> &str {
354        self.message.header("Subject").unwrap_or("")
355    }
356
357    /// Returns the first header with this name (case-insensitive), decoded.
358    ///
359    /// Folded lines are joined and RFC 2047 encoded words decoded. `None`
360    /// when the message has no such header.
361    ///
362    /// # Examples
363    ///
364    /// ```no_run
365    /// # async fn mailbox(email: ocre::mail::InboundEmail) {
366    /// let id = email.header("message-id").unwrap_or("");
367    /// # let _ = id;
368    /// # }
369    /// ```
370    pub fn header(&self, name: &str) -> Option<&str> {
371        self.message.header(name)
372    }
373
374    /// Returns every header, in message order, as decoded `(name, value)` pairs.
375    ///
376    /// Repeated headers (`Received`, ...) appear once per occurrence.
377    ///
378    /// # Examples
379    ///
380    /// ```no_run
381    /// # async fn mailbox(email: ocre::mail::InboundEmail) {
382    /// let hops = email.headers().iter().filter(|(name, _)| name.eq_ignore_ascii_case("Received")).count();
383    /// # let _ = hops;
384    /// # }
385    /// ```
386    pub fn headers(&self) -> &[(String, String)] {
387        &self.message.headers
388    }
389
390    /// Returns the first `text/plain` part, decoded to UTF-8, or `None` when there is none.
391    ///
392    /// # Examples
393    ///
394    /// ```no_run
395    /// # async fn mailbox(email: ocre::mail::InboundEmail) {
396    /// let body = email.text().unwrap_or_default();
397    /// # let _ = body;
398    /// # }
399    /// ```
400    pub fn text(&self) -> Option<&str> {
401        self.message.text.as_deref()
402    }
403
404    /// Returns the files of the email, decoded: every part that is not the first text or HTML body.
405    ///
406    /// Inline images carry their `content_id`. Store them in R2
407    /// (`ocre::storage`) rather than D1; they are the sender's files, so
408    /// check the type and size before keeping them.
409    ///
410    /// # Examples
411    ///
412    /// ```no_run
413    /// # async fn mailbox(email: ocre::mail::InboundEmail) {
414    /// for file in email.attachments() {
415    ///     worker::console_log!("{} ({}, {} bytes)", file.filename, file.content_type, file.content.len());
416    /// }
417    /// # }
418    /// ```
419    pub fn attachments(&self) -> &[Attachment] {
420        &self.message.attachments
421    }
422
423    /// Returns the first `text/html` part, decoded to UTF-8, or `None` when there is none.
424    ///
425    /// It is the sender's HTML: never render it unescaped.
426    ///
427    /// # Examples
428    ///
429    /// ```no_run
430    /// # async fn mailbox(email: ocre::mail::InboundEmail) {
431    /// let has_html = email.html().is_some();
432    /// # let _ = has_html;
433    /// # }
434    /// ```
435    pub fn html(&self) -> Option<&str> {
436        self.message.html.as_deref()
437    }
438
439    /// Returns the whole message as received (RFC 5322 bytes), e.g. to store it in R2 or read attachments.
440    ///
441    /// # Examples
442    ///
443    /// ```no_run
444    /// # async fn mailbox(email: ocre::mail::InboundEmail) {
445    /// let size = email.raw().len();
446    /// # let _ = size;
447    /// # }
448    /// ```
449    pub fn raw(&self) -> &[u8] {
450        &self.raw
451    }
452
453    /// Bounces the email: the sending server gets a permanent SMTP error with `reason`.
454    ///
455    /// The mailbox handler still returns normally; [`receive`](crate::mail::receive)
456    /// also bounces the email when the handler returns an `Err`.
457    ///
458    /// # Examples
459    ///
460    /// ```no_run
461    /// # async fn mailbox(email: ocre::mail::InboundEmail) {
462    /// if email.to() != "support@example.com" {
463    ///     email.reject("Unknown address");
464    /// }
465    /// # }
466    /// ```
467    pub fn reject(&self, reason: &str) {
468        self.inner.set_reject(reason);
469    }
470
471    /// Forwards the email unchanged to `to`, which must be a verified destination address of the Cloudflare account.
472    ///
473    /// # Errors
474    ///
475    /// [`Error::Internal`](crate::Error::Internal) when Cloudflare refuses, typically because
476    /// `to` is not a verified destination address in Email Routing (the
477    /// message says so).
478    ///
479    /// # Examples
480    ///
481    /// ```no_run
482    /// # async fn mailbox(email: ocre::mail::InboundEmail) -> ocre::Result<()> {
483    /// email.forward("team@example.com").await?;
484    /// # Ok(())
485    /// # }
486    /// ```
487    pub async fn forward(&self, to: &str) -> Result<()> {
488        self.inner.forward(to).await.map_err(|err| {
489            Error::internal(format!(
490                "forwarding the email to {to} failed ({}). Fix: add {to} as a verified destination address \
491                 in Cloudflare Email Routing",
492                js_error(&err)
493            ))
494        })?;
495        Ok(())
496    }
497}
498
499/// Runs the app's mailbox `handler` for an email from Cloudflare Email Routing; the Worker's `email` entry point.
500///
501/// Reads the raw message, parses it into an [`InboundEmail`], logs one
502/// `[ocre mail] received from <from> to <to>: <subject>` line and calls
503/// `handler(ctx, email)` with a fresh [`Ctx`](crate::Ctx). When the handler
504/// returns an `Err`, the error is logged (`[ocre mail] the mailbox failed:
505/// ...`) and the email bounced ("The message could not be processed"), so the
506/// sender knows it was not handled. Routing rules in the dashboard (Email
507/// Routing > Routing rules) send an address to the Worker; receiving is free
508/// and unlimited on every plan.
509///
510/// # Errors
511///
512/// A `worker::Error` only when the raw message cannot be read; handler
513/// errors are logged and bounce the email instead.
514///
515/// # Examples
516///
517/// `ocre g mailbox` writes the entry point in `src/lib.rs` and the handler in `src/mailbox.rs`:
518///
519/// ```no_run
520/// mod mailbox {
521///     use ocre::{Ctx, Result, mail::InboundEmail};
522///
523///     pub async fn receive(_ctx: Ctx, email: InboundEmail) -> Result<()> {
524///         email.forward("team@example.com").await
525///     }
526/// }
527///
528/// #[worker::event(email)]
529/// async fn email(
530///     message: worker::ForwardableEmailMessage,
531///     env: worker::Env,
532///     _ctx: worker::Context,
533/// ) -> worker::Result<()> {
534///     ocre::mail::receive(message, env, mailbox::receive).await
535/// }
536/// # fn main() {}
537/// ```
538pub async fn receive<F, Fut>(message: ForwardableEmailMessage, env: Env, handler: F) -> worker::Result<()>
539where
540    F: FnOnce(Ctx, InboundEmail) -> Fut,
541    Fut: Future<Output = Result<()>>,
542{
543    let raw = message.raw_bytes().await?;
544    let parsed = Message::parse(&raw);
545    let email = InboundEmail { from: message.from(), to: message.to(), raw, message: parsed, inner: message.clone() };
546    worker::console_log!("{LOG_PREFIX} received from {} to {}: {}", email.from(), email.to(), email.subject());
547    let ctx = Ctx::new(env);
548    if let Err(err) = handler(ctx.clone(), email).await {
549        worker::console_error!("{LOG_PREFIX} the mailbox failed: {err}");
550        super::jobs::report(&ctx, "ocre.mailbox", &err, []);
551        message.set_reject("The message could not be processed");
552    }
553    super::errors::flush(&ctx).await;
554    Ok(())
555}