Skip to main content

tuwunel_service/sendmail/
mod.rs

1//! Outbound email delivery.
2//!
3//! The service builds messages from the configured sender and delivers them through a pooled SMTP
4//! transport. It remains disabled when no SMTP connection URI is configured.
5
6#[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
22/// Delivers outbound email through the configured SMTP transport.
23///
24/// The service retains a pooled connection and sender mailbox when SMTP is configured. Without a
25/// connection URI it remains disabled and rejects delivery attempts.
26pub struct Service {
27	transport: Option<Transport>,
28}
29
30struct Transport {
31	smtp: AsyncSmtpTransport<Tokio1Executor>,
32	sender: Mailbox,
33}
34
35// RFC 3834: automatic responders should not answer mail marked with this field.
36const 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/// Reports whether outbound email is configured.
54///
55/// An enabled service has both a validated sender mailbox and an SMTP transport ready for use.
56#[implement(Service)]
57#[inline]
58#[must_use]
59pub fn is_enabled(&self) -> bool { self.transport.is_some() }
60
61/// Sends an HTML message to one recipient from the configured sender.
62///
63/// Message construction and SMTP delivery occur in one operation. A disabled transport, invalid
64/// message, or delivery failure returns an error.
65#[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/// Sends an automatic plain-text message to one recipient from the configured sender.
83///
84/// The message is marked `Auto-Submitted: auto-generated` (RFC 3834) so that automatic responders
85/// do not answer it. A disabled transport, invalid message, or delivery failure returns an error.
86#[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/// Parses a recipient address and sends an HTML message.
110///
111/// A malformed address maps to `M_INVALID_PARAM`. Valid addresses are delivered through
112/// [`Self::send`].
113#[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/// Validates that a string parses as an email address.
123///
124/// The address is not contacted or retained. A malformed value maps to `M_INVALID_PARAM`.
125#[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}