Skip to main content

pakem/core/mail/
mod.rs

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
11/// Driver untuk logging (Development)
12pub 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
30/// Driver untuk SMTP (Placeholder)
31pub 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
40/// Mailer Manager
41pub 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    /// Mulai membangun pengiriman email.
52    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
61/// Fluent Builder untuk pengiriman email.
62pub 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    /// Kirim email menggunakan template View.
75    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    /// Kirim email dengan body raw (biasanya untuk testing).
88    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}