use askama::Template;
use crate::address::Address;
use crate::email::Email;
use crate::error::MailError;
pub trait EmailTemplate: Template {
fn subject(&self) -> String;
fn to(&self) -> Address;
fn from(&self) -> Option<Address> {
None
}
fn reply_to(&self) -> Option<Address> {
None
}
fn cc(&self) -> Vec<Address> {
Vec::new()
}
fn bcc(&self) -> Vec<Address> {
Vec::new()
}
fn into_email(self) -> Result<Email, MailError>
where
Self: Sized,
{
let html = self
.render()
.map_err(|e| MailError::TemplateError(e.to_string()))?;
let mut email = Email::new()
.subject(self.subject())
.to(self.to())
.html_body(&html);
if let Some(from) = self.from() {
email = email.from(from);
}
if let Some(reply_to) = self.reply_to() {
email = email.reply_to(reply_to);
}
for cc in self.cc() {
email = email.cc(cc);
}
for bcc in self.bcc() {
email = email.bcc(bcc);
}
Ok(email)
}
}
pub trait EmailTemplateExt: EmailTemplate {
fn into_email_with_text(self, text_body: &str) -> Result<Email, MailError>
where
Self: Sized,
{
self.into_email().map(|e| e.text_body(text_body))
}
}
impl<T: EmailTemplate> EmailTemplateExt for T {}