hagrid-keyserver--hagrid/src/mail.rs

92 lines
2.1 KiB
Rust
Raw Normal View History

2018-12-25 19:06:28 +00:00
use handlebars::Handlebars;
2019-02-07 19:58:31 +00:00
use lettre::{EmailTransport, SendmailTransport};
use lettre_email::EmailBuilder;
use serde::Serialize;
use types::Email;
2019-02-07 19:58:31 +00:00
use Result;
#[derive(Serialize, Clone)]
2019-02-07 19:58:31 +00:00
pub struct Context {
pub token: String,
pub userid: String,
pub domain: String,
}
2019-02-07 19:58:31 +00:00
fn send_mail<T>(
to: &Email, subject: &str, mail_templates: &Handlebars, template: &str,
from: &str, ctx: T,
) -> Result<()>
where
T: Serialize + Clone,
{
let tmpl_html = format!("{}-html", template);
let tmpl_txt = format!("{}-txt", template);
2018-12-25 19:06:28 +00:00
let (html, txt) = {
2019-02-07 19:58:31 +00:00
if let (Ok(inner_html), Ok(inner_txt)) = (
mail_templates.render(&tmpl_html, &ctx),
mail_templates.render(&tmpl_txt, &ctx),
) {
(Some(inner_html), Some(inner_txt))
} else {
(None, None)
}
2018-12-25 19:06:28 +00:00
};
let email = EmailBuilder::new()
.to(to.to_string())
.from(from)
.subject(subject)
.alternative(
html.ok_or(failure::err_msg("Email template failed to render"))?,
txt.ok_or(failure::err_msg("Email template failed to render"))?,
2019-02-07 19:58:31 +00:00
)
.build()
.unwrap();
let mut sender = SendmailTransport::new();
sender.send(&email)?;
Ok(())
}
2019-02-07 19:58:31 +00:00
pub fn send_verification_mail(
userid: &Email, token: &str, mail_templates: &Handlebars, domain: &str,
from: &str,
) -> Result<()> {
let ctx = Context {
token: token.to_string(),
userid: userid.to_string(),
domain: domain.to_string(),
};
2019-02-07 19:58:31 +00:00
send_mail(
userid,
"Please verify your email address",
mail_templates,
"verify",
from,
ctx,
)
}
2019-02-07 19:58:31 +00:00
pub fn send_confirmation_mail(
userid: &Email, token: &str, mail_templates: &Handlebars, domain: &str,
from: &str,
) -> Result<()> {
let ctx = Context {
token: token.to_string(),
userid: userid.to_string(),
domain: domain.to_string(),
};
2019-02-07 19:58:31 +00:00
send_mail(
userid,
"Please confirm deletion of your key",
mail_templates,
"confirm",
from,
ctx,
)
}