(priority, true, out var p))
msg.Priority = p;
// ── Body ──
var body = exchange.In.Body is { } raw ? BodyText.Of(raw) : "";
var contentType = GetHeader(exchange, MailHeaders.ContentType)
?? _options.ResolveOption(_options.ContentType, exchange)
?? _options.ContentType;
var isHtml = contentType.Contains("html", StringComparison.OrdinalIgnoreCase);
var bodyBuilder = new BodyBuilder();
if (isHtml)
{
bodyBuilder.HtmlBody = body;
// Also set plain text alternative from header if provided
var textAlt = GetHeader(exchange, MailHeaders.TextBody);
if (!string.IsNullOrWhiteSpace(textAlt))
bodyBuilder.TextBody = textAlt;
else if (_options.AlternativeBody)
bodyBuilder.TextBody = StripHtml(body);
}
else
{
bodyBuilder.TextBody = body;
// Also set HTML alternative from header if provided
var htmlAlt = GetHeader(exchange, MailHeaders.HtmlBody);
if (!string.IsNullOrWhiteSpace(htmlAlt))
bodyBuilder.HtmlBody = htmlAlt;
}
// ── Attachments ──
AddAttachments(bodyBuilder, exchange);
msg.Body = bodyBuilder.ToMessageBody();
// ── Custom headers from exchange ──
foreach (var (key, value) in exchange.In.Headers)
{
if (key.StartsWith("X-", StringComparison.OrdinalIgnoreCase)
&& !MailHeaders.IsRedbHeader(key)
&& value is string sv)
{
msg.Headers.Add(key, sv);
}
}
return msg;
}
private void AddAttachments(BodyBuilder bodyBuilder, IExchange exchange)
{
// From options: comma-separated file paths
if (!string.IsNullOrWhiteSpace(_options.Attachments))
{
foreach (var path in _options.Attachments.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
if (System.IO.File.Exists(path))
bodyBuilder.Attachments.Add(path);
}
}
// The message attachments, whichever step or consumer put them there.
foreach (var attachment in exchange.In.Attachments)
AddAttachment(bodyBuilder, attachment);
}
///
/// Writes one message attachment as a MIME part: file name (else the attachment name), content type,
/// Content-ID, an inline disposition when the source part declared one, and the other part
/// headers that are not Content-* (those come from the attachment fields).
///
private static void AddAttachment(BodyBuilder bodyBuilder, Attachment attachment)
{
MimeEntity entity;
using (var content = attachment.Content.OpenRead())
entity = bodyBuilder.Attachments.Add(attachment.FileName ?? attachment.Name, content,
ContentType.Parse(attachment.ContentType));
if (attachment.ContentId is { Length: > 0 } contentId)
entity.ContentId = contentId;
foreach (var (name, value) in attachment.Headers)
{
if (name.Equals("Content-Disposition", StringComparison.OrdinalIgnoreCase))
{
if (ContentDisposition.TryParse(value, out var disposition)
&& disposition.Disposition.Equals(ContentDisposition.Inline, StringComparison.OrdinalIgnoreCase)
&& entity.ContentDisposition is { } written)
written.Disposition = ContentDisposition.Inline;
continue;
}
if (!name.StartsWith("Content-", StringComparison.OrdinalIgnoreCase))
entity.Headers.Add(name, value);
}
}
/// The failures of a connection the server closed while it was kept open between sends.
private static bool IsDeadConnection(Exception ex) => ex is ServiceNotConnectedException or SmtpProtocolException
or System.IO.IOException
|| ex is SmtpCommandException { StatusCode: SmtpStatusCode.ServiceNotAvailable };
private void Drop(SmtpClient client)
{
lock (_lock)
{
if (ReferenceEquals(_client, client))
_client = null;
}
client.Dispose();
}
/// The kept connection when there is one (reused), else a new one, connected and authenticated.
private async Task<(SmtpClient Client, bool Reused)> EnsureConnectedAsync(CancellationToken ct)
{
lock (_lock)
{
if (_client is { IsConnected: true })
return (_client, true);
}
var client = new SmtpClient();
client.Timeout = _options.Timeout;
if (_options.TrustAllCertificates)
client.ServerCertificateValidationCallback = (_, _, _, _) => true;
await client.ConnectAsync(
_endpoint.Host,
_endpoint.Port,
_options.ResolveSecurityOptions(),
ct).ConfigureAwait(false);
await AuthenticateAsync(client, ct).ConfigureAwait(false);
lock (_lock) _client = client;
return (client, false);
}
private async Task AuthenticateAsync(SmtpClient client, CancellationToken ct)
{
if (!string.IsNullOrEmpty(_options.AccessToken))
{
var mechanism = _options.AuthMechanism switch
{
MailAuthMechanism.OAuthBearer => new MailKit.Security.SaslMechanismOAuthBearer(_options.Username, _options.AccessToken),
_ => (MailKit.Security.SaslMechanism)new MailKit.Security.SaslMechanismOAuth2(_options.Username, _options.AccessToken)
};
await client.AuthenticateAsync(mechanism, ct).ConfigureAwait(false);
}
else if (!string.IsNullOrEmpty(_options.Username))
{
await client.AuthenticateAsync(_options.Username, _options.Password, ct).ConfigureAwait(false);
}
}
private static string? GetHeader(IExchange exchange, string key)
{
return exchange.In.Headers.TryGetValue(key, out var val) && val is string s && !string.IsNullOrWhiteSpace(s)
? s : null;
}
private static string StripHtml(string html)
{
if (string.IsNullOrEmpty(html)) return "";
var text = Regex.Replace(html, "
", "\n", RegexOptions.IgnoreCase);
text = Regex.Replace(text, "", "\n", RegexOptions.IgnoreCase);
text = Regex.Replace(text, "<[^>]+>", "");
return System.Net.WebUtility.HtmlDecode(text).Trim();
}
}
///
/// A decoded attachment of a received mail inside . The same attachment is also on the
/// message attachments (), which is what smtp: sends.
///
/// Attachment file name.
/// Attachment content bytes.
/// MIME content type (default: application/octet-stream).
public sealed class MailAttachment(string fileName, byte[] content, string? contentType = null) : ICloneable
{
/// Attachment file name.
public string FileName { get; } = fileName;
/// Decoded attachment payload.
public byte[] Content { get; } = content;
/// MIME content type, when known.
public string? ContentType { get; } = contentType;
// A class, not a record: records may not implement ICloneable (CS8859), and ICloneable is
// what Message.DeepCopyBody requires to carry this body through a checkpoint snapshot.
/// Deep copy for checkpoint snapshots — the payload bytes must not be shared.
public object Clone() => new MailAttachment(FileName, (byte[])Content.Clone(), ContentType);
}