Skip to main content

larust_mail/
send.rs

1use crate::Mailable;
2use larust_core::AppError;
3use lettre::message::{header::ContentType, Mailbox};
4use lettre::transport::smtp::authentication::Credentials;
5use lettre::{AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor};
6
7/// Entry point for Laravel's `Mail::to($user)->send(new WelcomeMail($user))`.
8pub fn mail() -> MailBuilder {
9    MailBuilder { to: Vec::new() }
10}
11
12#[must_use]
13pub struct MailBuilder {
14    to: Vec<String>,
15}
16
17impl MailBuilder {
18    /// Adds a recipient - callable more than once for multiple recipients.
19    pub fn to(mut self, email: impl Into<String>) -> Self {
20        self.to.push(email.into());
21        self
22    }
23
24    /// Sends `mailable` to every address given to `to(...)` so far.
25    ///
26    /// If `crate::fake::fake()` has been called anywhere in this process,
27    /// this records the rendered subject/body/recipients instead of
28    /// dispatching at all - checked *before* `mail_driver` is even read,
29    /// so `Mail::fake()` overrides log/smtp regardless of configuration,
30    /// matching Laravel's own `Mail::fake()`. Otherwise dispatches on
31    /// `mail_driver` via [`deliver`] - see [`Self::queue`] for the
32    /// deferred-delivery sibling of this method.
33    pub async fn send<M: Mailable>(self, mailable: M) -> Result<(), AppError> {
34        let subject = mailable.subject();
35        let body = mailable.html_body();
36
37        // Checked before building a `SentMail` at all - the common,
38        // real-dispatch case (`fake()` never called) shouldn't pay for
39        // cloning the rendered body/recipients (a full HTML email) just
40        // to immediately drop them.
41        if crate::fake::is_active() {
42            crate::fake::record(crate::fake::SentMail {
43                mailable_type: std::any::type_name::<M>(),
44                to: self.to,
45                subject,
46                html_body: body,
47            });
48            return Ok(());
49        }
50
51        deliver(&self.to, &subject, &body).await
52    }
53
54    /// Enqueues `mailable` for asynchronous delivery instead of sending it
55    /// immediately - Laravel's `Mail::to($user)->queue(new WelcomeMail($user))`.
56    ///
57    /// `Mailable` deliberately has no `Serialize`/`'static` bound (the real
58    /// `WelcomeMail<'a>` in `demo/app/Mail/welcome_mail.rs` borrows), so
59    /// this can't serialize the typed `mailable` itself the way an
60    /// app-defined `larust_queue::Job` would. Instead it renders
61    /// `subject()`/`html_body()` *eagerly, synchronously, right here* -
62    /// the exact same rendering `send()` already does - and enqueues only
63    /// the already-rendered `{to, subject, html_body}` via the
64    /// framework-owned [`crate::MailJob`]. **This is a deliberate,
65    /// documented deviation from Laravel**: Laravel's `Mail::queue(...)`
66    /// stores a serialized *reference* to the mailable's own data and
67    /// re-renders fresh on the worker at send time (so DB changes between
68    /// queue-time and send-time are reflected, and rendering work moves
69    /// off the request thread); this implementation defers *delivery*
70    /// (the SMTP/network I/O) but not *rendering* - the HTML is frozen at
71    /// the moment `.queue()` is called. Replicating Laravel's
72    /// re-resolve-on-worker behavior would need a `SerializesModels`-style
73    /// generic model-lookup mechanism this framework doesn't have.
74    ///
75    /// Respects `Mail::fake()` exactly like `send()` does - a faked
76    /// `.queue()` call records into the same `SentMail` list `send()`
77    /// uses (there's no separate `assertQueued` concept yet; see
78    /// `docs/ARCHITECTURE.md`'s Mail section) and never touches the real
79    /// queue.
80    ///
81    /// `xr new`'s scaffold registers `larust_support::mail::MailJob` in
82    /// every generated app's `queue:work` branch by default, so queued
83    /// mail works out of the box - but it's still a plain, real
84    /// registration line an app can remove, not runtime magic. An app
85    /// that removes it (or was scaffolded before this default existed)
86    /// sees an unregistered `MailJob` land in `failed_jobs`, the same
87    /// failure mode as any other unregistered job type.
88    pub async fn queue<M: Mailable>(self, mailable: M) -> Result<(), AppError> {
89        let subject = mailable.subject();
90        let body = mailable.html_body();
91
92        if crate::fake::is_active() {
93            crate::fake::record(crate::fake::SentMail {
94                mailable_type: std::any::type_name::<M>(),
95                to: self.to,
96                subject,
97                html_body: body,
98            });
99            return Ok(());
100        }
101
102        larust_queue::dispatch(&crate::MailJob {
103            to: self.to,
104            subject,
105            html_body: body,
106        })
107        .await
108    }
109}
110
111/// Dispatches an already-rendered `{to, subject, html_body}` on
112/// `Config::mail_driver`: `"smtp"` sends for real via [`deliver_via_smtp`];
113/// anything else (default `"log"`, the scaffold default) writes the
114/// rendered mail to `tracing::info!` and returns - no network touched, no
115/// SMTP server needed for local dev or `cargo test`. Shared by
116/// `MailBuilder::send`'s real-dispatch path and [`crate::MailJob::handle`]
117/// (the queued-mail worker path), so both go through identical
118/// driver-selection logic.
119pub(crate) async fn deliver(to: &[String], subject: &str, body: &str) -> Result<(), AppError> {
120    let config = larust_core::config();
121    match config.mail_driver.as_str() {
122        "smtp" => deliver_via_smtp(to, subject, body).await,
123        _ => {
124            tracing::info!(
125                ?to,
126                subject = %subject,
127                body = %body,
128                "mail (log driver, not sent)"
129            );
130            Ok(())
131        }
132    }
133}
134
135async fn deliver_via_smtp(to: &[String], subject: &str, body: &str) -> Result<(), AppError> {
136    let config = larust_core::config();
137
138    let from_address: lettre::Address = config
139        .mail_from_address
140        .parse()
141        .map_err(|source| AppError::Config(Box::new(source)))?;
142    let from = Mailbox::new(Some(config.mail_from_name.clone()), from_address);
143
144    let mut builder = Message::builder().from(from).subject(subject);
145    for address in to {
146        // A recipient address, not a config value (it can come from
147        // arbitrary data, e.g. a user's own `email` column) - `Internal`,
148        // not `Config`, so a caller that doesn't treat this as
149        // best-effort sees an accurate error category.
150        let mailbox: Mailbox = address
151            .parse()
152            .map_err(|source| AppError::Internal(Box::new(source)))?;
153        builder = builder.to(mailbox);
154    }
155    let message = builder
156        .header(ContentType::TEXT_HTML)
157        .body(body.to_string())
158        .map_err(|source| AppError::Internal(Box::new(source)))?;
159
160    let transport = build_transport(config)?;
161    transport
162        .send(message)
163        .await
164        .map_err(|source| AppError::Internal(Box::new(source)))?;
165
166    Ok(())
167}
168
169fn build_transport(
170    config: &larust_core::Config,
171) -> Result<AsyncSmtpTransport<Tokio1Executor>, AppError> {
172    let builder = match config.mail_encryption.as_str() {
173        "starttls" => AsyncSmtpTransport::<Tokio1Executor>::starttls_relay(&config.mail_host),
174        // No TLS at all - `builder_dangerous` doesn't stop credentials
175        // (below) from also being attached, so pairing `MAIL_ENCRYPTION=none`
176        // with real `MAIL_USERNAME`/`MAIL_PASSWORD` sends SMTP AUTH over a
177        // plaintext socket. Only reachable by deliberately opting into
178        // `"none"`; there's no misconfiguration path into this branch.
179        "none" => Ok(AsyncSmtpTransport::<Tokio1Executor>::builder_dangerous(
180            &config.mail_host,
181        )),
182        // "tls" and anything else default to implicit TLS - the common
183        // case (port 465) and the safest default if `MAIL_ENCRYPTION` is
184        // ever misconfigured to an unrecognized value.
185        _ => AsyncSmtpTransport::<Tokio1Executor>::relay(&config.mail_host),
186    }
187    .map_err(|source| AppError::Config(Box::new(source)))?;
188
189    let mut builder = builder.port(config.mail_port);
190    if !config.mail_username.is_empty() {
191        builder = builder.credentials(Credentials::new(
192            config.mail_username.clone(),
193            config.mail_password.clone(),
194        ));
195    }
196
197    Ok(builder.build())
198}
199
200#[cfg(test)]
201mod tests {
202    use super::*;
203    use larust_core::Config;
204
205    fn test_config(encryption: &str) -> Config {
206        Config {
207            app_name: "Test App".to_string(),
208            app_env: "testing".to_string(),
209            app_port: 8000,
210            session_secure_cookie: true,
211            app_debug: false,
212            app_url: "http://example.test".to_string(),
213            app_locale: "en".to_string(),
214            app_fallback_locale: "en".to_string(),
215            api_prefix: "/api".to_string(),
216            mail_driver: "smtp".to_string(),
217            mail_host: "smtp.example.test".to_string(),
218            mail_port: 587,
219            mail_username: String::new(),
220            mail_password: String::new(),
221            mail_encryption: encryption.to_string(),
222            mail_from_address: "hello@example.test".to_string(),
223            mail_from_name: "Test App".to_string(),
224            cache_driver: "database".to_string(),
225            queue_driver: "database".to_string(),
226            log_channel: "stdout".to_string(),
227            log_level: String::new(),
228            log_max_size: 10 * 1024 * 1024,
229            log_keep_files: 5,
230            deploy_type: "web".to_string(),
231            session_driver: "database".to_string(),
232        }
233    }
234
235    #[test]
236    fn build_transport_succeeds_for_implicit_tls() {
237        assert!(build_transport(&test_config("tls")).is_ok());
238    }
239
240    #[test]
241    fn build_transport_succeeds_for_starttls() {
242        assert!(build_transport(&test_config("starttls")).is_ok());
243    }
244
245    #[test]
246    fn build_transport_succeeds_for_no_encryption() {
247        assert!(build_transport(&test_config("none")).is_ok());
248    }
249
250    #[test]
251    fn build_transport_falls_back_to_implicit_tls_for_an_unrecognized_value() {
252        // The safest default if `MAIL_ENCRYPTION` is ever misconfigured -
253        // still succeeds, doesn't error out.
254        assert!(build_transport(&test_config("carrier-pigeon")).is_ok());
255    }
256
257    #[test]
258    fn build_transport_only_sets_credentials_when_a_username_is_configured() {
259        let mut config = test_config("tls");
260        config.mail_username = "user".to_string();
261        config.mail_password = "secret".to_string();
262        assert!(build_transport(&config).is_ok());
263    }
264}