Skip to main content

larastvel_core/mail/
mod.rs

1use std::collections::HashMap;
2use std::sync::Arc;
3
4use async_trait::async_trait;
5use lettre::{
6    message::header::ContentType, transport::smtp::authentication::Credentials, AsyncSmtpTransport,
7    AsyncTransport, Message, Tokio1Executor,
8};
9
10#[derive(Debug, thiserror::Error)]
11pub enum MailError {
12    #[error("Failed to build email: {0}")]
13    Build(String),
14    #[error("Failed to send email: {0}")]
15    Send(String),
16    #[error("Mailer error: {0}")]
17    General(String),
18}
19
20#[derive(Debug, Clone)]
21pub struct Mailable {
22    pub to: Vec<String>,
23    pub cc: Vec<String>,
24    pub bcc: Vec<String>,
25    pub from: Option<String>,
26    pub reply_to: Option<String>,
27    pub subject: String,
28    pub body: String,
29    pub content_type: ContentType,
30}
31
32impl Mailable {
33    pub fn new(to: Vec<String>, subject: &str, body: &str) -> Self {
34        Self {
35            to,
36            cc: Vec::new(),
37            bcc: Vec::new(),
38            from: None,
39            reply_to: None,
40            subject: subject.to_string(),
41            body: body.to_string(),
42            content_type: ContentType::TEXT_PLAIN,
43        }
44    }
45
46    pub fn html(to: Vec<String>, subject: &str, body: &str) -> Self {
47        Self {
48            to,
49            cc: Vec::new(),
50            bcc: Vec::new(),
51            from: None,
52            reply_to: None,
53            subject: subject.to_string(),
54            body: body.to_string(),
55            content_type: ContentType::TEXT_HTML,
56        }
57    }
58
59    pub fn from(mut self, from: &str) -> Self {
60        self.from = Some(from.to_string());
61        self
62    }
63
64    pub fn reply_to(mut self, reply_to: &str) -> Self {
65        self.reply_to = Some(reply_to.to_string());
66        self
67    }
68
69    pub fn cc(mut self, addresses: Vec<String>) -> Self {
70        self.cc = addresses;
71        self
72    }
73
74    pub fn bcc(mut self, addresses: Vec<String>) -> Self {
75        self.bcc = addresses;
76        self
77    }
78}
79
80#[async_trait]
81pub trait Mailer: Send + Sync + std::fmt::Debug {
82    async fn send(&self, mailable: Mailable) -> Result<(), MailError>;
83    fn name(&self) -> &str;
84}
85
86#[derive(Debug, Clone)]
87pub struct SmtpMailer {
88    name: String,
89    transport: AsyncSmtpTransport<Tokio1Executor>,
90}
91
92impl SmtpMailer {
93    pub fn new(
94        name: &str,
95        host: &str,
96        port: u16,
97        username: &str,
98        password: &str,
99    ) -> Result<Self, MailError> {
100        let creds = Credentials::new(username.to_string(), password.to_string());
101        let transport = AsyncSmtpTransport::<Tokio1Executor>::starttls_relay(host)
102            .map_err(|e| MailError::Build(e.to_string()))?
103            .port(port)
104            .credentials(creds)
105            .build();
106        Ok(Self {
107            name: name.to_string(),
108            transport,
109        })
110    }
111
112    pub fn new_without_auth(name: &str, host: &str, port: u16) -> Result<Self, MailError> {
113        let transport = AsyncSmtpTransport::<Tokio1Executor>::builder_dangerous(host)
114            .port(port)
115            .build();
116        Ok(Self {
117            name: name.to_string(),
118            transport,
119        })
120    }
121
122    pub fn relay(name: &str, host: &str) -> Result<Self, MailError> {
123        let transport = AsyncSmtpTransport::<Tokio1Executor>::relay(host)
124            .map_err(|e| MailError::Build(e.to_string()))?
125            .build();
126        Ok(Self {
127            name: name.to_string(),
128            transport,
129        })
130    }
131}
132
133#[async_trait]
134impl Mailer for SmtpMailer {
135    async fn send(&self, mailable: Mailable) -> Result<(), MailError> {
136        let from = mailable
137            .from
138            .clone()
139            .unwrap_or_else(|| "larastvel@localhost".to_string());
140
141        let mut message_builder = Message::builder()
142            .from(
143                from.parse::<lettre::message::Mailbox>()
144                    .map_err(|e| MailError::Build(e.to_string()))?,
145            )
146            .subject(&mailable.subject);
147
148        if mailable.to.is_empty() {
149            return Err(MailError::Build("No recipients specified".to_string()));
150        }
151
152        for addr in &mailable.to {
153            message_builder = message_builder.to(addr
154                .parse::<lettre::message::Mailbox>()
155                .map_err(|e| MailError::Build(e.to_string()))?);
156        }
157
158        for addr in &mailable.cc {
159            message_builder = message_builder.cc(addr
160                .parse::<lettre::message::Mailbox>()
161                .map_err(|e| MailError::Build(e.to_string()))?);
162        }
163
164        for addr in &mailable.bcc {
165            message_builder = message_builder.bcc(
166                addr.parse::<lettre::message::Mailbox>()
167                    .map_err(|e| MailError::Build(e.to_string()))?,
168            );
169        }
170
171        if let Some(reply_to) = &mailable.reply_to {
172            message_builder = message_builder.reply_to(
173                reply_to
174                    .parse::<lettre::message::Mailbox>()
175                    .map_err(|e| MailError::Build(e.to_string()))?,
176            );
177        }
178
179        let message = message_builder
180            .header(mailable.content_type)
181            .body(mailable.body)
182            .map_err(|e| MailError::Build(e.to_string()))?;
183
184        self.transport
185            .send(message)
186            .await
187            .map_err(|e| MailError::Send(e.to_string()))?;
188
189        Ok(())
190    }
191
192    fn name(&self) -> &str {
193        &self.name
194    }
195}
196
197#[derive(Debug, Clone)]
198pub struct LogMailer {
199    name: String,
200}
201
202impl LogMailer {
203    pub fn new(name: &str) -> Self {
204        Self {
205            name: name.to_string(),
206        }
207    }
208}
209
210#[async_trait]
211impl Mailer for LogMailer {
212    async fn send(&self, mailable: Mailable) -> Result<(), MailError> {
213        tracing::info!(
214            target: "larastvel::mail",
215            "📧 [{}] To: {:?} | Subject: {} | Body: {}",
216            self.name,
217            mailable.to,
218            mailable.subject,
219            if mailable.body.len() > 200 {
220                format!("{}... ({} bytes)", &mailable.body[..200], mailable.body.len())
221            } else {
222                mailable.body.clone()
223            },
224        );
225        Ok(())
226    }
227
228    fn name(&self) -> &str {
229        &self.name
230    }
231}
232
233#[derive(Debug, Clone)]
234pub struct MailManager {
235    mailers: HashMap<String, Arc<dyn Mailer>>,
236    default: String,
237}
238
239impl MailManager {
240    pub fn new(default: &str) -> Self {
241        Self {
242            mailers: HashMap::new(),
243            default: default.to_string(),
244        }
245    }
246
247    pub fn register<M: Mailer + 'static>(&mut self, name: &str, mailer: M) {
248        self.mailers.insert(name.to_string(), Arc::new(mailer));
249    }
250
251    pub fn mailer(&self, name: &str) -> Result<Arc<dyn Mailer>, MailError> {
252        self.mailers
253            .get(name)
254            .cloned()
255            .ok_or_else(|| MailError::General(format!("Mailer [{}] not configured", name)))
256    }
257
258    pub fn default_mailer(&self) -> Result<Arc<dyn Mailer>, MailError> {
259        self.mailer(&self.default)
260    }
261
262    pub fn set_default(&mut self, name: &str) {
263        self.default = name.to_string();
264    }
265
266    pub fn default_name(&self) -> &str {
267        &self.default
268    }
269
270    pub fn mailer_names(&self) -> Vec<String> {
271        self.mailers.keys().cloned().collect()
272    }
273}
274
275#[cfg(test)]
276mod tests {
277    use super::*;
278
279    #[tokio::test]
280    async fn test_log_mailer_send() {
281        let mailer = LogMailer::new("log");
282        let mailable = Mailable::new(
283            vec!["test@example.com".to_string()],
284            "Test Subject",
285            "Hello, this is a test email body.",
286        );
287        let result = mailer.send(mailable).await;
288        assert!(result.is_ok());
289    }
290
291    #[tokio::test]
292    async fn test_log_mailer_html() {
293        let mailer = LogMailer::new("log");
294        let mailable = Mailable::html(
295            vec!["user@example.com".to_string()],
296            "HTML Email",
297            "<h1>Hello</h1><p>World</p>",
298        );
299        let result = mailer.send(mailable).await;
300        assert!(result.is_ok());
301    }
302
303    #[tokio::test]
304    async fn test_log_mailer_name() {
305        let mailer = LogMailer::new("my-mailer");
306        assert_eq!(mailer.name(), "my-mailer");
307    }
308
309    #[tokio::test]
310    async fn test_log_mailer_multiple_recipients() {
311        let mailer = LogMailer::new("log");
312        let mailable = Mailable::new(
313            vec![
314                "alice@example.com".to_string(),
315                "bob@example.com".to_string(),
316            ],
317            "Multiple",
318            "To multiple recipients",
319        );
320        let result = mailer.send(mailable).await;
321        assert!(result.is_ok());
322    }
323
324    #[tokio::test]
325    async fn test_log_mailer_with_cc_bcc() {
326        let mailer = LogMailer::new("log");
327        let mailable = Mailable::new(
328            vec!["to@example.com".to_string()],
329            "CC Test",
330            "With CC and BCC",
331        )
332        .cc(vec!["cc@example.com".to_string()])
333        .bcc(vec!["bcc@example.com".to_string()])
334        .from("sender@example.com")
335        .reply_to("reply@example.com");
336
337        let result = mailer.send(mailable).await;
338        assert!(result.is_ok());
339    }
340
341    #[tokio::test]
342    async fn test_mailable_builder() {
343        let m = Mailable::new(vec!["a@b.com".to_string()], "Subject", "Body")
344            .from("f@b.com")
345            .reply_to("r@b.com")
346            .cc(vec!["c@b.com".to_string()])
347            .bcc(vec!["d@b.com".to_string()]);
348
349        assert_eq!(m.from, Some("f@b.com".to_string()));
350        assert_eq!(m.reply_to, Some("r@b.com".to_string()));
351        assert!(m.cc.contains(&"c@b.com".to_string()));
352        assert!(m.bcc.contains(&"d@b.com".to_string()));
353    }
354
355    #[tokio::test]
356    async fn test_mail_manager_default() {
357        let mut manager = MailManager::new("log");
358        manager.register("log", LogMailer::new("log"));
359        manager.register("smtp", LogMailer::new("smtp"));
360
361        let default = manager.default_mailer().unwrap();
362        assert_eq!(default.name(), "log");
363
364        let mailer = manager.mailer("smtp").unwrap();
365        assert_eq!(mailer.name(), "smtp");
366    }
367
368    #[tokio::test]
369    async fn test_mail_manager_missing_mailer() {
370        let manager = MailManager::new("log");
371        let result = manager.mailer("nonexistent");
372        assert!(result.is_err());
373    }
374
375    #[tokio::test]
376    async fn test_mail_manager_names() {
377        let mut manager = MailManager::new("log");
378        manager.register("log", LogMailer::new("log"));
379        manager.register("ses", LogMailer::new("ses"));
380        let mut names = manager.mailer_names();
381        names.sort();
382        assert_eq!(names, vec!["log", "ses"]);
383    }
384
385    #[tokio::test]
386    async fn test_mail_manager_set_default() {
387        let mut manager = MailManager::new("log");
388        manager.register("log", LogMailer::new("log"));
389        manager.register("smtp", LogMailer::new("smtp"));
390        manager.set_default("smtp");
391        assert_eq!(manager.default_name(), "smtp");
392
393        let default = manager.default_mailer().unwrap();
394        assert_eq!(default.name(), "smtp");
395    }
396
397    #[tokio::test]
398    async fn test_smtp_mailer_creation() {
399        let result = SmtpMailer::new("smtp", "localhost", 1025, "user", "pass");
400        assert!(result.is_ok());
401    }
402
403    #[tokio::test]
404    async fn test_smtp_mailer_creation_without_auth() {
405        let result = SmtpMailer::new_without_auth("smtp", "localhost", 1025);
406        assert!(result.is_ok());
407    }
408
409    #[tokio::test]
410    async fn test_mailable_no_recipients() {
411        let mailer = LogMailer::new("log");
412        let mailable = Mailable::new(vec![], "No To", "body");
413        let result = mailer.send(mailable).await;
414        assert!(
415            result.is_ok(),
416            "LogMailer should not reject empty recipients"
417        );
418    }
419
420    #[tokio::test]
421    async fn test_mailable_html_constructor() {
422        let m = Mailable::html(vec!["u@e.com".to_string()], "HTML", "<b>bold</b>");
423        assert_eq!(m.content_type, ContentType::TEXT_HTML);
424        assert_eq!(m.subject, "HTML");
425        assert_eq!(m.body, "<b>bold</b>");
426    }
427
428    #[tokio::test]
429    async fn test_log_mailer_long_body() {
430        let mailer = LogMailer::new("log");
431        let long = "a".repeat(500);
432        let mailable = Mailable::new(vec!["t@t.com".to_string()], "Long", &long);
433        let result = mailer.send(mailable).await;
434        assert!(result.is_ok());
435    }
436
437    // -----------------------------------------------------------------------
438    // #[mail] macro tests
439    // -----------------------------------------------------------------------
440
441    use larastvel_macros::mail;
442
443    #[mail(subject = "Welcome!", from = "noreply@example.com")]
444    #[derive(Debug)]
445    struct WelcomeMail {
446        to: Vec<String>,
447        name: String,
448    }
449
450    impl WelcomeMail {
451        fn html(&self) -> String {
452            format!("<h1>Welcome, {}</h1>", self.name)
453        }
454    }
455
456    #[tokio::test]
457    async fn test_mail_macro_send() {
458        let mail = WelcomeMail {
459            to: vec!["user@test.com".to_string()],
460            name: "Alice".to_string(),
461        };
462        let mailer = LogMailer::new("log");
463        let result = mail.send(&mailer).await;
464        assert!(result.is_ok());
465    }
466
467    #[test]
468    fn test_mail_macro_struct_fields() {
469        let mail = WelcomeMail {
470            to: vec!["a@b.com".to_string()],
471            name: "Bob".to_string(),
472        };
473        assert_eq!(mail.to, vec!["a@b.com"]);
474        assert_eq!(mail.name, "Bob");
475    }
476
477    #[mail(
478        subject = "Test",
479        from = "admin@test.com",
480        reply_to = "support@test.com"
481    )]
482    #[derive(Debug)]
483    struct MultiRecipientMail {
484        to: Vec<String>,
485    }
486
487    impl MultiRecipientMail {
488        fn html(&self) -> String {
489            "<p>test</p>".to_string()
490        }
491    }
492
493    #[tokio::test]
494    async fn test_mail_macro_with_reply_to() {
495        let mail = MultiRecipientMail {
496            to: vec!["a@b.com".to_string(), "c@d.com".to_string()],
497        };
498        let mailer = LogMailer::new("log");
499        let result = mail.send(&mailer).await;
500        assert!(result.is_ok());
501    }
502}