]> Untitled Git - lemmy.git/blob - lemmy_utils/src/email.rs
routes.api: fix get_captcha endpoint (#1135)
[lemmy.git] / lemmy_utils / src / email.rs
1 use crate::settings::Settings;
2 use lettre::{
3   smtp::{
4     authentication::{Credentials, Mechanism},
5     extension::ClientId,
6     ConnectionReuseParameters,
7   },
8   ClientSecurity,
9   SmtpClient,
10   Transport,
11 };
12 use lettre_email::Email;
13
14 pub fn send_email(
15   subject: &str,
16   to_email: &str,
17   to_username: &str,
18   html: &str,
19 ) -> Result<(), String> {
20   let email_config = Settings::get().email.ok_or("no_email_setup")?;
21
22   let email = Email::builder()
23     .to((to_email, to_username))
24     .from(email_config.smtp_from_address.to_owned())
25     .subject(subject)
26     .html(html)
27     .build()
28     .unwrap();
29
30   let mailer = if email_config.use_tls {
31     SmtpClient::new_simple(&email_config.smtp_server).unwrap()
32   } else {
33     SmtpClient::new(&email_config.smtp_server, ClientSecurity::None).unwrap()
34   }
35   .hello_name(ClientId::Domain(Settings::get().hostname))
36   .smtp_utf8(true)
37   .authentication_mechanism(Mechanism::Plain)
38   .connection_reuse(ConnectionReuseParameters::ReuseUnlimited);
39   let mailer = if let (Some(login), Some(password)) =
40     (&email_config.smtp_login, &email_config.smtp_password)
41   {
42     mailer.credentials(Credentials::new(login.to_owned(), password.to_owned()))
43   } else {
44     mailer
45   };
46
47   let mut transport = mailer.transport();
48   let result = transport.send(email.into());
49   transport.close();
50
51   match result {
52     Ok(_) => Ok(()),
53     Err(e) => Err(e.to_string()),
54   }
55 }