1 use crate::{settings::structs::Settings, LemmyError};
4 message::{header, Mailbox, MultiPart, SinglePart},
5 transport::smtp::{authentication::Credentials, extension::ClientId},
11 use std::str::FromStr;
20 ) -> Result<(), LemmyError> {
21 let email_config = settings
24 .ok_or_else(|| LemmyError::from_message("no_email_setup"))?;
25 let domain = settings.hostname.to_owned();
27 let (smtp_server, smtp_port) = {
28 let email_and_port = email_config.smtp_server.split(':').collect::<Vec<&str>>();
29 if email_and_port.len() == 1 {
30 return Err(LemmyError::from_message(
31 "email.smtp_server needs a port, IE smtp.xxx.com:465",
39 .expect("email needs a port"),
43 // the message length before wrap, 78, is somewhat arbritary but looks good to me
44 let plain_text = html2text::from_read(html.as_bytes(), 78);
46 let email = Message::builder()
51 .expect("email from address isn't valid"),
54 Some(to_username.to_string()),
55 Address::from_str(to_email).expect("email to address isn't valid"),
57 .message_id(Some(format!("{}@{}", Uuid::new_v4(), settings.hostname)))
60 MultiPart::mixed().multipart(
61 MultiPart::alternative()
64 .header(header::ContentType::TEXT_PLAIN)
68 MultiPart::related().singlepart(
70 .header(header::ContentType::TEXT_HTML)
71 .body(html.to_string()),
76 .expect("email built incorrectly");
78 // don't worry about 'dangeous'. it's just that leaving it at the default configuration
82 let builder_dangerous = SmtpTransport::builder_dangerous(smtp_server).port(smtp_port);
84 let mut builder = match email_config.tls_type.as_str() {
85 "starttls" => SmtpTransport::starttls_relay(smtp_server)?,
86 "tls" => SmtpTransport::relay(smtp_server)?,
87 _ => builder_dangerous,
90 // Set the creds if they exist
91 if let (Some(username), Some(password)) = (email_config.smtp_login, email_config.smtp_password) {
92 builder = builder.credentials(Credentials::new(username, password));
95 let mailer = builder.hello_name(ClientId::Domain(domain)).build();
97 let result = mailer.send(&email);
101 Err(e) => Err(LemmyError::from_error_message(e, "email_send_failed")),