aboutsummaryrefslogtreecommitdiff
path: root/src/mail.rs
blob: d86cff33118e68c059266bfa8c1f43fb0f11f761 (plain)
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
52
53
54
55
56
57
58
59
use lettre::sendmail::SendmailTransport;
use lettre::{SendableEmail, Transport};
use lettre_email::Email;

use crate::model::config::Config;

static FROM: &str = "contact@guyonvarch.me";

pub fn send(
    config: &Config,
    to: Vec<(String, String)>,
    subject: String,
    message: String,
) -> bool {
    match prepare_email(to.clone(), subject.clone(), message.clone()) {
        Ok(email) => {
            if config.mock_mails {
                let formatted_to = to
                    .into_iter()
                    .map(|t| t.0)
                    .collect::<Vec<String>>()
                    .join(", ");
                info!(
                    "MOCK MAIL\nto: {}\nsubject: {}\n\n{}",
                    formatted_to, subject, message
                );
                true
            } else {
                let mut sender =
                    SendmailTransport::new_with_command(&config.sendmail_path);
                match sender.send(email) {
                    Ok(_) => true,
                    Err(err) => {
                        error!("Error sending email: {:?}", err);
                        false
                    }
                }
            }
        }
        Err(err) => {
            error!("Error preparing email: {:?}", err);
            false
        }
    }
}

fn prepare_email(
    to: Vec<(String, String)>,
    subject: String,
    message: String,
) -> Result<SendableEmail, lettre_email::error::Error> {
    let mut email = Email::builder().from(FROM).subject(subject).text(message);

    for (address, name) in to.iter() {
        email = email.to((address, name));
    }

    email.build().map(|e| e.into())
}