reinhardt-mail 0.3.1

Email sending functionality with multiple backends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
// `SmtpConfig` is deprecated in favour of the `EmailSettings` fragment, but this
// module still defines, constructs, and bridges to it during the compatibility
// window. Allow deprecated usages crate-internally so `-D warnings` stays clean.
#![allow(deprecated)]

use crate::headers::{
	ListUnsubscribe, ListUnsubscribePost, Precedence, XEntityRefId, XMailer, XPriority,
};
use crate::message::EmailMessage;
use crate::{EmailError, EmailResult};
use lettre::message::header::{HeaderName, HeaderValue};
use lettre::message::{Mailbox, MultiPart, SinglePart, header};
use lettre::transport::smtp::authentication::{Credentials, Mechanism};
use lettre::transport::smtp::client::{Tls, TlsParameters};
use lettre::{AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor};
use reinhardt_conf::settings::email::EmailSettings;
use reinhardt_conf::settings::fragment::HasSettings;
use std::path::Path;
use std::time::Duration;
use zeroize::Zeroize;

/// Trait for email backends
#[async_trait::async_trait]
pub trait EmailBackend: Send + Sync {
	/// Send one or more email messages, returning the number of messages sent successfully.
	async fn send_messages(&self, messages: &[EmailMessage]) -> EmailResult<usize>;
}

/// Creates an email backend from settings configuration.
///
/// # Arguments
/// * `settings` - Email configuration settings
///
/// # Returns
/// A boxed EmailBackend trait object based on settings.backend field
///
/// # Errors
/// Returns EmailError if:
/// - Unknown backend type
/// - Missing required fields (e.g., file_path for FileBackend)
pub fn backend_from_settings<S: HasSettings<EmailSettings> + ?Sized>(
	settings: &S,
) -> crate::EmailResult<Box<dyn EmailBackend>> {
	let email_settings = settings.get_settings();

	// Validate from_email if configured
	if !email_settings.from_email.is_empty() {
		crate::validation::validate_email(&email_settings.from_email)?;
	}

	match email_settings.backend.to_lowercase().as_str() {
		"smtp" => {
			let security = match (email_settings.use_tls, email_settings.use_ssl) {
				(true, _) => SmtpSecurity::StartTls,
				(_, true) => SmtpSecurity::Tls,
				_ => SmtpSecurity::None,
			};

			let timeout = email_settings
				.timeout
				.map(std::time::Duration::from_secs)
				.unwrap_or(std::time::Duration::from_secs(60));

			let mut config = SmtpConfig::new(&email_settings.host, email_settings.port)
				.with_security(security)
				.with_timeout(timeout);

			if let (Some(username), Some(password)) =
				(&email_settings.username, &email_settings.password)
			{
				config = config.with_credentials(username.to_string(), password.to_string());
			}

			let backend = SmtpBackend::new(config)?;
			Ok(Box::new(backend))
		}
		"console" => Ok(Box::new(ConsoleBackend)),
		"file" => {
			let directory = email_settings
				.file_path
				.as_deref()
				.map(Path::to_path_buf)
				.ok_or_else(|| crate::EmailError::MissingField("file_path".to_string()))?;
			Ok(Box::new(FileBackend::new(directory)))
		}
		"memory" => Ok(Box::new(MemoryBackend::new())),
		unknown => Err(crate::EmailError::BackendError(format!(
			"Unknown email backend type: '{}'. Valid options: smtp, console, file, memory",
			unknown
		))),
	}
}

/// Console backend for development
///
/// Prints email messages to the console instead of sending them.
pub struct ConsoleBackend;

