1use crate::core::view::ViewEngine;
2use async_trait::async_trait;
3use serde_json::Value;
4use std::sync::Arc;
5
6#[async_trait]
7pub trait MailDriver: Send + Sync {
8 async fn send(&self, to: &str, subject: &str, html: String) -> Result<(), String>;
9}
10
11pub struct LogDriver;
13
14#[async_trait]
15impl MailDriver for LogDriver {
16 async fn send(&self, to: &str, subject: &str, html: String) -> Result<(), String> {
17 println!();
18 println!("📧 [MAIL LOG]");
19 println!("To: {}", to);
20 println!("Subject: {}", subject);
21 println!(
22 "Content (HTML Preview): {}...",
23 &html[..std::cmp::min(100, html.len())]
24 );
25 println!("--------------------------------------------------");
26 Ok(())
27 }
28}
29
30pub struct SmtpDriver;
32
33#[async_trait]
34impl MailDriver for SmtpDriver {
35 async fn send(&self, _to: &str, _subject: &str, _html: String) -> Result<(), String> {
36 Err("SMTP Driver belum diimplementasikan sepenuhnya. Silakan instal 'lettre'.".to_string())
37 }
38}
39
40pub struct Mail {
42 driver: Arc<dyn MailDriver>,
43 view: ViewEngine,
44}
45
46impl Mail {
47 pub fn new(driver: Arc<dyn MailDriver>, view: ViewEngine) -> Self {
48 Self { driver, view }
49 }
50
51 pub fn to(&self, address: &str) -> MailBuilder<'_> {
53 MailBuilder {
54 mailer: self,
55 to: address.to_string(),
56 subject: String::new(),
57 }
58 }
59}
60
61pub struct MailBuilder<'a> {
63 mailer: &'a Mail,
64 to: String,
65 subject: String,
66}
67
68impl<'a> MailBuilder<'a> {
69 pub fn subject(mut self, subject: &str) -> Self {
70 self.subject = subject.to_string();
71 self
72 }
73
74 pub async fn send(self, template: &str, data: Value) -> Result<(), String> {
76 let mut ctx = crate::core::blade::BladeContext::new();
77 if let Some(obj) = data.as_object() {
78 for (k, v) in obj {
79 ctx.insert(k, v);
80 }
81 }
82
83 let html = self.mailer.view.render(template, &ctx);
84 self.mailer.driver.send(&self.to, &self.subject, html).await
85 }
86
87 pub async fn send_raw(self, body: &str) -> Result<(), String> {
89 self.mailer
90 .driver
91 .send(&self.to, &self.subject, body.to_string())
92 .await
93 }
94}