tuwunel_service/sendmail/
mod.rs1#[cfg(test)]
7mod tests;
8
9use std::sync::Arc;
10
11pub use lettre::Address;
12use lettre::{
13 AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor,
14 error::Error as EmailError,
15 message::{
16 Mailbox, MessageBuilder,
17 header::{ContentType, HeaderName, HeaderValue},
18 },
19};
20use tuwunel_core::{Err, Result, err, implement};
21
22pub struct Service {
27 transport: Option<Transport>,
28}
29
30struct Transport {
31 smtp: AsyncSmtpTransport<Tokio1Executor>,
32 sender: Mailbox,
33}
34
35const AUTO_SUBMITTED: HeaderName = HeaderName::new_from_ascii_str("Auto-Submitted");
37
38impl crate::Service for Service {
39 fn build(args: &crate::Args<'_>) -> Result<Arc<Self>> {
40 let smtp = &args.server.config.smtp;
41 let transport = smtp
42 .connection_uri
43 .is_some()
44 .then(|| build_transport(smtp))
45 .transpose()?;
46
47 Ok(Arc::new(Self { transport }))
48 }
49
50 fn name(&self) -> &str { crate::service::make_name(std::module_path!()) }
51}
52
53#[implement(Service)]
57#[inline]
58#[must_use]
59pub fn is_enabled(&self) -> bool { self.transport.is_some() }
60
61#[implement(Service)]
66#[tracing::instrument(
67 level = "debug",
68 skip(self, subject, body_html),
69 fields(
70 %to,
71 ),
72)]
73pub async fn send(&self, to: &Address, subject: &str, body_html: String) -> Result<()> {
74 self.deliver(to, subject, |message| {
75 message
76 .header(ContentType::TEXT_HTML)
77 .body(body_html)
78 })
79 .await
80}
81
82#[implement(Service)]
87#[tracing::instrument(
88 level = "debug",
89 skip(self, subject, body_text),
90 fields(
91 %to,
92 ),
93)]
94pub async fn send_auto_generated(
95 &self,
96 to: &Address,
97 subject: &str,
98 body_text: String,
99) -> Result {
100 self.deliver(to, subject, |message| {
101 message
102 .header(ContentType::TEXT_PLAIN)
103 .raw_header(HeaderValue::new(AUTO_SUBMITTED, "auto-generated".to_owned()))
104 .body(body_text)
105 })
106 .await
107}
108
109#[implement(Service)]
114pub async fn send_to(&self, to: &str, subject: &str, body_html: String) -> Result<()> {
115 let to: Address = to
116 .parse()
117 .map_err(|_| err!(Request(InvalidParam("Email address is malformed"))))?;
118
119 self.send(&to, subject, body_html).await
120}
121
122#[implement(Service)]
126pub fn check_address(&self, to: &str) -> Result<()> {
127 to.parse::<Address>()
128 .map(|_| ())
129 .map_err(|_| err!(Request(InvalidParam("Email address is malformed"))))
130}
131
132#[implement(Service)]
133async fn deliver<Build>(&self, to: &Address, subject: &str, build: Build) -> Result
134where
135 Build: FnOnce(MessageBuilder) -> Result<Message, EmailError>,
136{
137 let Some(transport) = self.transport.as_ref() else {
138 return Err!(Config("smtp", "The email subsystem is not configured"));
139 };
140
141 let message = Message::builder()
142 .from(transport.sender.clone())
143 .to(Mailbox::new(None, to.clone()))
144 .subject(subject);
145
146 let message = build(message)
147 .map_err(|e| err!(Request(Unknown("Failed to build email message: {e}"))))?;
148
149 transport
150 .smtp
151 .send(message)
152 .await
153 .map(|_| ())
154 .map_err(|e| err!(Request(Unknown("Failed to send email: {e}"))))
155}
156
157fn build_transport(config: &tuwunel_core::config::SmtpConfig) -> Result<Transport> {
158 let uri = config.connection_uri.as_deref().ok_or_else(|| {
159 err!(Config(
160 "smtp.connection_uri",
161 "An SMTP connection_uri is required to send email"
162 ))
163 })?;
164
165 let sender = config
166 .sender
167 .as_deref()
168 .ok_or_else(|| err!(Config("smtp.sender", "An SMTP sender mailbox is required")))?
169 .parse()
170 .map_err(|e| err!(Config("smtp.sender", "Invalid sender mailbox: {e}")))?;
171
172 let smtp = AsyncSmtpTransport::<Tokio1Executor>::from_url(uri)
173 .map_err(|e| err!(Config("smtp.connection_uri", "Invalid SMTP connection_uri: {e}")))?
174 .build();
175
176 Ok(Transport { smtp, sender })
177}