use lettre::{Message, transport::smtp::{authentication::Credentials, extension::ClientId}, transport::smtp::AsyncSmtpTransport, AsyncTransport, Tokio1Executor}; use crate::{errors::ServiceError, config}; pub async fn send_email(to: String, subject: String, content: String) -> Result<(), ServiceError> { let config = config::Config::init("/etc/nccd/config.toml".to_string()).unwrap(); let email = if let Ok(e) = Message::builder() .from(config.email.email_from.parse().unwrap()) .to(to.parse().unwrap()) .subject(subject) .body(content) { e } else { return Err(ServiceError::Email("Invalid email content".to_string())); }; let mailer: AsyncSmtpTransport; let helo = ClientId::Domain(config.email.email_helo); if let Some(u) = config.email.smtp_username { let creds = Credentials::new(u, config.email.smtp_password.unwrap()); if config.email.smtp_starttls { mailer = AsyncSmtpTransport::::starttls_relay(&config.email.smtp_server) .unwrap() .credentials(creds) .hello_name(helo) .build(); } else { mailer = AsyncSmtpTransport::::builder_dangerous(&config.email.smtp_server) .credentials(creds) .hello_name(helo) .build(); } } else { if config.email.smtp_tls && config.email.smtp_starttls { mailer = AsyncSmtpTransport::::starttls_relay(&config.email.smtp_server).unwrap().hello_name(helo) .build(); } else if config.email.smtp_tls { mailer = AsyncSmtpTransport::::relay(&config.email.smtp_server).unwrap().hello_name(helo).build(); } else { mailer = AsyncSmtpTransport::::builder_dangerous(&config.email.smtp_server).hello_name(helo).build(); } } if let Err(e) = mailer.test_connection().await { return Err(ServiceError::Email(e.to_string())); } else { if let Err(e) = mailer.send(email).await { return Err(ServiceError::Email(e.to_string())); } } Ok(()) }