Path: redb-route/redb.Route.Mail/MailEndpointOptions.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Mail/MailEndpointOptions.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
namespace redb.Route.Mail;
///
/// Options for mail endpoints (SMTP, IMAP, POP3). Bound from URI query parameters.
/// Provides Camel-level configurability for enterprise email integration.
///
///
/// SMTP URI: smtp://mail.example.com:587?username=bot@ex.com&password=xxx&security=StartTls
/// IMAP URI: imap://mail.example.com:993?username=inbox@ex.com&password=xxx&folder=INBOX&unseen=true
/// POP3 URI: pop3://mail.example.com:995?username=inbox@ex.com&password=xxx&delete=true
///
public class MailEndpointOptions : EndpointOptions
{
// ── Connection ────────────────────────────────────────────────────
/// Mail server hostname. Resolved from URI host or this parameter.
public string Host { get; set; } = "localhost";
/// Mail server port. 0 = auto-detect from protocol and security mode.
public int Port { get; set; }
/// Connection security mode (None, Ssl, StartTls, Auto).
public MailSecurityMode Security { get; set; } = MailSecurityMode.Auto;
/// Connection timeout in milliseconds.
public int ConnectionTimeout { get; set; } = 30_000;
/// Socket read/write timeout in milliseconds.
public int Timeout { get; set; } = 60_000;
// ── Authentication ────────────────────────────────────────────────
///
/// Named from the route registry. Lets mailbox credentials
/// live in the registry instead of the endpoint URI, so they never reach logs or dashboards.
///
[RegistryReference(typeof(MailConnectionFactory))]
public string? ConnectionFactory { get; set; }
/// Username for authentication.
public string Username { get; set; } = "";
/// Password for authentication.
[Sensitive]
public string Password { get; set; } = "";
/// OAuth2 access token (for XOAUTH2/OAUTHBEARER).
[Sensitive]
public string AccessToken { get; set; } = "";
/// Authentication mechanism to use.
public MailAuthMechanism AuthMechanism { get; set; } = MailAuthMechanism.Auto;
// ── TLS/SSL ───────────────────────────────────────────────────────
/// Skip server certificate validation (development only!).
public bool TrustAllCertificates { get; set; }
/// Client certificate path for mutual TLS.
public string ClientCertPath { get; set; } = "";
/// Client certificate password.
[Sensitive]
public string ClientCertPassword { get; set; } = "";
// ── SMTP Producer options ─────────────────────────────────────────
/// Default From address for sent emails. Can be overridden by MailHeaders.From header.
[EndpointRole(EndpointRole.Producer)]
public string From { get; set; } = "";
/// Default To addresses (comma-separated). Can be overridden by MailHeaders.To header.
[EndpointRole(EndpointRole.Producer)]
public string To { get; set; } = "";
/// Default CC addresses (comma-separated).
[EndpointRole(EndpointRole.Producer)]
public string Cc { get; set; } = "";
/// Default BCC addresses (comma-separated).
[EndpointRole(EndpointRole.Producer)]
public string Bcc { get; set; } = "";
/// Default Reply-To address.
[EndpointRole(EndpointRole.Producer)]
public string ReplyTo { get; set; } = "";
/// Default subject line. Supports Simple expressions: ${header.orderId}.
[EndpointRole(EndpointRole.Producer)]
public string Subject { get; set; } = "";
/// Content type of the email body: text/plain or text/html.
[EndpointRole(EndpointRole.Producer)]
public string ContentType { get; set; } = "text/plain";
/// Alternative body (e.g. text/plain alternative when body is HTML).
[EndpointRole(EndpointRole.Producer)]
public bool AlternativeBody { get; set; }
/// Comma-separated file paths for attachments.
[EndpointRole(EndpointRole.Producer)]
public string Attachments { get; set; } = "";
// ── IMAP/POP3 Consumer options ────────────────────────────────────
/// IMAP folder to monitor (default: INBOX).
[EndpointRole(EndpointRole.Consumer)]
public string Folder { get; set; } = "INBOX";
/// Additional IMAP folders to monitor (comma-separated).
[EndpointRole(EndpointRole.Consumer)]
public string AdditionalFolders { get; set; } = "";
/// Polling interval in milliseconds.
[EndpointRole(EndpointRole.Consumer)]
public int Delay { get; set; } = 60_000;
/// Initial delay before first poll in milliseconds.
[EndpointRole(EndpointRole.Consumer)]
public int InitialDelay { get; set; }
///
/// Message filter for fetch (Unseen, All, Recent, Flagged, etc.), IMAP. A set selects the mails
/// instead, so the two are not set together.
///
[EndpointRole(EndpointRole.Consumer)]
public MailFetchFilter FetchFilter
{
get => _fetchFilter;
set { _fetchFilter = value; _fetchFilterSet = true; }
}
private MailFetchFilter _fetchFilter = MailFetchFilter.Unseen;
private bool _fetchFilterSet;
/// Maximum number of messages to fetch per poll cycle.
[EndpointRole(EndpointRole.Consumer)]
public int MaxMessages { get; set; } = 50;
///
/// What to do with a message whose exchange succeeded (Apache Camel's commit). An exchange that failed, with an
/// unhandled exception or marked rollback-only (.RollbackAll()), leaves the message as it is (Camel's
/// rollback); a handled exception is a success.
///
[EndpointRole(EndpointRole.Consumer)]
public PostProcessAction PostProcess
{
get => _postProcess;
set { _postProcess = value; _postProcessSet = true; }
}
private PostProcessAction _postProcess = PostProcessAction.MarkRead;
private bool _postProcessSet;
///
/// Apache Camel's delete, beside : true deletes a message whose exchange
/// succeeded, the same as postProcess=Delete, moving it to first when that is set;
/// false leaves to decide. A value that contradicts an explicit
/// fails validation. The header overrides it per message.
///
[EndpointRole(EndpointRole.Consumer)]
public bool Delete
{
get => _delete;
set { _delete = value; _deleteSet = true; }
}
private bool _delete;
private bool _deleteSet;
///
/// Target folder for Move/MarkReadAndMove post-processing, and for delete=true (IMAP only); created when
/// the mailbox does not have it.
///
[EndpointRole(EndpointRole.Consumer)]
public string MoveTo { get; set; } = "";
///
/// Apache Camel's copyTo: an IMAP folder a message whose exchange succeeded is copied to before anything
/// else is done to it. The header overrides it per message. Created when
/// missing; POP3 ignores it.
///
[EndpointRole(EndpointRole.Consumer)]
public string CopyTo { get; set; } = "";
/// Sort order for fetched messages.
[EndpointRole(EndpointRole.Consumer)]
public MailSortBy SortBy { get; set; } = MailSortBy.None;
/// Whether to use IMAP IDLE for push notifications instead of polling.
[EndpointRole(EndpointRole.Consumer)]
public bool Idle { get; set; }
/// IMAP IDLE timeout in milliseconds (max time to wait before re-issuing IDLE).
[EndpointRole(EndpointRole.Consumer)]
public int IdleTimeout { get; set; } = 29 * 60 * 1000; // 29 minutes (RFC 2177 recommends < 30 min)
/// Whether to download message body (false = headers only for envelope scanning).
[EndpointRole(EndpointRole.Consumer)]
public bool FetchBody { get; set; } = true;
/// Whether to carry attachment payloads on the exchange (names/count always stay).
[EndpointRole(EndpointRole.Consumer)]
public bool FetchAttachments { get; set; } = true;
///
/// Maximum DECODED attachment size in bytes carried on the exchange (0 = unlimited).
/// Caps the copy handed to the route, not the network transfer: the MIME message is already
/// in memory when the cap is applied; an oversized attachment keeps its name in
/// AttachmentNames but its payload is dropped.
///
[EndpointRole(EndpointRole.Consumer)]
public long MaxAttachmentSize { get; set; }
///
/// IMAP, Apache Camel's peek: true (the default) fetches a message without marking it read, so a
/// message whose exchange fails stays unseen and is fetched again; false marks it read when it is fetched,
/// just before the route, so a failed message stays read and fetchFilter=Unseen does not fetch it again.
/// POP3 has no read flag and ignores it.
///
[EndpointRole(EndpointRole.Consumer)]
public bool Peek { get; set; } = true;
///
/// In-memory idempotency: a message this consumer routed successfully is skipped when it is fetched again, until
/// the consumer restarts; a failed one is routed again. keeps the keys beyond a
/// restart and takes precedence. The key is the Message-ID, else folder, UIDVALIDITY and UID (IMAP) or the UIDL
/// (POP3).
///
[EndpointRole(EndpointRole.Consumer)]
public bool Idempotent { get; set; }
///
/// Apache Camel's idempotentRepository: the name of an registered with
/// context.AddIdempotentRepository(name, repository) or declared as a bean. A message's key is added before
/// its route and the message is skipped when the repository already holds it; a failed exchange removes the key,
/// a successful one removes it or confirms it (). The key is the
/// Message-ID, else folder, UIDVALIDITY and UID (IMAP) or the UIDL (POP3). Takes precedence over
/// .
///
[EndpointRole(EndpointRole.Consumer)]
[RegistryReference(typeof(IIdempotentRepository))]
public string? IdempotentRepository { get; set; }
///
/// Apache Camel's idempotentRepositoryRemoveOnCommit (default true): a committed message is removed
/// from , since it was deleted or marked read; false confirms its key, so
/// it is skipped whenever it is fetched again.
///
[EndpointRole(EndpointRole.Consumer)]
public bool IdempotentRepositoryRemoveOnCommit { get; set; } = true;
///
/// Apache Camel's searchTerm: which mails the consumer takes, as an option group
/// (searchTerm.subject=invoice&searchTerm.fromSentDate=now-24h) or a MailKit search query from the registry
/// (searchTerm=#name, IMAP only). A set search term replaces ; see
/// .
///
[EndpointRole(EndpointRole.Consumer)]
[OptionGroup]
public MailSearchTerm? SearchTerm { get; set; }
/// Minimum message age in milliseconds (skip messages newer than this).
[EndpointRole(EndpointRole.Consumer)]
public long MinAge { get; set; }
/// Maximum message age in milliseconds (skip messages older than this).
[EndpointRole(EndpointRole.Consumer)]
public long MaxAge { get; set; }
/// Subject filter — only process messages matching this pattern (regex).
[EndpointRole(EndpointRole.Consumer)]
public string SubjectFilter { get; set; } = "";
/// From filter — only process messages from these addresses (comma-separated).
[EndpointRole(EndpointRole.Consumer)]
public string FromFilter { get; set; } = "";
/// Whether to include MIME headers as exchange headers.
[EndpointRole(EndpointRole.Consumer)]
public bool MapMimeHeaders { get; set; }
/// Whether to keep the raw MimeMessage in exchange properties.
[EndpointRole(EndpointRole.Consumer)]
public bool KeepRawMessage { get; set; }
// ── Connection pooling ────────────────────────────────────────────
/// Whether to disconnect after each operation (default: maintain persistent connection).
public bool Disconnect { get; set; }
///
protected override string? UnknownParameterHint(string name)
{
if (name.Equals("skipCertificateValidation", StringComparison.OrdinalIgnoreCase))
return "'skipCertificateValidation' is renamed 'trustAllCertificates', the name every other connector uses.";
if (name.Equals("searchQuery", StringComparison.OrdinalIgnoreCase))
return "'searchQuery' is gone (it was never applied): write Apache Camel's searchTerm, as options "
+ "(searchTerm.subject=..., searchTerm.from=..., searchTerm.fromSentDate=now-24h) or searchTerm=#name.";
return null;
}
///
public override void Validate() => Validate(side: null);
///
/// Validates what the side being created reads: an smtp producer does not check the consumer options (a stray
/// one is refused by name before, ); null checks everything.
///
internal void Validate(EndpointRole? side)
{
if (Port < 0 || Port > 65535)
throw new ArgumentOutOfRangeException(nameof(Port), "Port must be 0-65535.");
if (ConnectionTimeout < 0)
throw new ArgumentOutOfRangeException(nameof(ConnectionTimeout));
if (Timeout < 0)
throw new ArgumentOutOfRangeException(nameof(Timeout));
if (side == EndpointRole.Producer)
return;
if (Delay < 0)
throw new ArgumentOutOfRangeException(nameof(Delay), "Delay must be non-negative.");
if (MaxMessages < 0)
throw new ArgumentOutOfRangeException(nameof(MaxMessages), "MaxMessages must be non-negative.");
if (SearchTerm is not null)
{
if (_fetchFilterSet)
throw new InvalidOperationException(
"searchTerm selects the mails, as fetchFilter does; set only one of them (searchTerm.unseen=false takes the "
+ "seen mails too).");
SearchTerm.Validate();
}
if (_deleteSet && _postProcessSet)
{
if (_delete && _postProcess != PostProcessAction.Delete)
throw new InvalidOperationException(
$"delete=true deletes the message, which contradicts postProcess={_postProcess}; set only one of them.");
if (!_delete && _postProcess == PostProcessAction.Delete)
throw new InvalidOperationException(
"delete=false keeps the message, which contradicts postProcess=Delete; set only one of them.");
}
if (PostProcess is PostProcessAction.Move or PostProcessAction.MarkReadAndMove
&& string.IsNullOrWhiteSpace(MoveTo))
throw new InvalidOperationException("MoveTo is required when PostProcess is Move or MarkReadAndMove.");
}
///
/// Refuses the parameters wrote whose option only the other side reads
/// (): imap, pop3 and smtp share these options, and such a parameter would bind
/// and do nothing. Each mail component has one side, so it refuses them when it creates the endpoint, naming the
/// parameters and never their values.
///
internal static void RefuseOtherSide(EndpointUri uri, string scheme, EndpointRole side)
{
var written = EndpointOptions.WrittenForOtherRole(typeof(MailEndpointOptions), uri, side);
if (written.Count == 0)
return;
var (self, reader) = side == EndpointRole.Producer
? ("producer", "an imap or pop3 consumer")
: ("consumer", "an smtp producer");
throw new InvalidOperationException(
$"{scheme} {self} '{EndpointUri.Sanitize(uri.NormalizedKey)}' sets {string.Join(", ", written)}: " +
$"only {reader} reads {(written.Count == 1 ? "it" : "them")}.");
}
///
/// Resolves the effective port based on protocol scheme and security mode.
///
internal int ResolvePort(string scheme)
{
if (Port > 0) return Port;
return scheme switch
{
"smtp" => Security switch
{
MailSecurityMode.Ssl => 465,
MailSecurityMode.None => 25,
_ => 587
},
"imap" => Security is MailSecurityMode.None ? 143 : 993,
"pop3" => Security is MailSecurityMode.None ? 110 : 995,
_ => 25
};
}
///
/// Resolves MailKit SecureSocketOptions from the Security setting.
///
internal MailKit.Security.SecureSocketOptions ResolveSecurityOptions()
{
return Security switch
{
MailSecurityMode.None => MailKit.Security.SecureSocketOptions.None,
MailSecurityMode.Ssl => MailKit.Security.SecureSocketOptions.SslOnConnect,
MailSecurityMode.StartTls => MailKit.Security.SecureSocketOptions.StartTls,
MailSecurityMode.Auto => MailKit.Security.SecureSocketOptions.Auto,
_ => MailKit.Security.SecureSocketOptions.Auto
};
}
}