use crate::Mailable;
use larust_core::AppError;
use lettre::message::{header::ContentType, Mailbox};
use lettre::transport::smtp::authentication::Credentials;
use lettre::{AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor};
pub fn mail() -> MailBuilder {
MailBuilder { to: Vec::new() }
}
#[must_use]
pub struct MailBuilder {
to: Vec<String>,
}
impl MailBuilder {
pub fn to(mut self, email: impl Into<String>) -> Self {
self.to.push(email.into());
self
}
pub async fn send<M: Mailable>(self, mailable: M) -> Result<(), AppError> {
let subject = mailable.subject();
let body = mailable.html_body();
if crate::fake::is_active() {
crate::fake::record(crate::fake::SentMail {
mailable_type: std::any::type_name::<M>(),
to: self.to,
subject,
html_body: body,
});
return Ok(());
}
deliver(&self.to, &subject, &body).await
}
pub async fn queue<M: Mailable>(self, mailable: M) -> Result<(), AppError> {
let subject = mailable.subject();
let body = mailable.html_body();
if crate::fake::is_active() {
crate::fake::record(crate::fake::SentMail {
mailable_type: std::any::type_name::<M>(),
to: self.to,
subject,
html_body: body,
});
return Ok(());
}
larust_queue::dispatch(&crate::MailJob {
to: self.to,
subject,
html_body: body,
})
.await
}
}
pub(crate) async fn deliver(to: &[String], subject: &str, body: &str) -> Result<(), AppError> {
let config = larust_core::config();
match config.mail_driver.as_str() {
"smtp" => deliver_via_smtp(to, subject, body).await,
_ => {
tracing::info!(
?to,
subject = %subject,
body = %body,
"mail (log driver, not sent)"
);
Ok(())
}
}
}
async fn deliver_via_smtp(to: &[String], subject: &str, body: &str) -> Result<(), AppError> {
let config = larust_core::config();
let from_address: lettre::Address = config
.mail_from_address
.parse()
.map_err(|source| AppError::Config(Box::new(source)))?;
let from = Mailbox::new(Some(config.mail_from_name.clone()), from_address);
let mut builder = Message::builder().from(from).subject(subject);
for address in to {
let mailbox: Mailbox = address
.parse()
.map_err(|source| AppError::Internal(Box::new(source)))?;
builder = builder.to(mailbox);
}
let message = builder
.header(ContentType::TEXT_HTML)
.body(body.to_string())
.map_err(|source| AppError::Internal(Box::new(source)))?;
let transport = build_transport(config)?;
transport
.send(message)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
Ok(())
}
fn build_transport(
config: &larust_core::Config,
) -> Result<AsyncSmtpTransport<Tokio1Executor>, AppError> {
let builder = match config.mail_encryption.as_str() {
"starttls" => AsyncSmtpTransport::<Tokio1Executor>::starttls_relay(&config.mail_host),
"none" => Ok(AsyncSmtpTransport::<Tokio1Executor>::builder_dangerous(
&config.mail_host,
)),
_ => AsyncSmtpTransport::<Tokio1Executor>::relay(&config.mail_host),
}
.map_err(|source| AppError::Config(Box::new(source)))?;
let mut builder = builder.port(config.mail_port);
if !config.mail_username.is_empty() {
builder = builder.credentials(Credentials::new(
config.mail_username.clone(),
config.mail_password.clone(),
));
}
Ok(builder.build())
}
#[cfg(test)]
mod tests {
use super::*;
use larust_core::Config;
fn test_config(encryption: &str) -> Config {
Config {
app_name: "Test App".to_string(),
app_env: "testing".to_string(),
app_port: 8000,
session_secure_cookie: true,
app_debug: false,
app_url: "http://example.test".to_string(),
app_locale: "en".to_string(),
app_fallback_locale: "en".to_string(),
api_prefix: "/api".to_string(),
mail_driver: "smtp".to_string(),
mail_host: "smtp.example.test".to_string(),
mail_port: 587,
mail_username: String::new(),
mail_password: String::new(),
mail_encryption: encryption.to_string(),
mail_from_address: "hello@example.test".to_string(),
mail_from_name: "Test App".to_string(),
cache_driver: "database".to_string(),
queue_driver: "database".to_string(),
log_channel: "stdout".to_string(),
log_level: String::new(),
log_max_size: 10 * 1024 * 1024,
log_keep_files: 5,
deploy_type: "web".to_string(),
session_driver: "database".to_string(),
}
}
#[test]
fn build_transport_succeeds_for_implicit_tls() {
assert!(build_transport(&test_config("tls")).is_ok());
}
#[test]
fn build_transport_succeeds_for_starttls() {
assert!(build_transport(&test_config("starttls")).is_ok());
}
#[test]
fn build_transport_succeeds_for_no_encryption() {
assert!(build_transport(&test_config("none")).is_ok());
}
#[test]
fn build_transport_falls_back_to_implicit_tls_for_an_unrecognized_value() {
assert!(build_transport(&test_config("carrier-pigeon")).is_ok());
}
#[test]
fn build_transport_only_sets_credentials_when_a_username_is_configured() {
let mut config = test_config("tls");
config.mail_username = "user".to_string();
config.mail_password = "secret".to_string();
assert!(build_transport(&config).is_ok());
}
}