#[async_trait::async_trait]
impl EmailBackend for ConsoleBackend {
	async fn send_messages(&self, messages: &[EmailMessage]) -> EmailResult<usize> {
		for (i, msg) in messages.iter().enumerate() {
			println!("========== Email {} ==========", i + 1);
			println!("From: {}", msg.from_email());
			println!("To: {}", msg.to().join(", "));
			if !msg.cc().is_empty() {
				println!("Cc: {}", msg.cc().join(", "));
			}
			if !msg.bcc().is_empty() {
				println!("Bcc: {}", msg.bcc().join(", "));
			}
			println!("Subject: {}", msg.subject());
			for (name, value) in msg.headers() {
				println!("{}: {}", name, value);
			}
			println!("\n{}", msg.body());
			if let Some(html) = msg.html_body() {
				println!("\n--- HTML ---\n{}", html);
			}
			for attachment in msg.attachments() {
				println!(
					"\n--- Attachment: {} (Content-Type: {}, {} bytes) ---",
					attachment.filename(),
					attachment.mime_type(),
					attachment.content().len()
				);
			}
			println!("==============================\n");
		}
		Ok(messages.len())
	}
}

/// File backend for saving emails to files
pub struct FileBackend {
	directory: std::path::PathBuf,
}

impl FileBackend {
	/// Creates a new file backend that stores emails in the specified directory.
	pub fn new(directory: impl Into<std::path::PathBuf>) -> Self {
		Self {
			directory: directory.into(),
		}
	}
}

#[async_trait::async_trait]
impl EmailBackend for FileBackend {
	async fn send_messages(&self, messages: &[EmailMessage]) -> EmailResult<usize> {
		std::fs::create_dir_all(&self.directory)?;

		for msg in messages.iter() {
			let filename = format!(
				"email_{}.eml",
				chrono::Utc::now().format("%Y%m%d_%H%M%S_%f")
			);
			let path = self.directory.join(filename);

			let mut content = format!(
				"From: {}\nTo: {}\nSubject: {}",
				msg.from_email(),
				msg.to().join(", "),
				msg.subject()
			);

			// Include custom headers
			for (name, value) in msg.headers() {
				content.push_str(&format!("\n{}: {}", name, value));
			}

			content.push_str(&format!("\n\n{}", msg.body()));

			// Include HTML body if present
			if let Some(html) = msg.html_body() {
				content.push_str("\n\n--- HTML Body ---\n");
				content.push_str(html);
			}

			// Include attachment metadata
			for attachment in msg.attachments() {
				content.push_str(&format!(
					"\n\n--- Attachment: {} ---\nContent-Type: {}\nSize: {} bytes\n",
					attachment.filename(),
					attachment.mime_type(),
					attachment.content().len()
				));
			}

			tokio::fs::write(path, content).await?;
		}

		Ok(messages.len())
	}
}

/// Memory backend for testing
pub struct MemoryBackend {
	messages: std::sync::Arc<tokio::sync::Mutex<Vec<EmailMessage>>>,
}

impl MemoryBackend {
	/// Creates a new memory backend with an empty message store.
	pub fn new() -> Self {
		Self {
			messages: std::sync::Arc::new(tokio::sync::Mutex::new(Vec::new())),
		}
	}

	/// Returns the number of messages stored in the backend.
	pub async fn count(&self) -> usize {
		self.messages.lock().await.len()
	}

	/// Returns a clone of all stored messages.
	pub async fn get_messages(&self) -> Vec<EmailMessage> {
		self.messages.lock().await.clone()
	}

	/// Removes all stored messages from the backend.
	pub async fn clear(&self) {
		self.messages.lock().await.clear();
	}
}

impl Default for MemoryBackend {
	fn default() -> Self {
		Self::new()
	}
}

#[async_trait::async_trait]
impl EmailBackend for MemoryBackend {
	async fn send_messages(&self, messages: &[EmailMessage]) -> EmailResult<usize> {
		let mut stored = self.messages.lock().await;
		stored.extend_from_slice(messages);
		Ok(messages.len())
	}
}

/// SMTP connection security mode
#[derive(Debug, Clone)]
pub enum SmtpSecurity {
	/// No encryption
	None,
	/// STARTTLS (upgrade to TLS)
	StartTls,
	/// Direct TLS/SSL connection
	Tls,
}

/// SMTP authentication mechanism
#[derive(Debug, Clone)]
pub enum SmtpAuthMechanism {
	/// PLAIN authentication
	Plain,
	/// LOGIN authentication
	Login,
	/// Any supported mechanism
	Auto,
}

