Skip to main content

Module mailable

Module mailable 

Source
Expand description

Laravel-shape Mailable trait — declare an email type as a struct that owns its template + recipient logic. Pairs with email_templates::EmailRenderer (rendering) and email_jobs (off-request delivery). See mailable::Mailable. Laravel-shape Mailable trait — declare an email type as a struct that owns its own template + recipient logic. Pairs with crate::email_templates::EmailRenderer (template rendering) and crate::email_jobs (off-request delivery).

§Why

Without this, building one email looks like:

let mut ctx = Context::new();
ctx.insert("name", &user.name);
ctx.insert("url", &reset_url);
let email = renderer.render("password_reset", &ctx)?
    .to(&user.email)
    .from("noreply@example.com");
mailer.send(&email).await?;

With a Mailable, the email type owns the template + recipient logic, so call sites are a one-liner:

PasswordReset { user: user.clone(), reset_url }
    .send(&renderer, &mailer).await?;

// Or via the job queue:
PasswordReset { user, reset_url }.dispatch(&renderer, &queue).await?;

§Defining a Mailable

use rustango::mailable::Mailable;
use rustango::email::Email;
use rustango::email_templates::EmailRenderer;
use tera::Context;

struct PasswordReset {
    pub user: User,
    pub reset_url: String,
}

impl Mailable for PasswordReset {
    const TEMPLATE: &'static str = "password_reset";

    fn build(&self, base: Email) -> Email {
        base.to(&self.user.email)
            .from("noreply@example.com")
            .reply_to("support@example.com")
    }

    fn context(&self) -> Context {
        let mut c = Context::new();
        c.insert("name", &self.user.name);
        c.insert("url", &self.reset_url);
        c
    }
}

Enums§

MailableError

Traits§

Mailable
One sendable email type. The struct holds whatever per-instance state it needs (recipient, IDs, URLs) and Mailable glues it to a Tera template + recipient + sender logic.