This commit is contained in:
2024-01-01 15:50:06 +01:00
parent cf5b2751dd
commit 0ad342b147
10 changed files with 407 additions and 0 deletions

65
src/model/mail.rs Normal file
View File

@ -0,0 +1,65 @@
use std::error::Error;
use lettre::{
message::{
header::{self, ContentType},
MultiPart, SinglePart,
},
transport::smtp::authentication::Credentials,
Message, SmtpTransport, Transport,
};
use sqlx::SqlitePool;
use crate::tera::admin::mail::MailToSend;
use super::role::Role;
pub struct Mail {}
impl Mail {
pub async fn send(db: &SqlitePool, data: MailToSend<'_>, smtp_pw: String) -> bool {
let mut email = Message::builder()
.from(
"ASKÖ Ruderverein Donau Linz <no-reply@rudernlinz.at>"
.parse()
.unwrap(),
)
.reply_to(
"ASKÖ Ruderverein Donau Linz <info@rudernlinz.at>"
.parse()
.unwrap(),
)
.to("ASKÖ Ruderverein Donau Linz <no-reply@rudernlinz.at>"
.parse()
.unwrap());
let role = Role::find_by_id(db, data.role_id).await.unwrap();
for rec in role.mails_from_role(db).await {
let splitted = rec.split(',');
for single_rec in splitted {
email = email.bcc(single_rec.parse().unwrap());
}
}
// TODO: handle attachments
let email = email
.subject(data.subject)
.header(ContentType::TEXT_PLAIN)
.body(String::from(data.body))
.unwrap();
let creds = Credentials::new("no-reply@rudernlinz.at".to_owned(), smtp_pw);
let mailer = SmtpTransport::relay("mail.your-server.de")
.unwrap()
.credentials(creds)
.build();
// Send the email
match mailer.send(&email) {
Ok(_) => return true,
Err(e) => println!("{:?}", e.source()),
};
false
}
}

View File

@ -13,6 +13,7 @@ pub mod location;
pub mod log;
pub mod logbook;
pub mod logtype;
pub mod mail;
pub mod planned_event;
pub mod role;
pub mod rower;

View File

@ -14,4 +14,32 @@ impl Role {
.await
.unwrap()
}
pub async fn find_by_id(db: &SqlitePool, name: i32) -> Option<Self> {
sqlx::query_as!(
Self,
"
SELECT id, name
FROM role
WHERE id like ?
",
name
)
.fetch_one(db)
.await
.ok()
}
pub async fn mails_from_role(&self, db: &SqlitePool) -> Vec<String> {
let query = format!(
"SELECT u.mail
FROM user u
JOIN user_role ur ON u.id = ur.user_id
JOIN role r ON ur.role_id = r.id
WHERE r.id = {}",
self.id
);
sqlx::query_scalar(&query).fetch_all(db).await.unwrap()
}
}