/// Configuration for SMTP backend
///
/// Deprecated: configure the SMTP backend through the
/// [`EmailSettings`] fragment and the
/// `#[settings]` macro instead. Use [`create_smtp_backend_from_settings`] (or
/// [`backend_from_settings`]) to build a backend from settings, or
/// `SmtpConfig::from(&settings)` for the bridge.
#[deprecated(
	since = "0.2.0",
	note = "Use `EmailSettings` with the `#[settings]` macro instead."
)]
#[derive(Debug, Clone)]
pub struct SmtpConfig {
	/// SMTP server hostname.
	pub host: String,
	/// SMTP server port number.
	pub port: u16,
	/// Optional username for SMTP authentication.
	pub username: Option<String>,
	/// Optional password for SMTP authentication.
	pub password: Option<String>,
	/// Connection security mode (none, STARTTLS, or TLS).
	pub security: SmtpSecurity,
	/// Authentication mechanism to use.
	pub auth_mechanism: SmtpAuthMechanism,
	/// Connection timeout duration.
	pub timeout: Duration,
}

impl Default for SmtpConfig {
	fn default() -> Self {
		Self {
			host: "localhost".to_string(),
			port: 25,
			username: None,
			password: None,
			security: SmtpSecurity::None,
			auth_mechanism: SmtpAuthMechanism::Auto,
			timeout: Duration::from_secs(30),
		}
	}
}

impl SmtpConfig {
	/// Creates a new SMTP configuration with the given host and port.
	pub fn new(host: impl Into<String>, port: u16) -> Self {
		Self {
			host: host.into(),
			port,
			username: None,
			password: None,
			security: SmtpSecurity::None,
			auth_mechanism: SmtpAuthMechanism::Auto,
			timeout: Duration::from_secs(30),
		}
	}

	/// Sets the SMTP authentication credentials.
	pub fn with_credentials(mut self, username: String, password: String) -> Self {
		self.username = Some(username);
		self.password = Some(password);
		self
	}

	/// Sets the connection security mode.
	pub fn with_security(mut self, security: SmtpSecurity) -> Self {
		self.security = security;
		self
	}

	/// Sets the authentication mechanism.
	pub fn with_auth_mechanism(mut self, mechanism: SmtpAuthMechanism) -> Self {
		self.auth_mechanism = mechanism;
		self
	}

	/// Sets the connection timeout duration.
	pub fn with_timeout(mut self, timeout: Duration) -> Self {
		self.timeout = timeout;
		self
	}

	/// Validate the SMTP configuration
	///
	/// Checks that email-formatted usernames (containing `@`) are valid email addresses.
	pub fn validate(&self) -> EmailResult<()> {
		// Validate username if it looks like an email address
		if let Some(username) = &self.username
			&& username.contains('@')
		{
			crate::validation::validate_email(username)?;
		}
		Ok(())
	}
}

/// Build an [`SmtpConfig`] from an email settings fragment or composed settings.
///
/// This mirrors the SMTP branch of [`backend_from_settings`]: the security mode
/// is derived from the `use_tls`/`use_ssl` flags, the timeout defaults to 60
/// seconds when unset, and credentials are populated only when both username and
/// password are present.
impl<S: HasSettings<EmailSettings> + ?Sized> From<&S> for SmtpConfig {
	fn from(settings: &S) -> Self {
		let email_settings = settings.get_settings();
		let security = match (email_settings.use_tls, email_settings.use_ssl) {
			(true, _) => SmtpSecurity::StartTls,
			(_, true) => SmtpSecurity::Tls,
			_ => SmtpSecurity::None,
		};

		let timeout = email_settings
			.timeout
			.map(Duration::from_secs)
			.unwrap_or_else(|| Duration::from_secs(60));

		let mut config = SmtpConfig::new(&email_settings.host, email_settings.port)
			.with_security(security)
			.with_timeout(timeout);

		if let (Some(username), Some(password)) =
			(&email_settings.username, &email_settings.password)
		{
			config = config.with_credentials(username.to_string(), password.to_string());
		}

		config
	}
}

