Skip to main content

teaql_tool_extra/
email.rs

1use lettre::message::header::ContentType;
2use lettre::transport::smtp::authentication::Credentials;
3use lettre::{Message, SmtpTransport, Transport};
4use teaql_tool_core::{Result, TeaQLToolError};
5
6#[derive(Debug, Clone)]
7pub struct EmailTool;
8
9impl EmailTool {
10    pub fn new() -> Self { Self }
11
12    pub fn send(&self, server: &str, user: &str, pass: &str, from: &str, to: &str, subject: &str, body: &str) -> Result<()> {
13        let email = Message::builder()
14            .from(from.parse().map_err(|_| TeaQLToolError::ParseError("Invalid from".into()))?)
15            .to(to.parse().map_err(|_| TeaQLToolError::ParseError("Invalid to".into()))?)
16            .subject(subject)
17            .header(ContentType::TEXT_PLAIN)
18            .body(String::from(body))
19            .map_err(|e| TeaQLToolError::ExecutionError(e.to_string()))?;
20
21        let creds = Credentials::new(user.to_owned(), pass.to_owned());
22
23        let mailer = SmtpTransport::relay(server)
24            .map_err(|e| TeaQLToolError::ExecutionError(e.to_string()))?
25            .credentials(creds)
26            .build();
27
28        mailer.send(&email).map_err(|e| TeaQLToolError::ExecutionError(e.to_string()))?;
29        Ok(())
30    }
31}
32
33impl Default for EmailTool {
34    fn default() -> Self { Self::new() }
35}