aboutsummaryrefslogtreecommitdiff
path: root/src/utils.rs
blob: e723db892dafdc7a69276e38a7d85da567363ba5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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<Tokio1Executor>;
    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::<Tokio1Executor>::starttls_relay(&config.email.smtp_server)
                .unwrap()
                .credentials(creds)
                .hello_name(helo)
                .build();
        } else {
            mailer = AsyncSmtpTransport::<Tokio1Executor>::builder_dangerous(&config.email.smtp_server)
                .credentials(creds)
                .hello_name(helo)
                .build();
        }
    } else { 
        if config.email.smtp_tls && config.email.smtp_starttls {
            mailer = AsyncSmtpTransport::<Tokio1Executor>::starttls_relay(&config.email.smtp_server).unwrap().hello_name(helo)
                .build();
        } else if config.email.smtp_tls {
            mailer = AsyncSmtpTransport::<Tokio1Executor>::relay(&config.email.smtp_server).unwrap().hello_name(helo).build();
        } else {
            mailer = AsyncSmtpTransport::<Tokio1Executor>::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(())
}