/// Build an [`SmtpBackend`] from an email settings fragment or composed settings.
///
/// This is the settings-first entry point for constructing an SMTP backend.
/// Prefer it over building an [`SmtpConfig`] manually.
///
/// # Errors
/// Returns [`EmailError`] if the resulting configuration fails validation (for
/// example, an email-formatted username that is not a valid address).
pub fn create_smtp_backend_from_settings<S: HasSettings<EmailSettings> + ?Sized>(
	settings: &S,
) -> EmailResult<SmtpBackend> {
	SmtpBackend::new(SmtpConfig::from(settings))
}

/// Zeroize SMTP credentials on drop to prevent sensitive data from lingering in memory.
///
/// This ensures that username and password fields are securely erased when
/// the `SmtpConfig` is no longer needed, reducing the risk of credential
/// exposure through memory inspection or core dumps.
impl Drop for SmtpConfig {
	fn drop(&mut self) {
		if let Some(ref mut username) = self.username {
			username.zeroize();
		}
		if let Some(ref mut password) = self.password {
			password.zeroize();
		}
	}
}

/// SMTP backend for sending emails
///
/// # Examples
///
/// ```rust,no_run
/// # #![allow(deprecated)]
/// # use reinhardt_mail::{SmtpBackend, SmtpConfig, SmtpSecurity};
/// # use std::time::Duration;
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let config = SmtpConfig::new("smtp.gmail.com", 587)
///     .with_credentials("user@gmail.com".to_string(), "password".to_string())
///     .with_security(SmtpSecurity::StartTls)
///     .with_timeout(Duration::from_secs(30));
///
/// let backend = SmtpBackend::new(config)?;
/// # Ok(())
/// # }
/// ```
pub struct SmtpBackend {
	config: SmtpConfig,
}

impl SmtpBackend {
	/// Creates a new SMTP backend with the given configuration.
	pub fn new(config: SmtpConfig) -> EmailResult<Self> {
		config.validate()?;
		Ok(Self { config })
	}

	fn build_transport(&self) -> EmailResult<AsyncSmtpTransport<Tokio1Executor>> {
		// Use lettre's recommended secure APIs for standard ports
		// This ensures proper TLS hostname verification by default
		match (&self.config.security, self.config.port) {
			// Port 465 with TLS: use relay() for secure SMTPS
			(SmtpSecurity::Tls, 465) => {
				let builder = AsyncSmtpTransport::<Tokio1Executor>::relay(&self.config.host)
					.map_err(|e| EmailError::SmtpError(format!("TLS relay error: {}", e)))?
					.timeout(Some(self.config.timeout));
				let builder = self.configure_auth(builder);
				Ok(builder.build())
			}
			// Port 587 with STARTTLS: use starttls_relay() for secure STARTTLS
			(SmtpSecurity::StartTls, 587) => {
				let builder =
					AsyncSmtpTransport::<Tokio1Executor>::starttls_relay(&self.config.host)
						.map_err(|e| EmailError::SmtpError(format!("STARTTLS relay error: {}", e)))?
						.timeout(Some(self.config.timeout));
				let builder = self.configure_auth(builder);
				Ok(builder.build())
			}
			// Custom port or no TLS: use builder_dangerous with manual TLS configuration
			// This is needed for test environments and non-standard SMTP configurations
			_ => self.build_transport_with_custom_port(),
		}
	}

	/// Configure authentication on the transport builder
	fn configure_auth(
		&self,
		mut builder: lettre::transport::smtp::AsyncSmtpTransportBuilder,
	) -> lettre::transport::smtp::AsyncSmtpTransportBuilder {
		if let (Some(username), Some(password)) = (&self.config.username, &self.config.password) {
			let credentials = Credentials::new(username.clone(), password.clone());

			builder = match &self.config.auth_mechanism {
				SmtpAuthMechanism::Plain => builder
					.credentials(credentials)
					.authentication(vec![Mechanism::Plain]),
				SmtpAuthMechanism::Login => builder
					.credentials(credentials)
					.authentication(vec![Mechanism::Login]),
				SmtpAuthMechanism::Auto => builder.credentials(credentials),
			};
		}
		builder
	}

