Skip to main content

intercept

Function intercept 

Source
pub fn intercept(
    interceptor: impl Fn(Email, &dyn Fn(&str) -> Option<String>) -> Option<Email> + Send + Sync + 'static,
)
Expand description

Registers an interceptor every outgoing email goes through, in registration order, before the adapter sends it.

Rails’ register_interceptor: interceptor gets the Email and a lookup of Worker variables and secrets, and returns the email to send (rewritten, e.g. every recipient replaced on a staging copy) or None to drop it, logged as [ocre mail] dropped by an interceptor: .... It applies to send and to emails sent from the queue (deliver_later), whatever the adapter, log included. Register interceptors once per Worker instance, in the start event of src/lib.rs.

§Examples

A safety switch for automated emails on a copy of production’s users: marketing emails carry X-Category: marketing, and go out only when the MARKETING_EMAILS variable is on.

#[worker::event(start)]
fn start() {
    ocre::mail::intercept(|email, vars| {
        let marketing = email.headers.iter().any(|(name, value)| name == "X-Category" && value == "marketing");
        let allowed = vars("MARKETING_EMAILS").is_some_and(|value| value.trim() == "on");
        (!marketing || allowed).then_some(email)
    });
}