Add mailer

This commit is contained in:
Mo 2022-10-29 00:41:18 +02:00
parent a1cd8f431d
commit dfe4290713

75
src/mailer.rs Normal file
View file

@ -0,0 +1,75 @@
use anyhow::{Context, Result};
use lettre::address::Address;
use lettre::message::{Mailbox, MessageBuilder};
use lettre::transport::smtp::authentication::Credentials;
use lettre::Transport;
use lettre::{Message, SmtpTransport};
use crate::config;
pub struct Mailer {
mailer: SmtpTransport,
message_builder: MessageBuilder,
}
impl Mailer {
pub fn new(config: &config::Config) -> Result<Self> {
let creds = Credentials::new(
config.email_server.email.clone(),
config.email_server.password.clone(),
);
let mailer = SmtpTransport::relay(&config.email_server.server_name)
.context("Failed to connect to the email server!")?
.credentials(creds)
.build();
let message_builder = Message::builder()
.from(Mailbox::new(
Some(config.email_from.name.clone()),
Address::new(&config.email_from.user, &config.email_from.domain)
.context("Failed to create the From email address!")?,
))
.to(Mailbox::new(
Some(config.email_to.name.clone()),
Address::new(&config.email_to.user, &config.email_to.domain)
.context("Failed to create the To email address!")?,
));
Ok(Self {
mailer,
message_builder,
})
}
pub fn send(&self, name: &str, email: &str, telefon: &str, message: &str) -> Result<()> {
let name = name.trim().to_string();
let telefon = telefon.trim();
let message = message.trim().to_string();
let subject = "Message from ".to_string() + &name;
let body = if telefon.len() > 0 {
message + "\n\nTelefon: " + &telefon
} else {
message
};
let email = self
.message_builder
.clone()
.reply_to(Mailbox::new(
Some(name),
email
.parse()
.context("Failed to parse the email from the form to an address!")?,
))
.subject(subject)
.body(body)
.context("Failed to build email!")?;
self.mailer.send(&email).context("Failed to send email!")?;
Ok(())
}
}