	/// Build transport with custom port using builder_dangerous
	///
	/// This method is used for non-standard ports or when TLS is disabled.
	/// For standard ports (465/587), prefer `relay()` or `starttls_relay()` instead.
	fn build_transport_with_custom_port(&self) -> EmailResult<AsyncSmtpTransport<Tokio1Executor>> {
		let mut builder =
			AsyncSmtpTransport::<Tokio1Executor>::builder_dangerous(&self.config.host)
				.port(self.config.port)
				.timeout(Some(self.config.timeout));

		// Configure TLS/SSL
		match &self.config.security {
			SmtpSecurity::None => {
				// No encryption - intended for test environments only
			}
			SmtpSecurity::StartTls => {
				let tls_params = TlsParameters::builder(self.config.host.clone())
					.build()
					.map_err(|e| EmailError::SmtpError(format!("TLS error: {}", e)))?;
				builder = builder.tls(Tls::Required(tls_params));
			}
			SmtpSecurity::Tls => {
				let tls_params = TlsParameters::builder(self.config.host.clone())
					.build()
					.map_err(|e| EmailError::SmtpError(format!("TLS error: {}", e)))?;
				builder = builder.tls(Tls::Wrapper(tls_params));
			}
		}

		builder = self.configure_auth(builder);

		Ok(builder.build())
	}

	fn build_message(&self, email: &EmailMessage) -> EmailResult<Message> {
		// Parse from address
		let from = email
			.from_email()
			.parse::<Mailbox>()
			.map_err(|e| EmailError::InvalidAddress(format!("Invalid from address: {}", e)))?;

		// Start building the message
		let mut builder = Message::builder().from(from).subject(email.subject());

		// Add recipients
		for to in email.to() {
			let mailbox = to
				.parse::<Mailbox>()
				.map_err(|e| EmailError::InvalidAddress(format!("Invalid to address: {}", e)))?;
			builder = builder.to(mailbox);
		}

		// Add CC recipients
		for cc in email.cc() {
			let mailbox = cc
				.parse::<Mailbox>()
				.map_err(|e| EmailError::InvalidAddress(format!("Invalid cc address: {}", e)))?;
			builder = builder.cc(mailbox);
		}

		// Add BCC recipients
		for bcc in email.bcc() {
			let mailbox = bcc
				.parse::<Mailbox>()
				.map_err(|e| EmailError::InvalidAddress(format!("Invalid bcc address: {}", e)))?;
			builder = builder.bcc(mailbox);
		}

		// Add Reply-To
		for reply_to in email.reply_to() {
			let mailbox = reply_to.parse::<Mailbox>().map_err(|e| {
				EmailError::InvalidAddress(format!("Invalid reply-to address: {}", e))
			})?;
			builder = builder.reply_to(mailbox);
		}

		// Add custom headers
		// Known headers are added via typed lettre Header implementations.
		// Unknown/arbitrary headers are injected via raw header insertion after message build.
		let mut deferred_headers: Vec<(String, String)> = Vec::new();
		for (name, value) in email.headers() {
			let name_lower = name.to_lowercase();
			match name_lower.as_str() {
				"x-mailer" => {
					builder = builder.header(XMailer::new(value));
				}
				"x-priority" => {
					builder = builder.header(XPriority::new(value));
				}
				"list-unsubscribe" => {
					builder = builder.header(ListUnsubscribe::new(value));
				}
				"list-unsubscribe-post" => {
					builder = builder.header(ListUnsubscribePost::new(value));
				}
				"x-entity-ref-id" => {
					builder = builder.header(XEntityRefId::new(value));
				}
				"precedence" => {
					builder = builder.header(Precedence::new(value));
				}
				_ => {
					// Defer arbitrary headers for raw insertion after build
					deferred_headers.push((name.clone(), value.clone()));
				}
			}
		}

		// Build the body - convert body to String once to avoid repeated allocation
		let has_html = email.html_body().is_some();
		let has_attachments = !email.attachments().is_empty();
		let body = email.body().to_string();

		let message = if has_html && has_attachments {
			// HTML with plain text alternative AND attachments
			// Structure: mixed( alternative(text, html), attachment1, attachment2, ... )
			let alternative = MultiPart::alternative()
				.singlepart(SinglePart::plain(body))
				.singlepart(SinglePart::html(email.html_body().unwrap().to_string()));

			let mut mixed = MultiPart::mixed().multipart(alternative);

			for attachment in email.attachments() {
				let content_type = header::ContentType::parse(attachment.mime_type())
					.unwrap_or(header::ContentType::parse("application/octet-stream").unwrap());

				let part = if let Some(cid) = attachment.content_id() {
					SinglePart::builder()
						.header(content_type)
						.header(header::ContentDisposition::inline())
						.header(header::ContentId::from(cid.to_string()))
						.body(attachment.content().to_vec())
				} else {
					SinglePart::builder()
						.header(content_type)
						.header(header::ContentDisposition::attachment(
							attachment.filename(),
						))
						.body(attachment.content().to_vec())
				};

				mixed = mixed.singlepart(part);
			}

			builder
				.multipart(mixed)
				.map_err(|e| EmailError::BackendError(format!("Failed to build message: {}", e)))?
		} else if has_html {
			// HTML with plain text alternative (no attachments)
			let multipart = MultiPart::alternative()
				.singlepart(SinglePart::plain(body))
				.singlepart(SinglePart::html(email.html_body().unwrap().to_string()));

			builder
				.multipart(multipart)
				.map_err(|e| EmailError::BackendError(format!("Failed to build message: {}", e)))?
		} else if has_attachments {
			// Plain text with attachments
			let mut multipart = MultiPart::mixed().singlepart(SinglePart::plain(body));

			for attachment in email.attachments() {
				let content_type = header::ContentType::parse(attachment.mime_type())
					.unwrap_or(header::ContentType::parse("application/octet-stream").unwrap());

				let part = if let Some(cid) = attachment.content_id() {
					// Inline attachment with content ID and Content-Type
					SinglePart::builder()
						.header(content_type)
						.header(header::ContentDisposition::inline())
						.header(header::ContentId::from(cid.to_string()))
						.body(attachment.content().to_vec())
				} else {
					// Regular attachment with Content-Type
					SinglePart::builder()
						.header(content_type)
						.header(header::ContentDisposition::attachment(
							attachment.filename(),
						))
						.body(attachment.content().to_vec())
				};

				multipart = multipart.singlepart(part);
			}

			builder
				.multipart(multipart)
				.map_err(|e| EmailError::BackendError(format!("Failed to build message: {}", e)))?
		} else {
			// Plain text only
			builder
				.body(body)
				.map_err(|e| EmailError::BackendError(format!("Failed to build message: {}", e)))?
		};

		// Inject deferred arbitrary headers via raw insertion
		let mut message = message;
		for (name, value) in deferred_headers {
			match HeaderName::new_from_ascii(name.clone()) {
				Ok(header_name) => {
					let header_value = HeaderValue::new(header_name, value);
					message.headers_mut().insert_raw(header_value);
				}
				Err(_) => {
					return Err(EmailError::InvalidHeader(format!(
						"Invalid header name: '{}'",
						name
					)));
				}
			}
		}

		Ok(message)
	}
}

