commit b08bce93dcb5f26e36b8af60ef043a410e433d37 from: witcher date: Sun Dec 18 10:02:09 2022 UTC Introduce Mail struct The `Mail` struct allows the caller to not have to worry about the format of an email. commit - 3a97a069bdfcf64cacc3800026d548a8f1154a89 commit + b08bce93dcb5f26e36b8af60ef043a410e433d37 blob - 382609ac9d796546fb759ca0b9db925273b11e3a blob + fe2d45e09b585c160662abb7768776c38f69bf9a --- src/mail.rs +++ src/mail.rs @@ -5,6 +5,45 @@ use lettre::{ AsyncTransport, Tokio1Executor, }; +pub struct Mail { + subject: String, + body: String, +} + +impl Mail { + /// Build a Mail. + /// + /// Build a Mail from the optional components subject, body, and url. + /// If any of the parameters are not given, they will be replaced with a default value. + pub fn new(subject: Option, body: Option, url: Option) -> Self { + let subject = subject.unwrap_or_else(|| "No title found".to_string()); + let url = url.unwrap_or_else(|| "No url found".to_string()); + let body = match body { + Some(c) => url + "\n\n" + &c, + None => url, + }; + + Self { subject, body } + } + + pub async fn send_email( + self, + config: &Config, + mailer: &AsyncSmtpTransport, + ) -> anyhow::Result<()> { + trace!("Sending to {}: {}", config.to, &self.subject); + let email = Message::builder() + .from(config.from.parse()?) + .to(config.to.parse()?) + .subject(self.subject) + .body(self.body)?; + + mailer.send(email).await?; + + Ok(()) + } +} + pub fn get_mailer(config: &Config) -> anyhow::Result> { let creds = Credentials::new( config.smtp.user.to_string(), @@ -18,25 +57,3 @@ pub fn get_mailer(config: &Config) -> anyhow::Result( - config: &Config, - subject: S, - body: I, - mailer: &AsyncSmtpTransport, -) -> anyhow::Result<()> -where - S: AsRef, - I: Into, -{ - let email = Message::builder() - .from(config.from.parse()?) - .to(config.to.parse()?) - .subject(subject.as_ref()) - .body(body.into())?; - - trace!("Sending to {}: {}", config.to, subject.as_ref()); - mailer.send(email).await?; - - Ok(()) -} blob - 0b92dc1fc2f50b65ecb736d7acddf8b2400c3858 blob + e202c06d88e575e988f74cd8fa5fe4c4fff547ed --- src/main.rs +++ src/main.rs @@ -10,7 +10,7 @@ pub mod feed; pub mod mail; pub mod models; -use crate::mail::{get_mailer, send_email}; +use crate::mail::{get_mailer, Mail}; use anyhow::Context; use config::Config; use lettre::{AsyncSmtpTransport, Tokio1Executor}; @@ -105,12 +105,9 @@ where E: sqlx::Executor<'a, Database = Sqlite>, { if !dry_run { - let subject = post.title.unwrap_or_else(|| "No title found".to_string()); - let body = match post.content { - Some(c) => c + "\n\n" + &post.url.unwrap(), - None => post.url.unwrap(), - }; - send_email(&config, subject, body, &mailer).await?; + Mail::new(post.title, post.content, post.url) + .send_email(&config, &mailer) + .await?; } sqlx::query!("update posts set sent = true where guid = ?", post.guid)