Add asynchronous call to database.
[recipes.git] / backend / src / email.rs
1 use std::time::Duration;
2 use derive_more::Display;
3 use lettre::{transport::smtp::authentication::Credentials, Message, SmtpTransport, Transport};
4
5 use crate::consts;
6
7 #[derive(Debug, Display)]
8 pub enum Error {
9 ParseError(lettre::address::AddressError),
10 SmtpError(lettre::transport::smtp::Error),
11 Email(lettre::error::Error),
12 }
13
14 impl From<lettre::address::AddressError> for Error {
15 fn from(error: lettre::address::AddressError) -> Self {
16 Error::ParseError(error)
17 }
18 }
19
20 impl From<lettre::transport::smtp::Error> for Error {
21 fn from(error: lettre::transport::smtp::Error) -> Self {
22 Error::SmtpError(error)
23 }
24 }
25
26 impl From<lettre::error::Error> for Error {
27 fn from(error: lettre::error::Error) -> Self {
28 Error::Email(error)
29 }
30 }
31
32 pub fn send_validation(site_url: &str, email: &str, token: &str, smtp_login: &str, smtp_password: &str) -> Result<(), Error> {
33 let email = Message::builder()
34 .message_id(None)
35 .from("recipes@gburri.org".parse()?)
36 .to(email.parse()?)
37 .subject("Recipes.gburri.org account validation")
38 .body(format!("Follow this link to confirm your inscription: {}/validation?token={}", site_url, token))?;
39
40 let credentials = Credentials::new(smtp_login.to_string(), smtp_password.to_string());
41
42 let mailer = SmtpTransport::relay("mail.gandi.net")?.credentials(credentials).timeout(Some(consts::SEND_EMAIL_TIMEOUT)).build();
43
44 if let Err(error) = mailer.send(&email) {
45 eprintln!("Error when sending E-mail:\n{:?}", &error);
46 }
47
48 Ok(())
49 }