#[async_trait::async_trait]
impl EmailBackend for SmtpBackend {
	async fn send_messages(&self, messages: &[EmailMessage]) -> EmailResult<usize> {
		let transport = self.build_transport()?;

		let mut sent_count = 0;
		for email in messages {
			let message = self.build_message(email)?;

			transport
				.send(message)
				.await
				.map_err(|e| EmailError::SmtpError(format!("Failed to send email: {}", e)))?;

			sent_count += 1;
		}

		Ok(sent_count)
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn smtp_config_from_fragment_email_settings() {
		// Arrange
		let mut settings = reinhardt_conf::EmailSettings::default();
		settings.host = "smtp.example.com".to_string();
		settings.port = 587;
		settings.username = Some("user@example.com".to_string());
		settings.password = Some("secret".to_string());
		settings.use_tls = true;
		settings.timeout = Some(45);

		// Act
		let config = SmtpConfig::from(&settings);

		// Assert
		assert_eq!(config.host, "smtp.example.com");
		assert_eq!(config.port, 587);
		assert_eq!(config.username.as_deref(), Some("user@example.com"));
		assert_eq!(config.password.as_deref(), Some("secret"));
		assert!(matches!(config.security, SmtpSecurity::StartTls));
		assert_eq!(config.timeout, Duration::from_secs(45));
	}
}