pr-tracker/src/mail.rs

77 lines
2.2 KiB
Rust
Raw Normal View History

2024-07-15 22:09:52 +02:00
use std::collections::HashSet;
use anyhow::Result;
use lettre::message::header::ContentType;
use lettre::message::Mailbox;
use lettre::transport::smtp::authentication::Credentials;
use lettre::{Message, SmtpTransport, Transport};
use std::env;
2024-07-18 01:03:05 +02:00
use urlencoding::encode;
use crate::CONFIG;
2024-07-15 22:09:52 +02:00
pub fn send_notification(
recipient: &str,
branches: &HashSet<String>,
pr_number: &str,
pr_title: &str,
last: bool,
) -> Result<()> {
let mut body = format!(
"This is your friendly neighbourhood pr-tracker.<br>
PR <a href=\"https://github.com/NixOS/nixpkgs/pull/{pr_number}\">#{pr_number}</a>\
(\"{pr_title}\") has reached:<br>
{:#?}<br>",
2024-07-15 22:09:52 +02:00
branches
);
if last {
body += "This is the last update you will get for this pr.<br>\
Thx for using this service<br>\
2024-07-15 22:09:52 +02:00
Goodbye";
2024-07-18 01:03:05 +02:00
} else {
body += &format!(
"<a href=\"{}/unsubscribe?pr={pr_number}&email={}\">Unsubscribe from this PR</a><br>",
&CONFIG.url,
encode(recipient)
);
body += &format!(
"<a href=\"{}/unsubscribe?email={}\">Unsubscribe from all PRs</a>",
2024-07-18 01:03:05 +02:00
&CONFIG.url,
encode(recipient)
);
2024-07-15 22:09:52 +02:00
}
2024-07-26 21:27:43 +02:00
let sending_address = &CONFIG.email_address;
let sending_user = match &CONFIG.email_user {
Some(address) => address,
_ => &sending_address,
2024-07-15 22:09:52 +02:00
};
2024-07-26 21:27:43 +02:00
let sending_passwd = env::var("PR_TRACKER_MAIL_PASSWD")?;
2024-07-15 22:09:52 +02:00
2024-07-26 21:27:43 +02:00
let sending_server = CONFIG.email_server.as_ref();
2024-07-15 22:09:52 +02:00
let email = Message::builder()
.from(format!("PR-Tracker <{}>", sending_address).parse().unwrap())
.to(Mailbox::new(None, recipient.parse().unwrap()))
2024-07-15 22:09:52 +02:00
.subject(format!(
"PR-tracker: {pr_number}: {pr_title} has reached {:?}",
branches
))
.header(ContentType::TEXT_HTML)
.body(body)
.unwrap();
2024-07-15 22:09:52 +02:00
let creds = Credentials::new(sending_user.to_string(), sending_passwd.to_string());
// Open a remote connection to gmail
let mailer = SmtpTransport::relay(&sending_server)
.unwrap()
2024-07-15 22:09:52 +02:00
.credentials(creds)
.build();
// Send the email
mailer.send(&email).unwrap();
2024-07-15 22:09:52 +02:00
println!("Email sent successfully!");
Ok(())
}