Skip to content

Commit

Permalink
feat(mail): send mail notification after print
Browse files Browse the repository at this point in the history
  • Loading branch information
Joxit committed Jan 13, 2024
1 parent 0f313ee commit c081eb8
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 5 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,4 @@ clap_complete = "^4.4"
sha256 = "^1.4"
anyhow = "^1.0"
mail-send = "^0.4.6"
tokio = "1.35.1"
17 changes: 13 additions & 4 deletions src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ pub use crate::config::task::Task;
use crate::config::yaml_trait::YamlTasksScheduler;
use anyhow::{anyhow, Result};
use std::collections::HashMap;
use tokio::runtime::Runtime;
use yaml_rust::YamlLoader;

mod task;
Expand Down Expand Up @@ -206,15 +207,23 @@ impl Notification {
}
}

if let Some(email) = self.email() {
if let Some(email) = self.email().clone() {
if let Some(when) = email.when() {
if !when.should_notify(&WhenNotify::TaskEnd) {
return;
}
}
if let Err(e) = crate::notification::notification_email(&email, msg.as_str()) {
eprintln!("Can't use email notification: {}", e);
}

match Runtime::new() {
Ok(rt) => {
rt.block_on(async {
if let Err(e) = crate::notification::notification_email(&email, msg.as_str()).await {
eprintln!("Can't use email notification: {}", e);
}
});
}
Err(e) => eprint!("Can't use email notification: {}", e),
};
}
}

Expand Down
23 changes: 22 additions & 1 deletion src/notification/mail.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,26 @@
use crate::config::Mail;
use anyhow::{anyhow, Result};
use mail_send::{mail_builder::MessageBuilder, Credentials, SmtpClientBuilder};

pub fn notification_email(mail: &Mail, message: &str) -> Result<(), String> {
pub async fn notification_email(mail: &Mail, body: &str) -> Result<()> {
let message = MessageBuilder::new()
.from(mail.from().clone())
.to(mail.to().clone())
.subject(mail.subject())
.html_body(format!("<p>{}</p>", body))
.text_body(body);

SmtpClientBuilder::new(mail.smtp_hostname(), mail.smtp_port())
.implicit_tls(mail.smtp_tls())
.credentials(Credentials::Plain {
username: mail.smtp_username(),
secret: mail.smtp_secret(),
})
.connect()
.await
.map_err(|e| anyhow!("Connection to SMTP failed: {}", e))?
.send(message)
.await
.map_err(|e| anyhow!("Failed to sending email: {}", e))?;
Ok(())
}

0 comments on commit c081eb8

Please sign in to comment.