rustfmt
[recipes.git] / backend / src / email.rs
1 use derive_more::Display;
2 use lettre::{transport::smtp::authentication::Credentials, Message, SmtpTransport, Transport};
3 use std::time::Duration;
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(
33 site_url: &str,
34 email: &str,
35 token: &str,
36 smtp_login: &str,
37 smtp_password: &str,
38 ) -> Result<(), Error> {
39 let email = Message::builder()
40 .message_id(None)
41 .from("recipes@gburri.org".parse()?)
42 .to(email.parse()?)
43 .subject("Recipes.gburri.org account validation")
44 .body(format!(
45 "Follow this link to confirm your inscription: {}/validation?token={}",
46 site_url, token
47 ))?;
48
49 let credentials = Credentials::new(smtp_login.to_string(), smtp_password.to_string());
50
51 let mailer = SmtpTransport::relay("mail.gandi.net")?
52 .credentials(credentials)
53 .timeout(Some(consts::SEND_EMAIL_TIMEOUT))
54 .build();
55
56 if let Err(error) = mailer.send(&email) {
57 eprintln!("Error when sending E-mail:\n{:?}", &error);
58 }
59
60 Ok(())
61 }