Bundle: redb-route / redb.Route.Mail (redb.Route.Mail.txt), 14 files Snapshot: 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 Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt ==== Path: redb-route/redb.Route.Mail/Extensions/ServiceCollectionExtensions.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/Extensions/ServiceCollectionExtensions.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Route.Extensions; namespace redb.Route.Mail; /// /// Extension methods for registering the Mail transport (SMTP, IMAP, POP3) in a DI container. /// public static class ServiceCollectionExtensions { /// /// Registers , , and /// so that smtp://, imap://, and pop3:// URIs are resolved. /// /// /// services.AddRedbRoute(route => /// { /// route.Services.AddRedbRouteMail(); /// route.AddRouteBuilder<MyRoutes>(); /// }); /// /// /// public static IServiceCollection AddRedbRouteMail(this IServiceCollection services) { services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); // IRouteContextConfigurator is applied by RouteHostedService at startup -- // the correct registration hook (a lazy marker singleton never fires). services.AddRouteContextConfigurator((sp, context) => { context.AddComponent(sp.GetRequiredService()); context.AddComponent(sp.GetRequiredService()); context.AddComponent(sp.GetRequiredService()); }); return services; } } Path: redb-route/redb.Route.Mail/Fluent/MailDsl.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/Fluent/MailDsl.cs ---- using System.Text; using redb.Route.Abstractions; namespace redb.Route.Mail; /// /// Fluent API for SMTP (send email) endpoints. /// /// .To(Smtp.Send("smtp.example.com").Port(587).Security("StartTls") /// .Username("bot@example.com").Password("secret") /// .From("bot@example.com").To("user@example.com").Subject("Alert")) /// /// public static class Smtp { /// Creates an SMTP producer endpoint for the given mail server. public static MailBuilder Send(string server) => new("smtp", server); } /// /// Fluent API for IMAP (receive email) endpoints. /// /// .From(Imap.Read("imap.example.com").Port(993).Security("Ssl") /// .Username("inbox@example.com").Password("secret") /// .Folder("INBOX").Unseen().Delay(30000)) /// /// public static class Imap { /// Creates an IMAP consumer endpoint for the given mail server. public static MailBuilder Read(string server) => new("imap", server); } /// /// Fluent API for POP3 (receive email) endpoints. /// /// .From(Pop3.Read("pop3.example.com").Port(995).Security("Ssl") /// .Username("inbox@example.com").Password("secret")) /// /// public static class Pop3 { /// Creates a POP3 consumer endpoint for the given mail server. public static MailBuilder Read(string server) => new("pop3", server); } /// /// Fluent builder for Mail endpoint URIs (SMTP/IMAP/POP3). /// public sealed class MailBuilder { private readonly string _scheme; private readonly string _server; // Connection private int? _port; private string? _security; private int? _connectionTimeout; private int? _timeout; private string? _username; private string? _password; private string? _connectionFactory; private string? _accessToken; private string? _authMechanism; private bool _trustAllCertificates; private string? _clientCertPath; private string? _clientCertPassword; // SMTP (producer) private string? _from; private string? _to; private string? _cc; private string? _bcc; private string? _replyTo; private string? _subject; private string? _contentType; private bool _alternativeBody; private string? _attachments; // IMAP/POP3 (consumer) private string? _folder; private string? _additionalFolders; private int? _delay; private int? _initialDelay; private string? _fetchFilter; private int? _maxMessages; private string? _postProcess; private string? _moveTo; private bool? _delete; private string? _copyTo; private string? _sortBy; private bool _idle; private int? _idleTimeout; private bool? _fetchBody; private bool? _fetchAttachments; private long? _maxAttachmentSize; private bool? _peek; private bool _idempotent; private string? _idempotentRepository; private bool? _idempotentRepositoryRemoveOnCommit; private readonly List> _searchTerm = []; private long? _minAge; private long? _maxAge; private string? _subjectFilter; private string? _fromFilter; private bool _mapMimeHeaders; private bool _keepRawMessage; private bool _disconnect; internal MailBuilder(string scheme, string server) { ArgumentException.ThrowIfNullOrWhiteSpace(server); _scheme = scheme; _server = server; } // ── Connection ──────────────────────────────────────────────────── /// Server port. Auto-detected if 0. public MailBuilder Port(int port) { _port = port; return this; } /// Security mode: None, Ssl, StartTls, Auto. public MailBuilder Security(string mode) { _security = mode; return this; } /// Connection timeout in milliseconds. Default 30000. public MailBuilder ConnectionTimeout(int ms) { _connectionTimeout = ms; return this; } /// Operation timeout in milliseconds. Default 60000. public MailBuilder Timeout(int ms) { _timeout = ms; return this; } /// Username for authentication. public MailBuilder Username(string username) { _username = username; return this; } /// Password for authentication. public MailBuilder Password(string password) { _password = password; return this; } /// /// References a named from the route registry instead of /// putting mailbox credentials in the URI. /// public MailBuilder ConnectionFactory(string name) { _connectionFactory = name; return this; } /// OAuth2/Bearer access token. public MailBuilder AccessToken(string token) { _accessToken = token; return this; } /// Auth mechanism: Auto, Plain, Login, CramMd5, XOAuth2, OAuthBearer, Ntlm. public MailBuilder AuthMechanism(string mechanism) { _authMechanism = mechanism; return this; } /// Skip SSL certificate validation. public MailBuilder TrustAllCertificates() { _trustAllCertificates = true; return this; } /// Client certificate for mutual TLS. public MailBuilder ClientCert(string path, string? password = null) { _clientCertPath = path; _clientCertPassword = password; return this; } // ── SMTP (producer) ─────────────────────────────────────────────── /// From address. public MailBuilder From(string address) { _from = address; return this; } /// From address from an expression. public MailBuilder From(IExpression address) { _from = address.ToTemplateString(); return this; } /// To address(es), comma-separated. public MailBuilder To(string addresses) { _to = addresses; return this; } /// To address(es) from an expression. public MailBuilder To(IExpression addresses) { _to = addresses.ToTemplateString(); return this; } /// CC address(es), comma-separated. public MailBuilder Cc(string addresses) { _cc = addresses; return this; } /// CC address(es) from an expression. public MailBuilder Cc(IExpression addresses) { _cc = addresses.ToTemplateString(); return this; } /// BCC address(es), comma-separated. public MailBuilder Bcc(string addresses) { _bcc = addresses; return this; } /// BCC address(es) from an expression. public MailBuilder Bcc(IExpression addresses) { _bcc = addresses.ToTemplateString(); return this; } /// Reply-To address. public MailBuilder ReplyTo(string address) { _replyTo = address; return this; } /// Reply-To address from an expression. public MailBuilder ReplyTo(IExpression address) { _replyTo = address.ToTemplateString(); return this; } /// Email subject. public MailBuilder Subject(string subject) { _subject = subject; return this; } /// Email subject from an expression. public MailBuilder Subject(IExpression subject) { _subject = subject.ToTemplateString(); return this; } /// Content type. Default "text/plain". public MailBuilder ContentType(string type) { _contentType = type; return this; } /// Content type from an expression. public MailBuilder ContentType(IExpression type) { _contentType = type.ToTemplateString(); return this; } /// Send body as alternative (e.g. HTML alternative to plain text). public MailBuilder AlternativeBody() { _alternativeBody = true; return this; } /// Attachment file paths, comma-separated. public MailBuilder Attachments(string paths) { _attachments = paths; return this; } // ── IMAP/POP3 (consumer) ────────────────────────────────────────── /// Mailbox folder. Default "INBOX". public MailBuilder Folder(string folder) { _folder = folder; return this; } /// Additional IMAP folders to monitor, comma-separated. public MailBuilder AdditionalFolders(string folders) { _additionalFolders = folders; return this; } /// Poll delay in milliseconds. Default 60000. public MailBuilder Delay(int ms) { _delay = ms; return this; } /// Initial delay before first poll. Default 0. public MailBuilder InitialDelay(int ms) { _initialDelay = ms; return this; } /// Fetch filter: Unseen, All, Recent, Flagged, Answered, Unanswered. public MailBuilder FetchFilter(string filter) { _fetchFilter = filter; return this; } /// Shortcut for FetchFilter("Unseen"). public MailBuilder Unseen() { _fetchFilter = "Unseen"; return this; } /// Max messages per poll. Default 50. public MailBuilder MaxMessages(int max) { _maxMessages = max; return this; } /// Post-processing: None, MarkRead, Delete, Move, MarkReadAndMove, Flag. public MailBuilder PostProcess(string action) { _postProcess = action; return this; } /// Move processed messages to this folder (IMAP). public MailBuilder MoveTo(string folder) { _moveTo = folder; return this; } /// Apache Camel's delete: delete a message whose exchange succeeded (moved to MoveTo first when set). public MailBuilder Delete(bool delete = true) { _delete = delete; return this; } /// Apache Camel's copyTo: the IMAP folder a successful message is copied to first. public MailBuilder CopyTo(string folder) { _copyTo = folder; return this; } /// Sort order: None, DateAsc, DateDesc, SubjectAsc, FromAsc, SizeAsc, SizeDesc. public MailBuilder SortBy(string sort) { _sortBy = sort; return this; } /// Use IMAP IDLE for push notifications instead of polling. public MailBuilder Idle(int? timeoutMs = null) { _idle = true; _idleTimeout = timeoutMs; return this; } /// Fetch message body. Default true. public MailBuilder FetchBody(bool fetch = true) { _fetchBody = fetch; return this; } /// Fetch message attachments. Default true. public MailBuilder FetchAttachments(bool fetch = true) { _fetchAttachments = fetch; return this; } /// Max attachment size in bytes. 0 = unlimited. public MailBuilder MaxAttachmentSize(long bytes) { _maxAttachmentSize = bytes; return this; } /// Peek at messages without marking them read at fetch (IMAP); the default. public MailBuilder Peek() { _peek = true; return this; } /// /// false marks each IMAP message read when it is fetched, so one whose exchange fails stays read and is not /// fetched again; true (the default) leaves it unseen until the commit. /// public MailBuilder Peek(bool peek) { _peek = peek; return this; } /// Enable idempotent consumer (skip already-processed messages). public MailBuilder Idempotent() { _idempotent = true; return this; } /// Apache Camel's idempotentRepository: the registered IIdempotentRepository that keeps the message keys. public MailBuilder IdempotentRepository(string name) { _idempotentRepository = name; return this; } /// Whether a committed message is removed from the repository (true, the default) or confirmed. public MailBuilder IdempotentRepositoryRemoveOnCommit(bool remove) { _idempotentRepositoryRemoveOnCommit = remove; return this; } /// /// Apache Camel's searchTerm=#name: a MailKit SearchQuery registered under , /// sent to the IMAP server as it is. /// public MailBuilder SearchTerm(string reference) { _searchTerm.Add(new("searchTerm", reference)); return this; } /// /// Apache Camel's searchTerm.* options (): .SearchTerm(t => t.Subject("invoice").FromSentDate("now-24h")) /// writes searchTerm.subject=invoice&searchTerm.fromSentDate=now-24h. /// public MailBuilder SearchTerm(Action configure) { ArgumentNullException.ThrowIfNull(configure); var builder = new MailSearchTermBuilder(); configure(builder); _searchTerm.AddRange(builder.Terms); return this; } /// Minimum message age in milliseconds. public MailBuilder MinAge(long ms) { _minAge = ms; return this; } /// Maximum message age in milliseconds. public MailBuilder MaxAge(long ms) { _maxAge = ms; return this; } /// Filter messages by subject (contains). public MailBuilder SubjectFilter(string filter) { _subjectFilter = filter; return this; } /// Filter messages by sender (contains). public MailBuilder FromFilter(string filter) { _fromFilter = filter; return this; } /// Map MIME headers to exchange headers. public MailBuilder MapMimeHeaders() { _mapMimeHeaders = true; return this; } /// Keep the raw MIME message in the exchange. public MailBuilder KeepRawMessage() { _keepRawMessage = true; return this; } /// Disconnect after each operation. public MailBuilder Disconnect() { _disconnect = true; return this; } // ── Build ───────────────────────────────────────────────────────── /// Builds the Mail endpoint URI string. public string Build() { var sb = new StringBuilder(); sb.Append(_scheme); sb.Append(':'); sb.Append(_server); var sep = '?'; void Append(string key, string value) { sb.Append(sep); sb.Append(key); sb.Append('='); sb.Append(Uri.EscapeDataString(value)); sep = '&'; } void AppendIf(string key, string? value) { if (!string.IsNullOrEmpty(value)) Append(key, value); } void AppendBool(string key, bool value) { if (value) Append(key, "true"); } void AppendBoolExplicit(string key, bool? value) { if (value.HasValue) Append(key, value.Value.ToString().ToLowerInvariant()); } void AppendInt(string key, int? value) { if (value.HasValue) Append(key, value.Value.ToString()); } void AppendLong(string key, long? value) { if (value.HasValue) Append(key, value.Value.ToString()); } // Connection AppendInt("port", _port); AppendIf("security", _security); AppendInt("connectionTimeout", _connectionTimeout); AppendInt("timeout", _timeout); AppendIf("username", _username); AppendIf("password", _password); AppendIf("connectionFactory", _connectionFactory); AppendIf("accessToken", _accessToken); AppendIf("authMechanism", _authMechanism); AppendBool("trustAllCertificates", _trustAllCertificates); AppendIf("clientCertPath", _clientCertPath); AppendIf("clientCertPassword", _clientCertPassword); // SMTP AppendIf("from", _from); AppendIf("to", _to); AppendIf("cc", _cc); AppendIf("bcc", _bcc); AppendIf("replyTo", _replyTo); AppendIf("subject", _subject); AppendIf("contentType", _contentType); AppendBool("alternativeBody", _alternativeBody); AppendIf("attachments", _attachments); // IMAP/POP3 AppendIf("folder", _folder); AppendIf("additionalFolders", _additionalFolders); AppendInt("delay", _delay); AppendInt("initialDelay", _initialDelay); AppendIf("fetchFilter", _fetchFilter); AppendInt("maxMessages", _maxMessages); AppendIf("postProcess", _postProcess); AppendIf("moveTo", _moveTo); AppendBoolExplicit("delete", _delete); AppendIf("copyTo", _copyTo); AppendIf("sortBy", _sortBy); AppendBool("idle", _idle); AppendInt("idleTimeout", _idleTimeout); AppendBoolExplicit("fetchBody", _fetchBody); AppendBoolExplicit("fetchAttachments", _fetchAttachments); AppendLong("maxAttachmentSize", _maxAttachmentSize); AppendBoolExplicit("peek", _peek); AppendBool("idempotent", _idempotent); AppendIf("idempotentRepository", _idempotentRepository); AppendBoolExplicit("idempotentRepositoryRemoveOnCommit", _idempotentRepositoryRemoveOnCommit); foreach (var (key, value) in _searchTerm) Append(key, value); AppendLong("minAge", _minAge); AppendLong("maxAge", _maxAge); AppendIf("subjectFilter", _subjectFilter); AppendIf("fromFilter", _fromFilter); AppendBool("mapMimeHeaders", _mapMimeHeaders); AppendBool("keepRawMessage", _keepRawMessage); AppendBool("disconnect", _disconnect); return sb.ToString(); } /// Implicit conversion to URI string. public static implicit operator string(MailBuilder b) => b.Build(); /// public override string ToString() => Build(); } /// The searchTerm.* options of a mail consumer (), in Apache Camel's names. public sealed class MailSearchTermBuilder { internal List> Terms { get; } = []; private MailSearchTermBuilder Set(string member, string value) { Terms.Add(new("searchTerm." + member, value)); return this; } /// Only unseen mails (default true); false takes the seen ones too. public MailSearchTermBuilder Unseen(bool unseen = true) => Set("unseen", unseen ? "true" : "false"); /// Text the subject or the body contains. public MailSearchTermBuilder SubjectOrBody(string text) => Set("subjectOrBody", text); /// Text the subject contains. public MailSearchTermBuilder Subject(string text) => Set("subject", text); /// Text the body contains. public MailSearchTermBuilder Body(string text) => Set("body", text); /// Text the From address contains. public MailSearchTermBuilder From(string text) => Set("from", text); /// Text a To address contains. public MailSearchTermBuilder To(string text) => Set("to", text); /// Sent at or after: yyyy-MM-dd HH:mm:ss or now with an offset (now-24h). public MailSearchTermBuilder FromSentDate(string date) => Set("fromSentDate", date); /// Sent at or before: yyyy-MM-dd HH:mm:ss or now with an offset. public MailSearchTermBuilder ToSentDate(string date) => Set("toSentDate", date); /// Received at or after (IMAP): yyyy-MM-dd HH:mm:ss or now with an offset. public MailSearchTermBuilder FromReceivedDate(string date) => Set("fromReceivedDate", date); /// Received at or before (IMAP): yyyy-MM-dd HH:mm:ss or now with an offset. public MailSearchTermBuilder ToReceivedDate(string date) => Set("toReceivedDate", date); } Path: redb-route/redb.Route.Mail/ImapComponent.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/ImapComponent.cs ---- using System.Diagnostics; using System.Text.RegularExpressions; using MailKit; using MailKit.Net.Imap; using MailKit.Search; using Microsoft.Extensions.Logging; using MimeKit; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Extensions; using redb.Route.Telemetry; namespace redb.Route.Mail; /// /// IMAP component. Scheme: "imap". /// Provides email consumption via IMAP using MailKit. /// Supports both polling and IDLE push modes. /// URI: imap://mail.example.com:993?username=inbox@ex.com&password=xxx&folder=INBOX&unseen=true /// [EndpointRole(EndpointRole.Consumer, Hint = "Use smtp: to send mail.")] public class ImapComponent : ComponentBase { /// public override string Scheme => "imap"; /// public override IEndpoint CreateEndpoint(EndpointUri uri) { ArgumentNullException.ThrowIfNull(uri); var options = new MailEndpointOptions(); if (!string.IsNullOrEmpty(uri.Path) && uri.Path != "/") options.Host = uri.Path.TrimStart('/'); options.BindFromUri(uri.RawParameters); MailEndpointOptions.RefuseOtherSide(uri, Scheme, EndpointRole.Consumer); MailConnectionFactory.TryApply(Context, options, uri, Logger, "IMAP"); options.Validate(EndpointRole.Consumer); return new ImapEndpoint(uri, this, options); } } /// /// IMAP endpoint. Creates an ImapConsumer for receiving email. /// public class ImapEndpoint : EndpointBase { /// Creates an IMAP endpoint. public ImapEndpoint(EndpointUri uri, ImapComponent component, MailEndpointOptions options) : base(uri, component, options) { } /// The mail server host. public string Host => Options.Host; /// The resolved port number. public int Port => Options.ResolvePort("imap"); /// Endpoint options for external access. internal MailEndpointOptions EndpointOptions => Options; /// public override IProducer CreateProducer() => throw new NotSupportedException("IMAP does not support producing. Use smtp: scheme instead."); /// public override IConsumer CreateConsumer(IProcessor processor) { ArgumentNullException.ThrowIfNull(processor); return new ImapConsumer(this, processor, Options); } } /// /// IMAP consumer — fetches email messages via MailKit ImapClient. /// Supports polling mode and IMAP IDLE push mode. /// Full support for filtering, sorting, post-processing (mark read, delete, move), /// attachments, idempotency, and OAuth2. /// public class ImapConsumer : DrainableConsumer { private readonly ImapEndpoint _endpoint; private readonly MailEndpointOptions _options; private MailIdempotency? _idempotency; private readonly Regex? _subjectRegex; private readonly HashSet? _fromFilter; private long _processedCount; private SearchQuery? _registryQuery; /// protected override IEndpoint ConsumerEndpoint => _endpoint; /// protected override string ConsumerName => "imap"; /// Creates an IMAP consumer. public ImapConsumer(ImapEndpoint endpoint, IProcessor processor, MailEndpointOptions options) : base(processor) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _options = options ?? throw new ArgumentNullException(nameof(options)); if (!string.IsNullOrWhiteSpace(options.SubjectFilter)) _subjectRegex = new Regex(options.SubjectFilter, RegexOptions.IgnoreCase | RegexOptions.Compiled); if (!string.IsNullOrWhiteSpace(options.FromFilter)) _fromFilter = new HashSet( options.FromFilter.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries), StringComparer.OrdinalIgnoreCase); } /// Number of messages successfully processed. public long ProcessedCount => Interlocked.Read(ref _processedCount); /// protected override Task OnStarting(CancellationToken ct) { // The repository is looked up when the consumer starts, so a name nothing is registered under stops the route. _idempotency = MailIdempotency.Create(_options, _endpoint); // searchTerm=#name: the registry's MailKit search query, looked up at start so a missing name stops the route. if (_options.SearchTerm is { HasReference: true } term) { var context = (_endpoint.Component as ComponentBase)?.Context ?? throw new InvalidOperationException($"searchTerm '{term.Reference}' needs a route context to look it up."); _registryQuery = context.GetRequiredFromRegistry(term.Reference!); } return Task.CompletedTask; } /// protected override Task RunAsync(CancellationToken pollCt, CancellationToken processingCt) { return _options.Idle ? IdleLoop(pollCt, processingCt) : PollLoop(pollCt, processingCt); } // ── Polling mode ────────────────────────────────────────────────── private async Task PollLoop(CancellationToken pollCt, CancellationToken processingCt) { if (_options.InitialDelay > 0) await Task.Delay(_options.InitialDelay, pollCt).ConfigureAwait(false); var delay = TimeSpan.FromMilliseconds(_options.Delay); while (!pollCt.IsCancellationRequested) { try { using var client = await ConnectAsync(processingCt).ConfigureAwait(false); await FetchAndProcessAsync(client, processingCt).ConfigureAwait(false); if (!_options.Disconnect) await client.DisconnectAsync(quit: true, processingCt).ConfigureAwait(false); } catch (OperationCanceledException) when (pollCt.IsCancellationRequested || processingCt.IsCancellationRequested) { break; } catch (Exception ex) { Logger?.LogWarning(ex, "IMAP poll failed, retrying on next cycle"); } try { await Task.Delay(delay, pollCt).ConfigureAwait(false); } catch (OperationCanceledException) { break; } } } // ── IDLE mode ───────────────────────────────────────────────────── private async Task IdleLoop(CancellationToken pollCt, CancellationToken processingCt) { if (_options.InitialDelay > 0) await Task.Delay(_options.InitialDelay, pollCt).ConfigureAwait(false); while (!pollCt.IsCancellationRequested) { try { using var client = await ConnectAsync(processingCt).ConfigureAwait(false); var folder = await OpenFolderAsync(client, processingCt).ConfigureAwait(false); // Initial fetch await FetchFromFolderAsync(client, folder, processingCt).ConfigureAwait(false); // IDLE loop — wait for notifications while (!pollCt.IsCancellationRequested) { using var idleCts = CancellationTokenSource.CreateLinkedTokenSource(pollCt); idleCts.CancelAfter(_options.IdleTimeout); try { await client.IdleAsync(idleCts.Token).ConfigureAwait(false); } catch (OperationCanceledException) when (!pollCt.IsCancellationRequested) { // IDLE timeout expired — refetch and re-IDLE (RFC 2177 recommendation) } // Re-fetch after IDLE notification or timeout if (!pollCt.IsCancellationRequested) await FetchFromFolderAsync(client, folder, processingCt).ConfigureAwait(false); } } catch (OperationCanceledException) when (pollCt.IsCancellationRequested || processingCt.IsCancellationRequested) { break; } catch { // Connection lost — wait and reconnect try { await Task.Delay(5000, pollCt).ConfigureAwait(false); } catch (OperationCanceledException) { break; } } } } // ── Fetch & process ─────────────────────────────────────────────── private async Task FetchAndProcessAsync(ImapClient client, CancellationToken ct) { var folders = GetFolderNames(); foreach (var folderName in folders) { var folder = await client.GetFolderAsync(folderName, ct).ConfigureAwait(false); await folder.OpenAsync(FolderAccess.ReadWrite, ct).ConfigureAwait(false); await FetchFromFolderAsync(client, folder, ct).ConfigureAwait(false); await folder.CloseAsync(expunge: false, ct).ConfigureAwait(false); } } private async Task FetchFromFolderAsync(ImapClient client, IMailFolder folder, CancellationToken ct) { var now = DateTimeOffset.Now; var query = BuildSearchQuery(now); IList uids = await folder.SearchAsync(query, ct).ConfigureAwait(false); // IMAP SEARCH compares dates by whole days: the date bounds of searchTerm are checked here against the exact time, // before maxMessages counts, from the envelope's Date and the arrival time (INTERNALDATE) in one FETCH. if (_registryQuery is null && _options.SearchTerm is { HasDateBounds: true } term && uids.Count > 0) { var summaries = await folder.FetchAsync(uids, MessageSummaryItems.UniqueId | MessageSummaryItems.Envelope | MessageSummaryItems.InternalDate, ct).ConfigureAwait(false); uids = summaries .Where(s => term.MatchesDates(s.Envelope?.Date, s.InternalDate, now)) .Select(s => s.UniqueId) .ToList(); } if (uids.Count == 0) return; // Apply MaxMessages var toFetch = _options.MaxMessages > 0 && uids.Count > _options.MaxMessages ? uids.Take(_options.MaxMessages).ToList() : uids.ToList(); // Sort if requested if (_options.SortBy != MailSortBy.None && toFetch.Count > 1) toFetch = await SortUidsAsync(folder, toFetch, ct).ConfigureAwait(false); foreach (var uid in toFetch) { if (ct.IsCancellationRequested) break; MimeMessage mime; if (!_options.FetchBody) { // fetchBody=false: envelope scanning - only the headers travel from the server. // MimeKit keeps address/subject/date properties in sync with the header list, so // filters, idempotency and the exchange headers all work; the body stays empty. // (A dead option before the options sweep.) var headerList = await folder.GetHeadersAsync(uid, ct).ConfigureAwait(false); mime = MailMessageHelper.FromHeadersOnly(headerList); } else { mime = await folder.GetMessageAsync(uid, ct, progress: null).ConfigureAwait(false); } // Client-side filters if (!PassesFilters(mime)) continue; // Age filters if (!PassesAgeFilter(mime)) continue; // Idempotency, after the filters: a message they hold back is not taken. The key is the Message-ID, else // the folder, UIDVALIDITY and UID, which name one message for as long as the folder keeps its UIDVALIDITY. string? key = null; if (_idempotency is not null) { key = !string.IsNullOrEmpty(mime.MessageId) ? mime.MessageId : $"{folder.FullName}/{folder.UidValidity}/{uid.Id}"; if (!await _idempotency.TryAdd(key, ct).ConfigureAwait(false)) continue; } var exchange = MailMessageHelper.CreateExchange(mime, "imap", folder.FullName, uid, scopeFactory: _endpoint.ScopeFactory, options: _options); if (_options.KeepRawMessage) exchange.Properties["RawMimeMessage"] = mime; using var span = StartConsumerSpan(mime, folder.FullName); // peek=false (Apache Camel's): the message is marked read as it is fetched for the route, so one whose // exchange fails stays read; the fetch itself always peeks. if (!_options.Peek) await folder.AddFlagsAsync(uid, MessageFlags.Seen, silent: true, ct).ConfigureAwait(false); IncrementInflight(); try { try { await Processor.Process(exchange, ct).ConfigureAwait(false); } catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; // our own stop: end the fetch, the message is not a failure } catch (Exception ex) { // A failure that escaped the route is one failed message: it is left as it is and the fetch goes // on, so a message that fails on every attempt does not hold up the messages after it. span.Activity.RecordFailure(ex); Logger?.LogError(ex, "IMAP: the route failed for message {Uid} in {Folder}; the message is left as it is", uid, folder.FullName); if (key is not null) await _idempotency!.Rollback(key, ct).ConfigureAwait(false); continue; } if (exchange.Exception is { } failure && !exchange.ExceptionHandled && (failure is not OperationCanceledException || !ct.IsCancellationRequested)) span.Activity.RecordFailure(failure); // Apache Camel's rollback: a failed exchange (an unhandled exception, or rollback-only) leaves the // message as it is; only a successful one is committed. if (exchange.EndedInFailure()) { Logger?.LogWarning(exchange.ExceptionHandled ? null : exchange.Exception, "IMAP: the exchange for message {Uid} in {Folder} failed; the message is left as it is", uid, folder.FullName); if (key is not null) await _idempotency!.Rollback(key, ct).ConfigureAwait(false); continue; } Interlocked.Increment(ref _processedCount); await PostProcessAsync(folder, uid, client, exchange.HasOut ? exchange.Out! : exchange.In, ct).ConfigureAwait(false); if (key is not null) await _idempotency!.Commit(key, ct).ConfigureAwait(false); } finally { DecrementInflight(); await exchange.DisposeAsync().ConfigureAwait(false); } } } /// /// Commits a message whose exchange succeeded, the way Apache Camel's mail consumer does. The copy /// (, else ) is taken first. Then, when /// , or /// is set, the message is deleted (moved first when a folder is given) or marked read (and moved), the headers /// on the message the route ended with winning over the options. Otherwise /// applies. /// private async Task PostProcessAsync(IMailFolder folder, UniqueId uid, ImapClient client, IMessage result, CancellationToken ct) { var copyHeader = result.GetHeader(MailHeaders.CopyTo); var copyTo = !string.IsNullOrWhiteSpace(copyHeader) ? copyHeader : _options.CopyTo; if (!string.IsNullOrWhiteSpace(copyTo)) { var copyTarget = await GetOrCreateFolderAsync(client, copyTo, ct).ConfigureAwait(false); await folder.CopyToAsync(uid, copyTarget, ct).ConfigureAwait(false); } var deleteHeader = result.Headers.ContainsKey(MailHeaders.Delete) ? result.GetHeader(MailHeaders.Delete) : (bool?)null; var moveHeader = result.GetHeader(MailHeaders.MoveTo); if (deleteHeader is not null || !string.IsNullOrWhiteSpace(moveHeader) || _options.Delete) { var delete = deleteHeader ?? (_options.Delete || _options.PostProcess == PostProcessAction.Delete); var moveTo = !string.IsNullOrWhiteSpace(moveHeader) ? moveHeader : _options.Delete || _options.PostProcess is PostProcessAction.Move or PostProcessAction.MarkReadAndMove ? _options.MoveTo : null; await CommitAsync(folder, uid, client, delete, moveTo, ct).ConfigureAwait(false); return; } switch (_options.PostProcess) { case PostProcessAction.MarkRead: await folder.AddFlagsAsync(uid, MessageFlags.Seen, silent: true, ct).ConfigureAwait(false); break; case PostProcessAction.Delete: await folder.AddFlagsAsync(uid, MessageFlags.Deleted, silent: true, ct).ConfigureAwait(false); await folder.ExpungeAsync(ct).ConfigureAwait(false); break; case PostProcessAction.Move: var targetFolder = await GetOrCreateFolderAsync(client, _options.MoveTo, ct).ConfigureAwait(false); await folder.MoveToAsync(uid, targetFolder, ct).ConfigureAwait(false); break; case PostProcessAction.MarkReadAndMove: await folder.AddFlagsAsync(uid, MessageFlags.Seen, silent: true, ct).ConfigureAwait(false); var moveTarget = await GetOrCreateFolderAsync(client, _options.MoveTo, ct).ConfigureAwait(false); await folder.MoveToAsync(uid, moveTarget, ct).ConfigureAwait(false); break; case PostProcessAction.Flag: await folder.AddFlagsAsync(uid, MessageFlags.Flagged, silent: true, ct).ConfigureAwait(false); break; case PostProcessAction.None: default: break; } } /// Apache Camel's commit of a mail: deleted (moved first when a folder is given), or marked read and moved. private static async Task CommitAsync(IMailFolder folder, UniqueId uid, ImapClient client, bool delete, string? moveTo, CancellationToken ct) { if (!delete) await folder.AddFlagsAsync(uid, MessageFlags.Seen, silent: true, ct).ConfigureAwait(false); if (!string.IsNullOrWhiteSpace(moveTo)) { var target = await GetOrCreateFolderAsync(client, moveTo, ct).ConfigureAwait(false); await folder.MoveToAsync(uid, target, ct).ConfigureAwait(false); return; } if (delete) { await folder.AddFlagsAsync(uid, MessageFlags.Deleted, silent: true, ct).ConfigureAwait(false); await folder.ExpungeAsync(ct).ConfigureAwait(false); } } /// /// The folder a message is moved or copied to, created (with the folders above it) when the mailbox does not have /// it yet, as Apache Camel's mail consumer creates a missing moveTo / copyTo folder. The path is the /// folder's full name, its levels split by the server's separator, under the personal namespace. /// private static async Task GetOrCreateFolderAsync(ImapClient client, string path, CancellationToken ct) { try { return await client.GetFolderAsync(path, ct).ConfigureAwait(false); } catch (FolderNotFoundException) { } var parent = client.PersonalNamespaces.Count > 0 ? client.GetFolder(client.PersonalNamespaces[0]) : client.GetFolder(new FolderNamespace(client.Inbox.DirectorySeparator, "")); foreach (var level in path.Split(parent.DirectorySeparator, StringSplitOptions.RemoveEmptyEntries)) { try { parent = await parent.GetSubfolderAsync(level, ct).ConfigureAwait(false); } catch (FolderNotFoundException) { parent = await parent.CreateAsync(level, isMessageFolder: true, ct).ConfigureAwait(false); } } return parent; } // ── Search query builder ────────────────────────────────────────── // Camel's order: the registry's search query (searchTerm=#name) as it is, else the searchTerm options, else the fetch // filter. A set searchTerm replaces the fetch filter (setting both is refused at start). private SearchQuery BuildSearchQuery(DateTimeOffset now) => _registryQuery ?? _options.SearchTerm?.ToImapQuery(now) ?? BuildFetchFilterQuery(); private SearchQuery BuildFetchFilterQuery() { return _options.FetchFilter switch { MailFetchFilter.Unseen => SearchQuery.NotSeen, MailFetchFilter.All => SearchQuery.All, MailFetchFilter.Recent => SearchQuery.Recent, MailFetchFilter.Flagged => SearchQuery.Flagged, MailFetchFilter.Answered => SearchQuery.Answered, MailFetchFilter.Unanswered => SearchQuery.Not(SearchQuery.Answered), _ => SearchQuery.NotSeen }; } // ── Sorting ─────────────────────────────────────────────────────── private async Task> SortUidsAsync(IMailFolder folder, List uids, CancellationToken ct) { try { var orderBy = _options.SortBy switch { MailSortBy.DateAsc => new[] { OrderBy.Date }, MailSortBy.DateDesc => new[] { OrderBy.ReverseDate }, MailSortBy.SubjectAsc => new[] { OrderBy.Subject }, MailSortBy.FromAsc => new[] { OrderBy.From }, MailSortBy.SizeAsc => new[] { OrderBy.Size }, MailSortBy.SizeDesc => new[] { OrderBy.ReverseSize }, _ => Array.Empty() }; if (orderBy.Length > 0) { var sorted = await folder.SortAsync(SearchQuery.All, orderBy, ct).ConfigureAwait(false); return sorted.Where(uids.Contains).ToList(); } } catch (NotSupportedException) { /* server doesn't support SORT */ } return uids; } // ── Client-side filters ─────────────────────────────────────────── private bool PassesFilters(MimeMessage mime) { if (_subjectRegex is not null && !_subjectRegex.IsMatch(mime.Subject ?? "")) return false; if (_fromFilter is not null && mime.From.Mailboxes.All(mb => !_fromFilter.Contains(mb.Address))) return false; return true; } private bool PassesAgeFilter(MimeMessage mime) { if (_options.MinAge <= 0 && _options.MaxAge <= 0) return true; var messageDate = mime.Date.UtcDateTime; if (messageDate == default) return true; var age = DateTimeOffset.UtcNow - messageDate; if (_options.MinAge > 0 && age.TotalMilliseconds < _options.MinAge) return false; if (_options.MaxAge > 0 && age.TotalMilliseconds > _options.MaxAge) return false; return true; } // ── Connection helpers ──────────────────────────────────────────── private async Task ConnectAsync(CancellationToken ct) { var client = new ImapClient(); 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); return client; } private async Task OpenFolderAsync(ImapClient client, CancellationToken ct) { var folder = await client.GetFolderAsync(_options.Folder, ct).ConfigureAwait(false); await folder.OpenAsync(FolderAccess.ReadWrite, ct).ConfigureAwait(false); return folder; } private async Task AuthenticateAsync(ImapClient 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 string[] GetFolderNames() { var folders = new List { _options.Folder }; if (!string.IsNullOrWhiteSpace(_options.AdditionalFolders)) { folders.AddRange(_options.AdditionalFolders.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)); } return folders.ToArray(); } /// /// The span of one message. A mailbox message carries no trace context the connector reads, so the span is a root, /// never a child of the activity the poll loop holds. /// private TransportSpan StartConsumerSpan(MimeMessage mime, string folder) { var span = RouteTelemetryExtensions.StartConsumerSpan( (_endpoint.Component as ComponentBase)?.Context, $"{_endpoint.Host} receive", ActivityKind.Consumer, "messaging.system", "imap", _endpoint.Uri.NormalizedKey, null, static (_, _) => null, destination: _endpoint.Host, operation: "receive"); if (span.Activity is { IsAllDataRequested: true } activity) { activity.SetTag("messaging.imap.folder", folder); if (!string.IsNullOrEmpty(mime.MessageId)) activity.SetTag("messaging.message.id", mime.MessageId); if (!string.IsNullOrEmpty(mime.Subject)) activity.SetTag("messaging.imap.subject", mime.Subject); } return span; } } Path: redb-route/redb.Route.Mail/MailConnectionFactory.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/MailConnectionFactory.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Extensions; using redb.Route.Core; namespace redb.Route.Mail; /// /// Named connection factory for mail transports (SMTP, IMAP, POP3). Register it in the route /// registry and reference it by name from the endpoint URI (connectionFactory=my-mailbox) /// so mailbox credentials never have to appear in the URI, and therefore can never reach logs, /// telemetry, or the Tsak dashboard. One factory serves all three protocols. /// /// Example: /// /// context.AddToRegistry("corp-mailbox", new MailConnectionFactory /// { /// Host = "mail.corp.local", /// Port = 993, /// Security = MailSecurityMode.SslOnConnect, /// Username = "svc-reports", /// Password = Environment.GetEnvironmentVariable("MAIL_PASSWORD")! /// }); /// /// // route carries no credentials at all: /// r.From("imap://?connectionFactory=corp-mailbox&folder=INBOX") /// /// /// public sealed class MailConnectionFactory { // ── Connection ── /// Mail server hostname or IP. public string Host { get; set; } = "localhost"; /// Server port (0 = protocol default for the chosen security mode). public int Port { get; set; } /// Transport security mode (Auto, None, SslOnConnect, StartTls…). public MailSecurityMode Security { get; set; } = MailSecurityMode.Auto; /// Connection timeout in milliseconds. public int ConnectionTimeout { get; set; } = 30_000; /// Operation timeout in milliseconds. public int Timeout { get; set; } = 60_000; // ── Auth ── /// Mailbox username. public string Username { get; set; } = ""; /// Mailbox password. [Sensitive] public string Password { get; set; } = ""; /// OAuth2 access token (used instead of the password when set). [Sensitive] public string AccessToken { get; set; } = ""; /// Authentication mechanism. public MailAuthMechanism AuthMechanism { get; set; } = MailAuthMechanism.Auto; // ── TLS ── /// Skip server certificate validation (development only!). public bool TrustAllCertificates { get; set; } /// Path to the client certificate for mutual TLS. public string ClientCertPath { get; set; } = ""; /// Password for the client certificate. [Sensitive] public string ClientCertPassword { get; set; } = ""; /// /// Copies this factory's connection and credential settings onto the endpoint options, but only /// for parameters the endpoint URI did not set explicitly — an inline URI value always wins, /// so existing routes keep their behaviour. is additionally skipped when the /// URI path already carried the host (imap://mail.corp.local), so a factory can never /// silently redirect a route to a different server. /// internal void ApplyTo(MailEndpointOptions options, EndpointUri uri) { var supplied = uri.RawParameters; var hostFromPath = !string.IsNullOrEmpty(uri.Path) && uri.Path != "/"; if (!supplied.ContainsKey(nameof(options.Host)) && !hostFromPath) options.Host = Host; if (!supplied.ContainsKey(nameof(options.Port))) options.Port = Port; if (!supplied.ContainsKey(nameof(options.Security))) options.Security = Security; if (!supplied.ContainsKey(nameof(options.ConnectionTimeout))) options.ConnectionTimeout = ConnectionTimeout; if (!supplied.ContainsKey(nameof(options.Timeout))) options.Timeout = Timeout; if (!supplied.ContainsKey(nameof(options.Username))) options.Username = Username; if (!supplied.ContainsKey(nameof(options.Password))) options.Password = Password; if (!supplied.ContainsKey(nameof(options.AccessToken))) options.AccessToken = AccessToken; if (!supplied.ContainsKey(nameof(options.AuthMechanism))) options.AuthMechanism = AuthMechanism; if (!supplied.ContainsKey(nameof(options.TrustAllCertificates))) options.TrustAllCertificates = TrustAllCertificates; if (!supplied.ContainsKey(nameof(options.ClientCertPath))) options.ClientCertPath = ClientCertPath; if (!supplied.ContainsKey(nameof(options.ClientCertPassword))) options.ClientCertPassword = ClientCertPassword; } /// /// Shared resolution step for the SMTP / IMAP / POP3 components: looks the named factory up in /// the registry and applies it. Called after BindFromUri and before Validate(). /// internal static void TryApply( IRouteContext? context, MailEndpointOptions options, EndpointUri uri, ILogger? logger, string protocol) { if (string.IsNullOrEmpty(options.ConnectionFactory)) return; // A set-but-unknown name fails loud — never a silent fallback to URI params. var factory = context.GetRequiredFromRegistry(options.ConnectionFactory); factory.ApplyTo(options, uri); } } 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 }; } } Path: redb-route/redb.Route.Mail/MailEnums.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/MailEnums.cs ---- namespace redb.Route.Mail; /// Security mode for mail connections. public enum MailSecurityMode { /// No encryption (port 25/110/143). None, /// Implicit SSL/TLS — connect encrypted from the start (port 465/993/995). Ssl, /// Explicit STARTTLS — upgrade cleartext to TLS after connect (port 587/143/110). StartTls, /// Auto-detect based on port number. Auto } /// Authentication mechanism for mail connections. public enum MailAuthMechanism { /// Auto-select (let MailKit choose the best available). Auto, /// PLAIN (RFC 4616). Plain, /// LOGIN. Login, /// CRAM-MD5 (RFC 2195). CramMd5, /// XOAUTH2 (Google, Microsoft). XOAuth2, /// OAUTHBEARER (RFC 7628). OAuthBearer, /// NTLM (Windows Integrated). Ntlm } /// What to do with messages after processing (consumer). public enum PostProcessAction { /// Leave message untouched. None, /// Mark as read (IMAP: set \Seen flag). MarkRead, /// Delete the message. Delete, /// Move to another folder (IMAP only). Move, /// Mark as read and move to another folder (IMAP only). MarkReadAndMove, /// Flag the message (IMAP: set \Flagged). Flag } /// Sort order for fetched messages. public enum MailSortBy { /// No sorting (server order). None, /// Oldest first (by date). DateAsc, /// Newest first (by date). DateDesc, /// By subject ascending. SubjectAsc, /// By sender ascending. FromAsc, /// By size ascending. SizeAsc, /// By size descending. SizeDesc } /// IMAP search filter for message selection. public enum MailFetchFilter { /// Only unseen (unread) messages. Unseen, /// All messages. All, /// Only recent messages (IMAP \Recent flag). Recent, /// Only flagged messages. Flagged, /// Only answered messages. Answered, /// Unanswered messages. Unanswered } Path: redb-route/redb.Route.Mail/MailHeaders.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/MailHeaders.cs ---- namespace redb.Route.Mail; /// /// Header constants for email messages in the redb.Route pipeline. /// All headers use the "redbMail." prefix. /// public static class MailHeaders { /// Header prefix for all mail-related headers. public const string Prefix = "redbMail."; // ── Addressing ──────────────────────────────────────────────────── /// Sender address (RFC 5322 From). public const string From = "redbMail.From"; /// Comma-separated recipient addresses (To). public const string To = "redbMail.To"; /// Comma-separated CC addresses. public const string Cc = "redbMail.Cc"; /// Comma-separated BCC addresses. public const string Bcc = "redbMail.Bcc"; /// Reply-To address. public const string ReplyTo = "redbMail.ReplyTo"; /// Sender (envelope sender, may differ from From). public const string Sender = "redbMail.Sender"; // ── Subject & identifiers ───────────────────────────────────────── /// Email subject line. public const string Subject = "redbMail.Subject"; /// Message-ID header (RFC 2822). public const string MessageId = "redbMail.MessageId"; /// In-Reply-To header (thread reference). public const string InReplyTo = "redbMail.InReplyTo"; /// References header (full thread chain). public const string References = "redbMail.References"; // ── Content ─────────────────────────────────────────────────────── /// MIME content type of the body (text/plain, text/html, multipart/mixed). public const string ContentType = "redbMail.ContentType"; /// Whether the email body is HTML. public const string IsHtml = "redbMail.IsHtml"; /// Plain text body (when multipart, the text/plain alternative). public const string TextBody = "redbMail.TextBody"; /// HTML body (when multipart, the text/html alternative). public const string HtmlBody = "redbMail.HtmlBody"; // ── Attachments ─────────────────────────────────────────────────── /// Number of attachments. public const string AttachmentCount = "redbMail.AttachmentCount"; /// Whether the message has attachments. public const string HasAttachments = "redbMail.HasAttachments"; /// Comma-separated attachment file names. public const string AttachmentNames = "redbMail.AttachmentNames"; // ── Date & timestamps ───────────────────────────────────────────── /// Date header from the email. public const string Date = "redbMail.Date"; /// Date the email was received (IMAP internal date). public const string ReceivedDate = "redbMail.ReceivedDate"; // ── Flags & metadata ────────────────────────────────────────────── /// IMAP message UID. public const string Uid = "redbMail.Uid"; /// IMAP/POP3 message index (sequence number). public const string Index = "redbMail.Index"; /// IMAP folder name where the message was found. public const string Folder = "redbMail.Folder"; /// IMAP message flags (Seen, Answered, Flagged, etc.). public const string Flags = "redbMail.Flags"; /// /// Prefix for raw MIME headers copied onto the exchange when mapMimeHeaders=true: /// redbMail.Mime.<Field> (e.g. redbMail.Mime.X-Custom-Track). /// public const string MimePrefix = "redbMail.Mime."; /// Message size in bytes. public const string Size = "redbMail.Size"; /// Message priority (Urgent, Normal, NonUrgent). public const string Priority = "redbMail.Priority"; // ── Commit of a consumed message (set by the route) ─────────────── /// /// Set by the route to override the endpoint at commit time (Apache Camel's CamelMailDelete): true /// deletes the message, false marks it read instead (IMAP) or keeps it on the server (POP3). Read from the /// message the route ended with, only when the exchange succeeded. /// public const string Delete = "redbMail.Delete"; /// /// Set by the route to move the consumed message to this IMAP folder at commit time (Apache Camel's /// CamelMailMoveTo); marked read first unless is true. Created when missing; /// POP3 ignores it. /// public const string MoveTo = "redbMail.MoveTo"; /// /// Set by the route to copy the consumed message to this IMAP folder at commit time, before anything else is done /// to it (Apache Camel's CamelMailCopyTo). Created when missing; POP3 ignores it. /// public const string CopyTo = "redbMail.CopyTo"; // ── Protocol info ───────────────────────────────────────────────── /// Protocol used to retrieve the message (imap, pop3). public const string Protocol = "redbMail.Protocol"; /// Whether the connection used TLS/SSL. public const string Secure = "redbMail.Secure"; /// /// Checks whether a header key belongs to the redbMail namespace. /// public static bool IsRedbHeader(string key) => key.StartsWith(Prefix, StringComparison.Ordinal); } Path: redb-route/redb.Route.Mail/MailIdempotency.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/MailIdempotency.cs ---- using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Mail; /// /// The idempotency of a mail consumer, as Apache Camel's mail consumer keeps it: a message's key is added to the /// repository before its route and the message is skipped when the repository already holds it; a failed exchange /// removes the key, so the message is routed again; a successful one confirms it, or removes it when /// says so. /// internal sealed class MailIdempotency { private readonly IIdempotentRepository _repository; private readonly bool _removeOnCommit; private MailIdempotency(IIdempotentRepository repository, bool removeOnCommit) { _repository = repository; _removeOnCommit = removeOnCommit; } /// /// The idempotency the options ask for: the registered , /// else the consumer's own in-memory set for , else none. /// public static MailIdempotency? Create(MailEndpointOptions options, IEndpoint endpoint) { if (!string.IsNullOrEmpty(options.IdempotentRepository)) { var context = (endpoint.Component as ComponentBase)?.Context ?? throw new InvalidOperationException( $"idempotentRepository '{options.IdempotentRepository}' needs a route context: register the " + "repository with context.AddIdempotentRepository(name, repository)."); return new MailIdempotency( context.GetIdempotentRepositoryProvider().Get(options.IdempotentRepository), options.IdempotentRepositoryRemoveOnCommit); } // idempotent=true: the messages this consumer routed successfully are skipped until it restarts. return options.Idempotent ? new MailIdempotency(new InMemoryIdempotentRepository(), removeOnCommit: false) : null; } /// Adds the key before the route; false when the repository already holds it (a duplicate). public Task TryAdd(string key, CancellationToken ct) => _repository.Add(key, ct); /// The exchange succeeded and the message is committed. public Task Commit(string key, CancellationToken ct) => _removeOnCommit ? _repository.Remove(key, ct) : _repository.Confirm(key, ct); /// The exchange failed and the message is left as it is: it may be routed again. public Task Rollback(string key, CancellationToken ct) => _repository.Remove(key, ct); } Path: redb-route/redb.Route.Mail/MailMessageHelper.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/MailMessageHelper.cs ---- using MailKit; using Microsoft.Extensions.DependencyInjection; using MimeKit; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Mail; /// /// Shared utility for converting MimeMessage to Exchange. /// Used by both ImapConsumer and Pop3Consumer. /// internal static class MailMessageHelper { /// /// Creates an Exchange from a MimeMessage, populating all MailHeaders and body/attachments. /// /// Source MIME message. /// Protocol name: "imap" or "pop3". /// Folder name (IMAP) or null (POP3). /// IMAP UniqueId or POP3 index. Pass default for POP3. /// Sequence index of the message. /// /// Builds a headers-only from a fetched header list by round-tripping /// it through the MIME parser — copying headers into a fresh message does NOT sync properties /// like Subject/From, the parser is the one construction path that does (fetchBody=false). /// internal static MimeMessage FromHeadersOnly(HeaderList headerList) { using var ms = new MemoryStream(); headerList.WriteTo(ms); ms.Write("\r\n"u8); // blank line: end of headers, empty body ms.Position = 0; var message = MimeMessage.Load(ms); message.Body = null; // headers-only: the parser materializes an empty text part otherwise return message; } public static Exchange CreateExchange( MimeMessage mime, string protocol, string? folder = null, UniqueId uid = default, int index = -1, IServiceScopeFactory? scopeFactory = null, MailEndpointOptions? options = null) { ArgumentNullException.ThrowIfNull(mime); var body = mime.HtmlBody ?? mime.TextBody ?? ""; var message = new Message(body); var headers = message.Headers; // ── Addressing ─────────────────────────────────────────────── SetIfNotEmpty(headers, MailHeaders.From, FormatAddresses(mime.From)); SetIfNotEmpty(headers, MailHeaders.To, FormatAddresses(mime.To)); SetIfNotEmpty(headers, MailHeaders.Cc, FormatAddresses(mime.Cc)); SetIfNotEmpty(headers, MailHeaders.Bcc, FormatAddresses(mime.Bcc)); SetIfNotEmpty(headers, MailHeaders.ReplyTo, FormatAddresses(mime.ReplyTo)); if (mime.Sender is not null) headers[MailHeaders.Sender] = mime.Sender.Address; // ── Subject & identifiers ──────────────────────────────────── SetIfNotEmpty(headers, MailHeaders.Subject, mime.Subject); SetIfNotEmpty(headers, MailHeaders.MessageId, mime.MessageId); SetIfNotEmpty(headers, MailHeaders.InReplyTo, mime.InReplyTo); if (mime.References.Count > 0) headers[MailHeaders.References] = string.Join(" ", mime.References); // ── Content ────────────────────────────────────────────────── headers[MailHeaders.IsHtml] = mime.HtmlBody is not null; if (mime.TextBody is not null) headers[MailHeaders.TextBody] = mime.TextBody; if (mime.HtmlBody is not null) headers[MailHeaders.HtmlBody] = mime.HtmlBody; if (mime.Body is not null) headers[MailHeaders.ContentType] = mime.Body.ContentType.MimeType; // ── Attachments ────────────────────────────────────────────── var attachments = mime.Attachments.ToList(); headers[MailHeaders.AttachmentCount] = attachments.Count; headers[MailHeaders.HasAttachments] = attachments.Count > 0; if (attachments.Count > 0) { var names = new List(); var mailAttachments = new List(); // fetchAttachments=false: the metadata (count, names) stays, the payload copies do // not. maxAttachmentSize caps the DECODED copy handed to the route - the MIME message // itself is already in memory at this point, so the cap bounds the exchange, not the // network transfer (both were dead options before the options sweep). var fetchAttachments = options?.FetchAttachments ?? true; var maxSize = options?.MaxAttachmentSize ?? 0; foreach (var att in attachments) { var fileName = att.ContentDisposition?.FileName ?? att.ContentType.Name ?? "attachment"; names.Add(fileName); if (!fetchAttachments) continue; using var ms = new MemoryStream(); if (att is MimePart part && part.Content is not null) part.Content.DecodeTo(ms); else if (att is MessagePart { Message: not null } attached) attached.Message.WriteTo(ms); // message/rfc822: one attachment with its bytes else continue; if (maxSize > 0 && ms.Length > maxSize) continue; // oversized: named in AttachmentNames, payload not carried var bytes = ms.ToArray(); if (att is MimePart) mailAttachments.Add(new MailAttachment(fileName, bytes, att.ContentType.MimeType)); // The same file on the message attachments: smtp: and the other producers send these, so // imap -> smtp forwards them without a mapping step. message.Attachments.Add(new Attachment { Name = BareFileName(fileName), FileName = BareFileName(fileName), ContentType = att.ContentType.MimeType, ContentId = string.IsNullOrEmpty(att.ContentId) ? null : att.ContentId, Headers = PartHeaders(att), Content = AttachmentContent.FromBytes(bytes), }); } headers[MailHeaders.AttachmentNames] = string.Join(", ", names); // Body-type contract: with fetchAttachments on (the default), a mail // that HAS attachments always yields a MailMessageBody - even when none of them // decoded into the list (message/rfc822 parts, everything over the size cap). // Existing routes cast on HasAttachments=true; handing them a bare string only for // those shapes was an unannounced contract change. fetchAttachments=false is the // explicit opt-in for "metadata only, plain body". if (fetchAttachments) message.Body = new MailMessageBody(body, mailAttachments); } // ── Dates ──────────────────────────────────────────────────── if (mime.Date != default) headers[MailHeaders.Date] = mime.Date.ToString("O"); // ── Priority ───────────────────────────────────────────────── headers[MailHeaders.Priority] = mime.Importance switch { MessageImportance.High => "high", MessageImportance.Low => "low", _ => "normal" }; // ── Protocol ───────────────────────────────────────────────── headers[MailHeaders.Protocol] = protocol; // mapMimeHeaders=true: every raw MIME header rides the exchange under redbMail.Mime.* // (a dead option before the options sweep). if (options?.MapMimeHeaders == true) { foreach (var h in mime.Headers) headers[MailHeaders.MimePrefix + h.Field] = h.Value; } // ── IMAP-specific ──────────────────────────────────────────── if (folder is not null) headers[MailHeaders.Folder] = folder; if (uid.IsValid) headers[MailHeaders.Uid] = uid.Id.ToString(); if (index >= 0) headers[MailHeaders.Index] = index; return Exchange.Create(message, scopeFactory); } private static readonly System.Text.RegularExpressions.Regex Folding = new(@"\r?\n[ \t]*"); /// The file name without a directory: a sender's path does not reach the route. private static string BareFileName(string fileName) { var slash = fileName.LastIndexOfAny(['/', '\\']); var bare = (slash < 0 ? fileName : fileName[(slash + 1)..]).Replace("\r", "").Replace("\n", ""); return bare.Length == 0 ? "attachment" : bare; } /// The part headers, unfolded (an attachment holds no line breaks). private static Dictionary PartHeaders(MimeEntity part) { var headers = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var header in part.Headers) headers[header.Field] = Folding.Replace(header.Value ?? string.Empty, " ").Trim(); return headers; } private static string FormatAddresses(InternetAddressList list) { if (list.Count == 0) return ""; return string.Join(", ", list.Mailboxes.Select(m => m.Address)); } private static void SetIfNotEmpty(IDictionary headers, string key, string? value) { if (!string.IsNullOrEmpty(value)) headers[key] = value; } } /// /// Composite body for emails with attachments. /// Text holds the email body, Attachments holds the decoded file data. The same files are also on the message /// attachments (), which is what smtp: sends. /// public sealed class MailMessageBody(string text, IReadOnlyList attachments) : ICloneable { /// Decoded text body. public string Text { get; } = text; /// The text body: what smtp: writes when a received mail is sent on. public override string ToString() => Text; /// Decoded attachments that fit the size cap (names always ride the headers). public IReadOnlyList Attachments { get; } = attachments; // 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 — attachment payload bytes must not be shared. public object Clone() => new MailMessageBody( Text, Attachments.Select(a => (MailAttachment)a.Clone()).ToList()); } Path: redb-route/redb.Route.Mail/MailSearchTerm.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/MailSearchTerm.cs ---- using System.Globalization; using System.Text.RegularExpressions; using MailKit.Search; using MimeKit; using redb.Route.Core; namespace redb.Route.Mail; /// /// Apache Camel's mail searchTerm: which mails the consumer takes. Written on the URI as an option group, /// searchTerm.subject=invoice&searchTerm.fromSentDate=now-24h (Camel's SimpleSearchTerm), or as /// searchTerm=#name, a MailKit registered under that name, which then wins over the /// simple options (IMAP only). The terms that are set are ANDed. A set search term replaces fetchFilter. /// /// IMAP sends the terms to the server as one SEARCH. IMAP compares dates by whole days, so a date bound is also checked /// on the client against the exact time: the Date header for the sent dates, the arrival time (INTERNALDATE) for the /// received dates. POP3 has no search: the consumer checks every term but (POP3 keeps no flags) on /// the client, and refuses at start what it cannot check: a registry search query and the received dates. /// /// public sealed class MailSearchTerm { /// The format of a fixed date: yyyy-MM-dd HH:mm:ss, in the host's time zone. public const string DateFormat = "yyyy-MM-dd HH:mm:ss"; /// /// searchTerm=#name: a MailKit in the registry, sent to the IMAP server as it is. /// The simple options are not read beside it. /// [OptionGroupValue] [RegistryReference(typeof(SearchQuery))] public string? Reference { get; set; } /// Only mails not yet seen (default true, as in Camel). IMAP only: POP3 keeps no flags. public bool Unseen { get; set; } = true; /// Text the subject or the body contains. public string? SubjectOrBody { get; set; } /// Text the subject contains. public string? Subject { get; set; } /// Text the body contains. public string? Body { get; set; } /// Text the From address contains. public string? From { get; set; } /// Text a To address contains. public string? To { get; set; } /// Sent at or after: , or now with an offset (now-24h, now - 1d12h). public string? FromSentDate { get; set; } /// Sent at or before: , or now with an offset. public string? ToSentDate { get; set; } /// Received (arrived on the server) at or after: , or now with an offset. IMAP only. public string? FromReceivedDate { get; set; } /// Received at or before: , or now with an offset. IMAP only. public string? ToReceivedDate { get; set; } /// Whether a registry search query is named. internal bool HasReference => !string.IsNullOrWhiteSpace(Reference); /// Whether a received date bound is set. internal bool HasReceivedBounds => FromReceivedDate is not null || ToReceivedDate is not null; /// Refuses a date the format does not take, naming the option. internal void Validate() { foreach (var (name, value) in Dates()) if (value is not null) _ = SearchDate.Parse(name, value); } private IEnumerable<(string Name, string? Value)> Dates() => [ ("searchTerm.fromSentDate", FromSentDate), ("searchTerm.toSentDate", ToSentDate), ("searchTerm.fromReceivedDate", FromReceivedDate), ("searchTerm.toReceivedDate", ToReceivedDate), ]; /// /// The IMAP SEARCH of the simple options at : the terms ANDed, the date bounds widened to the /// whole day (IMAP compares days; then checks the exact time). /// internal SearchQuery ToImapQuery(DateTimeOffset now) { var terms = new List(); if (Unseen) terms.Add(SearchQuery.NotSeen); if (SubjectOrBody is not null) terms.Add(SearchQuery.SubjectContains(SubjectOrBody).Or(SearchQuery.BodyContains(SubjectOrBody))); if (Subject is not null) terms.Add(SearchQuery.SubjectContains(Subject)); if (Body is not null) terms.Add(SearchQuery.BodyContains(Body)); if (From is not null) terms.Add(SearchQuery.FromContains(From)); if (To is not null) terms.Add(SearchQuery.ToContains(To)); // SENTSINCE d: on or after day d; SENTBEFORE d: before day d, so the day of the bound is d + 1. if (Bound(nameof(FromSentDate), FromSentDate, now) is { } fromSent) terms.Add(SearchQuery.SentSince(fromSent.LocalDateTime.Date)); if (Bound(nameof(ToSentDate), ToSentDate, now) is { } toSent) terms.Add(SearchQuery.SentBefore(toSent.LocalDateTime.Date.AddDays(1))); if (Bound(nameof(FromReceivedDate), FromReceivedDate, now) is { } fromReceived) terms.Add(SearchQuery.DeliveredAfter(fromReceived.LocalDateTime.Date.AddDays(-1))); if (Bound(nameof(ToReceivedDate), ToReceivedDate, now) is { } toReceived) terms.Add(SearchQuery.DeliveredBefore(toReceived.LocalDateTime.Date.AddDays(1))); return terms.Count == 0 ? SearchQuery.All : terms.Aggregate(SearchQuery.And); } /// /// Whether a fetched mail meets the terms, checked on the client: what POP3, which has no search, does for every term /// but (POP3 keeps no flags). The received dates are refused on POP3 at start. /// internal bool Matches(MimeMessage mime, DateTimeOffset now) { if (SubjectOrBody is not null && !Contains(mime.Subject, SubjectOrBody) && !Contains(BodyText(mime), SubjectOrBody)) return false; if (Subject is not null && !Contains(mime.Subject, Subject)) return false; if (Body is not null && !Contains(BodyText(mime), Body)) return false; if (From is not null && !mime.From.Mailboxes.Any(m => Contains(m.ToString(), From))) return false; if (To is not null && !mime.To.Mailboxes.Any(m => Contains(m.ToString(), To))) return false; return MatchesDates(mime.Date == default ? null : mime.Date, received: null, now); } /// Whether a mail sent at and received at is within the date bounds. internal bool MatchesDates(DateTimeOffset? sent, DateTimeOffset? received, DateTimeOffset now) => Within(sent, Bound(nameof(FromSentDate), FromSentDate, now), Bound(nameof(ToSentDate), ToSentDate, now)) && (!HasReceivedBounds || Within(received, Bound(nameof(FromReceivedDate), FromReceivedDate, now), Bound(nameof(ToReceivedDate), ToReceivedDate, now))); /// Whether a date bound is set. internal bool HasDateBounds => FromSentDate is not null || ToSentDate is not null || HasReceivedBounds; // A mail without the date a bound reads does not match it, as Camel's NowSearchTerm. private static bool Within(DateTimeOffset? date, DateTimeOffset? from, DateTimeOffset? to) => (from is null && to is null) || (date is { } d && (from is null || d >= from) && (to is null || d <= to)); private static DateTimeOffset? Bound(string member, string? value, DateTimeOffset now) => value is null ? null : SearchDate.Parse("searchTerm." + char.ToLowerInvariant(member[0]) + member[1..], value).At(now); private static bool Contains(string? text, string term) => text?.Contains(term, StringComparison.OrdinalIgnoreCase) == true; private static string? BodyText(MimeMessage mime) => mime.TextBody ?? mime.HtmlBody; /// A date bound: a fixed time, or now with an offset. internal readonly record struct SearchDate(DateTimeOffset? Fixed, TimeSpan Offset) { // Camel's "now-24h", "now - 24h", "now+1d"; the offset in Camel's TimeUtils units. private static readonly Regex Now = new(@"^now\s*(?:([+-])\s*(.+))?$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); private static readonly Regex Duration = new( @"^\s*(?:(\d+)\s*d(?:ays?)?)?\s*(?:(\d+)\s*h(?:ours?)?)?\s*(?:(\d+)\s*m(?:in(?:utes?)?)?(?!s))?\s*(?:(\d+)\s*s(?:ec(?:onds?)?)?)?\s*(?:(\d+)\s*ms)?\s*$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); /// The time the bound names at . public DateTimeOffset At(DateTimeOffset now) => Fixed ?? now + Offset; /// Parses a bound, refusing anything else with the option's name. public static SearchDate Parse(string option, string value) { var text = value.Trim(); if (Now.Match(text) is { Success: true } now) return new SearchDate(null, now.Groups[1].Success ? (now.Groups[1].Value == "-" ? -ParseOffset(option, value, now.Groups[2].Value) : ParseOffset(option, value, now.Groups[2].Value)) : TimeSpan.Zero); if (DateTime.TryParseExact(text, DateFormat, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out var date)) return new SearchDate(new DateTimeOffset(date), TimeSpan.Zero); throw Refused(option, value); } private static TimeSpan ParseOffset(string option, string value, string offset) { offset = offset.Trim(); if (long.TryParse(offset, NumberStyles.None, CultureInfo.InvariantCulture, out var millis)) return TimeSpan.FromMilliseconds(millis); var match = Duration.Match(offset); if (!match.Success || offset.Length == 0) throw Refused(option, value); long Part(int group) => match.Groups[group].Success ? long.Parse(match.Groups[group].Value, CultureInfo.InvariantCulture) : 0; return TimeSpan.FromDays(Part(1)) + TimeSpan.FromHours(Part(2)) + TimeSpan.FromMinutes(Part(3)) + TimeSpan.FromSeconds(Part(4)) + TimeSpan.FromMilliseconds(Part(5)); } private static ArgumentException Refused(string option, string value) => new( $"'{option}={value}' is not a valid value: {option} takes a date '{DateFormat}' or now with an offset " + "('now-24h', 'now+1d12h'; units d, h, m, s, ms, or milliseconds).", option); } } Path: redb-route/redb.Route.Mail/Pop3Component.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/Pop3Component.cs ---- using System.Diagnostics; using System.Text.RegularExpressions; using MailKit.Net.Pop3; using Microsoft.Extensions.Logging; using MimeKit; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Telemetry; namespace redb.Route.Mail; /// /// POP3 component. Scheme: "pop3". /// Provides email consumption via POP3 using MailKit. /// URI: pop3://mail.example.com:995?username=inbox@ex.com&password=xxx /// [EndpointRole(EndpointRole.Consumer, Hint = "Use smtp: to send mail.")] public class Pop3Component : ComponentBase { /// public override string Scheme => "pop3"; /// public override IEndpoint CreateEndpoint(EndpointUri uri) { ArgumentNullException.ThrowIfNull(uri); var options = new MailEndpointOptions(); if (!string.IsNullOrEmpty(uri.Path) && uri.Path != "/") options.Host = uri.Path.TrimStart('/'); options.BindFromUri(uri.RawParameters); MailEndpointOptions.RefuseOtherSide(uri, Scheme, EndpointRole.Consumer); MailConnectionFactory.TryApply(Context, options, uri, Logger, "POP3"); options.Validate(EndpointRole.Consumer); return new Pop3Endpoint(uri, this, options); } } /// /// POP3 endpoint. Creates a Pop3Consumer for receiving email. /// public class Pop3Endpoint : EndpointBase { /// Creates a POP3 endpoint. public Pop3Endpoint(EndpointUri uri, Pop3Component component, MailEndpointOptions options) : base(uri, component, options) { } /// The mail server host. public string Host => Options.Host; /// The resolved port number. public int Port => Options.ResolvePort("pop3"); /// Endpoint options. internal MailEndpointOptions EndpointOptions => Options; /// public override IProducer CreateProducer() => throw new NotSupportedException("POP3 does not support producing. Use smtp: scheme instead."); /// public override IConsumer CreateConsumer(IProcessor processor) { ArgumentNullException.ThrowIfNull(processor); return new Pop3Consumer(this, processor, Options); } } /// /// POP3 consumer — fetches email messages via MailKit Pop3Client. /// POP3 is a simple polling protocol: connect, list messages, download, optionally delete. /// Does not support IDLE mode or folders. /// public class Pop3Consumer : DrainableConsumer { private readonly Pop3Endpoint _endpoint; private readonly MailEndpointOptions _options; private MailIdempotency? _idempotency; // POP3 UIDL is optional (RFC 1939); a message without a Message-ID then has no key, said once. private bool _warnedNoKey; private readonly Regex? _subjectRegex; private readonly HashSet? _fromFilter; private long _processedCount; // POP3 TOP is optional (RFC 1939); once a server refuses it, stop asking every message. private bool _serverLacksTop; /// protected override IEndpoint ConsumerEndpoint => _endpoint; /// protected override string ConsumerName => "pop3"; /// Creates a POP3 consumer. public Pop3Consumer(Pop3Endpoint endpoint, IProcessor processor, MailEndpointOptions options) : base(processor) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _options = options ?? throw new ArgumentNullException(nameof(options)); if (!string.IsNullOrWhiteSpace(options.SubjectFilter)) _subjectRegex = new Regex(options.SubjectFilter, RegexOptions.IgnoreCase | RegexOptions.Compiled); if (!string.IsNullOrWhiteSpace(options.FromFilter)) _fromFilter = new HashSet( options.FromFilter.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries), StringComparer.OrdinalIgnoreCase); } /// Number of messages successfully processed. public long ProcessedCount => Interlocked.Read(ref _processedCount); /// protected override Task OnStarting(CancellationToken ct) { // The repository is looked up when the consumer starts, so a name nothing is registered under stops the route. _idempotency = MailIdempotency.Create(_options, _endpoint); // POP3 has no search: the searchTerm options are checked on the client. A registry search query (IMAP SEARCH) // and the received dates (POP3 has no arrival time) cannot be, so they stop the route instead of matching nothing. if (_options.SearchTerm is { } term) { if (term.HasReference) throw new InvalidOperationException( "searchTerm=" + term.Reference + " names an IMAP search query; POP3 has no search and takes the searchTerm.* options."); if (term.HasReceivedBounds) throw new InvalidOperationException( "searchTerm.fromReceivedDate and searchTerm.toReceivedDate need the arrival time, which POP3 does not keep."); } return Task.CompletedTask; } /// The Message-ID, else the UIDL; null when the message has neither (the server lacks UIDL). private async Task IdempotentKeyAsync(Pop3Client client, MimeMessage mime, int index, CancellationToken ct) { if (!string.IsNullOrEmpty(mime.MessageId)) return mime.MessageId; if (client.Capabilities.HasFlag(Pop3Capabilities.UIDL)) return await client.GetMessageUidAsync(index, ct).ConfigureAwait(false); if (!_warnedNoKey) { _warnedNoKey = true; Logger?.LogWarning("POP3 server does not support UIDL; a message without a Message-ID is routed without " + "an idempotency key"); } return null; } /// protected override async Task RunAsync(CancellationToken pollCt, CancellationToken processingCt) { if (_options.InitialDelay > 0) await Task.Delay(_options.InitialDelay, pollCt).ConfigureAwait(false); var delay = TimeSpan.FromMilliseconds(_options.Delay); while (!pollCt.IsCancellationRequested) { try { using var client = await ConnectAsync(processingCt).ConfigureAwait(false); var count = client.Count; var toFetch = _options.MaxMessages > 0 ? Math.Min(count, _options.MaxMessages) : count; for (var i = 0; i < toFetch; i++) { if (processingCt.IsCancellationRequested) break; MimeMessage mime; if (!_options.FetchBody && !_serverLacksTop) { // fetchBody=false: envelope scanning - headers only. try { var headerList = await client.GetMessageHeadersAsync(i, processingCt).ConfigureAwait(false); mime = MailMessageHelper.FromHeadersOnly(headerList); } catch (NotSupportedException ex) { // Headers-only needs the POP3 TOP command, which RFC 1939 makes // OPTIONAL. Without this fallback the poll died with a generic // transient warning every cycle, indistinguishable from a network // blip. Fall back to full fetch, say why, once. _serverLacksTop = true; Logger?.LogWarning(ex, "POP3 server does not support the TOP command; fetchBody=false " + "cannot do headers-only on this server - falling back to full fetch"); mime = await client.GetMessageAsync(i, processingCt).ConfigureAwait(false); } } else { mime = await client.GetMessageAsync(i, processingCt).ConfigureAwait(false); } // Client-side filters if (!PassesFilters(mime)) continue; if (!PassesAgeFilter(mime)) continue; if (_options.SearchTerm is { } search && !search.Matches(mime, DateTimeOffset.Now)) continue; // Idempotency, after the filters: a message they hold back is not taken. The key is the // Message-ID, else the UIDL; the position in the mailbox names another message next session. var key = _idempotency is null ? null : await IdempotentKeyAsync(client, mime, i, processingCt).ConfigureAwait(false); if (key is not null && !await _idempotency!.TryAdd(key, processingCt).ConfigureAwait(false)) continue; var exchange = MailMessageHelper.CreateExchange(mime, "pop3", index: i, scopeFactory: _endpoint.ScopeFactory, options: _options); if (_options.KeepRawMessage) exchange.Properties["RawMimeMessage"] = mime; using var span = StartConsumerSpan(mime); IncrementInflight(); try { try { await Processor.Process(exchange, processingCt).ConfigureAwait(false); } catch (OperationCanceledException) when (processingCt.IsCancellationRequested) { throw; // our own stop: end the poll, the message is not a failure } catch (Exception ex) { // A failure that escaped the route is one failed message: it is left on the server and the // poll goes on to QUIT, so the deletes made before it in this session commit. span.Activity.RecordFailure(ex); Logger?.LogError(ex, "POP3: the route failed for message {Index}; the message is left on the server", i); if (key is not null) await _idempotency!.Rollback(key, processingCt).ConfigureAwait(false); continue; } if (exchange.Exception is { } failure && !exchange.ExceptionHandled && (failure is not OperationCanceledException || !processingCt.IsCancellationRequested)) span.Activity.RecordFailure(failure); // Apache Camel's rollback: a failed exchange (an unhandled exception, or rollback-only) leaves // the message on the server; only a successful one is committed. if (exchange.EndedInFailure()) { Logger?.LogWarning(exchange.ExceptionHandled ? null : exchange.Exception, "POP3: the exchange for message {Index} failed; the message is left on the server", i); if (key is not null) await _idempotency!.Rollback(key, processingCt).ConfigureAwait(false); continue; } Interlocked.Increment(ref _processedCount); // POP3 post-processing: only delete or none. redbMail.Delete on the message the route ended with // overrides the endpoint (Apache Camel's CamelMailDelete); POP3 has no folders to move or copy to. var result = exchange.HasOut ? exchange.Out! : exchange.In; var delete = result.Headers.ContainsKey(MailHeaders.Delete) ? result.GetHeader(MailHeaders.Delete) : _options.Delete || _options.PostProcess == PostProcessAction.Delete; if (delete) await client.DeleteMessageAsync(i, processingCt).ConfigureAwait(false); if (key is not null) await _idempotency!.Commit(key, processingCt).ConfigureAwait(false); } finally { DecrementInflight(); await exchange.DisposeAsync().ConfigureAwait(false); } } await client.DisconnectAsync(quit: true, processingCt).ConfigureAwait(false); } catch (OperationCanceledException) when (pollCt.IsCancellationRequested || processingCt.IsCancellationRequested) { break; } catch (Exception ex) { Logger?.LogWarning(ex, "POP3 poll failed, retrying on next cycle"); } try { await Task.Delay(delay, pollCt).ConfigureAwait(false); } catch (OperationCanceledException) { break; } } } // ── Client-side filters ─────────────────────────────────────────── private bool PassesFilters(MimeMessage mime) { if (_subjectRegex is not null && !_subjectRegex.IsMatch(mime.Subject ?? "")) return false; if (_fromFilter is not null && mime.From.Mailboxes.All(mb => !_fromFilter.Contains(mb.Address))) return false; return true; } private bool PassesAgeFilter(MimeMessage mime) { if (_options.MinAge <= 0 && _options.MaxAge <= 0) return true; var messageDate = mime.Date.UtcDateTime; if (messageDate == default) return true; var age = DateTimeOffset.UtcNow - messageDate; if (_options.MinAge > 0 && age.TotalMilliseconds < _options.MinAge) return false; if (_options.MaxAge > 0 && age.TotalMilliseconds > _options.MaxAge) return false; return true; } // ── Connection ──────────────────────────────────────────────────── private async Task ConnectAsync(CancellationToken ct) { var client = new Pop3Client(); 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); return client; } private async Task AuthenticateAsync(Pop3Client 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); } } /// /// The span of one message. A mailbox message carries no trace context the connector reads, so the span is a root, /// never a child of the activity the poll loop holds. /// private TransportSpan StartConsumerSpan(MimeMessage mime) { var span = RouteTelemetryExtensions.StartConsumerSpan( (_endpoint.Component as ComponentBase)?.Context, $"{_endpoint.Host} receive", ActivityKind.Consumer, "messaging.system", "pop3", _endpoint.Uri.NormalizedKey, null, static (_, _) => null, destination: _endpoint.Host, operation: "receive"); if (span.Activity is { IsAllDataRequested: true } activity) { if (!string.IsNullOrEmpty(mime.MessageId)) activity.SetTag("messaging.message.id", mime.MessageId); if (!string.IsNullOrEmpty(mime.Subject)) activity.SetTag("messaging.pop3.subject", mime.Subject); } return span; } } Path: redb-route/redb.Route.Mail/README.md 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/README.md ---- # redb.Route.Mail > Documentation and articles: Email transport for redb.Route via MailKit. SMTP producer for sending, IMAP/POP3 consumers for receiving with IDLE push, attachments, TLS/SSL, and OAuth. [![NuGet](https://img.shields.io/nuget/v/redb.Route.Mail?label=NuGet&color=blue)](https://www.nuget.org/packages/redb.Route.Mail) [![License: Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-blue)](../../LICENSE) ## Installation ```bash dotnet add package redb.Route.Mail ``` ## Usage ### Fluent DSL ```csharp using redb.Route.Mail; // Send email via SMTP From("direct://send-email") .To(Smtp.Send("smtp.gmail.com") .Port(587) .Security("StartTls") .Username("sender@gmail.com").Password("app-password") .From("sender@gmail.com") .To("recipient@example.com") .Subject("Order Confirmation")); // Receive emails via IMAP (IDLE push) From(Imap.Read("imap.gmail.com") .Port(993) .Security("Ssl") .Username("inbox@gmail.com").Password("app-password") .Folder("INBOX") .Unseen() .Idle() .FetchBody() .FetchAttachments() .PostProcess(nameof(PostProcessAction.MarkRead))) .Log("Email from: ${header.From} — ${header.Subject}") .To("direct://process"); // POP3 polling From(Pop3.Read("pop3.example.com") .Port(995) .Security("Ssl") .Username("user").Password("pass") .Delay(30000) .MaxMessages(10)) .To("seda://email-queue"); ``` ## Fluent Builder API | Category | Methods | |----------|---------| | **Connection** | `.Port()`, `.Security(mode)`, `.ConnectionTimeout()`, `.Timeout()`, `.Username()`, `.Password()`, `.AccessToken()`, `.AuthMechanism()`, `.TrustAllCertificates()`, `.ClientCert()` | | **SMTP** | `Smtp.Send(server)`, `.From()`, `.To()`, `.Cc()`, `.Bcc()`, `.ReplyTo()`, `.Subject()`, `.ContentType()`, `.AlternativeBody()`, `.Attachments()` | | **IMAP** | `Imap.Read(server)`, `.Folder()`, `.AdditionalFolders()`, `.Idle()`, `.IdleTimeout()`, `.SearchTerm(t => ...)`, `.SearchTerm("#name")` (see [Search term](#search-term)) | | **POP3** | `Pop3.Read(server)` | | **Consumer** | `.Delay()`, `.InitialDelay()`, `.Unseen()`, `.MaxMessages()`, `.FetchFilter()`, `.FetchBody()`, `.FetchAttachments()`, `.MaxAttachmentSize()`, `.Peek(bool)`, `.Idempotent()`, `.IdempotentRepository()`, `.IdempotentRepositoryRemoveOnCommit()`, `.SortBy()`, `.MinAge()`, `.MaxAge()`, `.SubjectFilter()`, `.FromFilter()` | | **Post-process** | `.PostProcess(action)`, `.MoveTo()`, `.Delete()`, `.CopyTo()` | The three schemes share one set of options, but each option belongs to one side: the SMTP group to `smtp:`, the IMAP, consumer and post-process groups to `imap:` and `pop3:`. An option written on the other side is refused when the endpoint is created, naming it ("smtp producer '...' sets postProcess: only an imap or pop3 consumer reads it."); connection, authentication and TLS options are read by both. ## Search term Which mails a consumer takes is Apache Camel's `searchTerm`, written as an option group: each option of the group is `searchTerm.` and its name, as in Camel, so a Camel URI carries over. ``` imap://mail.example.com?username=u&password=p&searchTerm.subject=invoice&searchTerm.fromSentDate=now-24h ``` | Option | Default | Takes the mails | |--------|---------|-----------------| | `searchTerm.unseen` | `true` | not yet seen (IMAP; POP3 keeps no flags) | | `searchTerm.subjectOrBody` | | whose subject or body contains the text | | `searchTerm.subject` | | whose subject contains the text | | `searchTerm.body` | | whose body contains the text | | `searchTerm.from` | | whose From address contains the text | | `searchTerm.to` | | whose To addresses contain the text | | `searchTerm.fromSentDate`, `searchTerm.toSentDate` | | sent at or after, at or before the date | | `searchTerm.fromReceivedDate`, `searchTerm.toReceivedDate` | | received at or after, at or before the date (IMAP) | - The options that are set are ANDed. Text matches ignore case. - A date is `yyyy-MM-dd HH:mm:ss` in the host's time zone, or `now` with an offset: `now-24h`, `now - 1d12h`, `now+30m` (units `d`, `h`, `m`, `s`, `ms`, or a number of milliseconds). Camel writes the same, though its parser reads the seconds field as milliseconds; here the seconds are seconds. - `searchTerm=#name` names a MailKit `SearchQuery` in the registry instead, sent to the IMAP server as it is; the `searchTerm.*` options are not read beside it, as in Camel. - A set search term replaces `fetchFilter`, so the two are not set together (the endpoint refuses it at start; `searchTerm.unseen=false` takes the seen mails too). - IMAP sends the options to the server as one SEARCH. IMAP compares dates by whole days, so the consumer checks the date bounds again against the exact time, the Date header for the sent dates and the arrival time (INTERNALDATE) for the received ones, before `maxMessages` counts. A mail without the date a bound reads is not taken. - POP3 has no search: the consumer checks the options on each mail it reads (the body ones need `fetchBody=true`, the default). `searchTerm=#name` and the received dates cannot be checked on POP3 and stop the route at start. - `subjectFilter`, `fromFilter`, `minAge` and `maxAge` still filter on the client after the search. In route XML the group is written as attributes with the same names (an XML name may hold a dot): ``. ## Three Schemes | Scheme | Direction | Description | |--------|-----------|-------------| | `smtp` | Producer | Send emails | | `imap` | Consumer | Receive via IMAP (IDLE push or polling) | | `pop3` | Consumer | Receive via POP3 (polling) | The `smtp` producer keeps its connection between sends. When the server has closed it while it was idle (a socket timeout answered with `421`, a reset), the message is sent once more on a new connection; a refusal on a fresh connection is the server's answer and fails the exchange. `disconnect=true` opens a connection per message instead. ## What happens to a consumed mail `imap:` and `pop3:` treat a mail the way Apache Camel's mail consumer does once its exchange ends. - **The exchange succeeded** (also when an `OnException` handled the failure): the mail is committed. `copyTo` copies it first; then `postProcess` applies (`MarkRead`, the default; `Delete`; `Move` or `MarkReadAndMove` with `moveTo`; `Flag`; `None`), or Camel's `delete=true`, which deletes it, moved to `moveTo` first when that is set. A `moveTo` or `copyTo` folder the mailbox does not have is created. POP3 knows only deleting and keeping. - **The exchange failed** (an unhandled exception, or `.RollbackAll()`): the mail is left as it is. On IMAP it stays unseen and is fetched again; `peek=false` marks each mail read when it is fetched, so a failed one stays read and `fetchFilter=Unseen` does not fetch it again. On POP3 it stays on the server and is fetched again. The mails after it are routed as usual. The route decides per mail with three headers on the message, read only when the exchange succeeded, as Camel's `CamelMailDelete`, `CamelMailMoveTo` and `CamelMailCopyTo`: | Header | Effect | |--------|--------| | `redbMail.Delete` | `true` deletes the mail; `false` marks it read (IMAP) or keeps it on the server (POP3) | | `redbMail.MoveTo` | moves it to this IMAP folder, marked read unless `redbMail.Delete` is `true` | | `redbMail.CopyTo` | copies it to this IMAP folder before anything else is done to it | **Delete only what succeeded.** Delete the mails the route accepted; keep the rejected and the failed ones in the mailbox, read, so they are not fetched again and can be looked at by hand: ```csharp From(Imap.Read("imap.example.com").ConnectionFactory("inbox") .Unseen() .PostProcess(nameof(PostProcessAction.Delete)) .Peek(false)) // a failed mail was marked read at fetch .Process(exchange => { if (!Accepts(exchange)) { exchange.In.Headers[MailHeaders.Delete] = false; // rejected: kept, read exchange.Stop(); } }) .To("direct://process"); // accepted: deleted once the route ends ``` ```xml ``` Without `peek=false`, handle the failure instead and set `redbMail.Delete=false` in the handler: the exchange then commits and the mail is marked read rather than deleted. **Idempotency.** `idempotent=true` skips, until the consumer restarts, the mails it routed successfully. `idempotentRepository=name` (Camel's option) uses a registered `IIdempotentRepository` instead, which a persistent implementation keeps across restarts: a mail's key is added before its route and the mail is skipped while the repository holds it; a failed exchange releases the key; a committed one removes it (`idempotentRepositoryRemoveOnCommit=true`, the default, since the mail was deleted or marked read) or confirms it. The key is the Message-ID, else the folder, UIDVALIDITY and UID (IMAP) or the UIDL (POP3). ## Attachments Mail works with the [message attachments](../README.md#attachments) (`exchange.In.Attachments`), the same list an upload, a SOAP MTOM call or a route step fills, so the connector before `smtp:` does not matter. ```csharp // From code exchange.In.Attachments.Add(new Attachment { Name = "invoice", FileName = "invoice-42.pdf", ContentType = "application/pdf", Content = AttachmentContent.FromBytes(pdf), }); // From a route step: a file read by file:, sent as an attachment From("file:///data/out?include=*.pdf") .AddAttachmentFromBody("report", fileName: Header("redbFile.Name"), contentType: "application/pdf") .SetBody("The report is attached.") .To("smtp://mail.example.com?to=team@example.com&subject=Report"); // Forwarding: the received attachments go out as they came From("imap://imap.example.com?username=in&password=...") .To("smtp://mail.example.com?to=archive@example.com"); ``` **`smtp:` sends** every message attachment as a part of the mail: the file name (the attachment name when there is none), the content type, the `Content-ID`, an `inline` disposition when the part it came from was inline, and the other part headers except `Content-*`. The `attachments=` option still adds files by path, before the message attachments. **`imap:` and `pop3:` receive** every attachment of the mail onto the message attachments: named by its file name without a directory, with its content type, `Content-ID` and part headers; an attached mail (`message/rfc822`) is one attachment with its bytes. The body stays as before: `MailMessageBody` with the text and the decoded files, and the `redbMail.HasAttachments`, `redbMail.AttachmentCount`, `redbMail.AttachmentNames` headers. `fetchAttachments=false` puts none on the message; `maxAttachmentSize` leaves out the ones above it. `MailMessageBody` converts to its text, so `smtp:` sends a received mail on with its text. The exchange property `Attachments` is not read: it is an ordinary property now. A route that put a `List` or file paths there sends the mail without those files until it puts them on the message attachments (see `UPGRADING.md`, "Mail and SOAP attachments are message attachments"). ## Part of [redb.Route](../README.md) — ESB & EIP Framework for .NET ## Named connection factory Keep credentials out of the route URI: register a factory in the context registry and reference it by name. A set-but-unknown name fails loud at startup — a typo can never silently fall back to inline URI parameters. ```csharp context.AddToRegistry("prod", new MailConnectionFactory { Host = "smtp.internal", Username = "noreply", Password = secrets.SmtpPassword, }); // smtp://noreply@internal?connectionFactory=prod ``` ## Tracing On the `redb.Route` activity source (`AddSource("redb.Route")`), with `messaging.system` = `imap` / `pop3` / `smtp` and `redb.route.endpoint`: - **IMAP and POP3 consumers.** One `Consumer` span per routed message, `{host} receive`. The connector reads no trace context from a message, so the span is a root, never a child of the activity the poll loop inherited from whoever started the routes; an empty mailbox opens none. A failed route marks it an error; our own stop does not. - **SMTP producer.** One `Producer` span per send, `{host} send`; an error when the send fails, unless our own token cancelled it. - `RouteEngineOptions.EnableTelemetry = false` opens none of these spans. Path: redb-route/redb.Route.Mail/SmtpComponent.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/SmtpComponent.cs ---- using System.Diagnostics; using System.Text.RegularExpressions; using MailKit; using MailKit.Net.Smtp; using MimeKit; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Telemetry; namespace redb.Route.Mail; /// /// SMTP component. Scheme: "smtp". /// Provides email sending via SMTP using MailKit. /// URI: smtp://mail.example.com:587?username=bot@ex.com&password=xxx&security=StartTls /// [EndpointRole(EndpointRole.Producer, Hint = "Use imap: or pop3: to receive mail.")] public class SmtpComponent : ComponentBase { /// public override string Scheme => "smtp"; /// public override IEndpoint CreateEndpoint(EndpointUri uri) { ArgumentNullException.ThrowIfNull(uri); var options = new MailEndpointOptions(); if (!string.IsNullOrEmpty(uri.Path) && uri.Path != "/") options.Host = uri.Path.TrimStart('/'); options.BindFromUri(uri.RawParameters); MailEndpointOptions.RefuseOtherSide(uri, Scheme, EndpointRole.Producer); MailConnectionFactory.TryApply(Context, options, uri, Logger, "SMTP"); options.Validate(EndpointRole.Producer); return new SmtpEndpoint(uri, this, options); } } /// /// SMTP endpoint. Creates an SmtpProducer for sending email. /// public class SmtpEndpoint : EndpointBase { /// Creates an SMTP endpoint. public SmtpEndpoint(EndpointUri uri, SmtpComponent component, MailEndpointOptions options) : base(uri, component, options) { } /// The mail server host. public string Host => Options.Host; /// The resolved port number. public int Port => Options.ResolvePort("smtp"); /// Endpoint options for external access. internal MailEndpointOptions EndpointOptions => Options; /// public override IProducer CreateProducer() => new SmtpProducer(this, Options); /// public override IConsumer CreateConsumer(IProcessor processor) => throw new NotSupportedException("SMTP does not support consuming. Use imap: or pop3: scheme instead."); } /// /// SMTP producer — sends email messages via MailKit SmtpClient. /// Supports plain text and HTML bodies, attachments, CC/BCC, Reply-To, /// OAuth2 authentication, and TLS/SSL. /// public class SmtpProducer : IProducer { private readonly SmtpEndpoint _endpoint; private readonly MailEndpointOptions _options; private SmtpClient? _client; private readonly object _lock = new(); /// Creates an SMTP producer. public SmtpProducer(SmtpEndpoint endpoint, MailEndpointOptions options) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _options = options ?? throw new ArgumentNullException(nameof(options)); } /// public Task Start(CancellationToken ct = default) => Task.CompletedTask; /// public async Task Stop(CancellationToken ct = default) { if (_client is { IsConnected: true }) { await _client.DisconnectAsync(quit: true, ct).ConfigureAwait(false); _client.Dispose(); _client = null; } } /// public async Task Process(IExchange exchange, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(exchange); using var activity = RouteTelemetryExtensions.StartTransportSpan( (_endpoint.Component as ComponentBase)?.Context, $"{_endpoint.Host} send", ActivityKind.Producer, "messaging.system", "smtp", _endpoint.Uri.NormalizedKey, destination: _endpoint.Host, operation: "send"); try { await SendAsync(exchange, activity, ct).ConfigureAwait(false); } catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested) { // Only our own token cancelling the send is a stop; any other failure marks the span. activity.RecordFailure(ex); throw; } } private async Task SendAsync(IExchange exchange, Activity? activity, CancellationToken ct) { var message = BuildMimeMessage(exchange); if (activity is { IsAllDataRequested: true }) { activity.SetTag("messaging.smtp.from", message.From.ToString()); activity.SetTag("messaging.smtp.to", message.To.ToString()); if (!string.IsNullOrEmpty(message.Subject)) activity.SetTag("messaging.smtp.subject", message.Subject); } var (client, reused) = await EnsureConnectedAsync(ct).ConfigureAwait(false); try { await client.SendAsync(message, ct).ConfigureAwait(false); } // A kept connection the server has closed while it was idle (a socket timeout: "421 Service shutting down", a // reset) is not seen by IsConnected; the server refused before taking the message, so it is sent once more on a // new connection. A failure on a fresh connection is the server's answer and goes up. catch (Exception ex) when (reused && IsDeadConnection(ex) && !ct.IsCancellationRequested) { Drop(client); (client, _) = await EnsureConnectedAsync(ct).ConfigureAwait(false); await client.SendAsync(message, ct).ConfigureAwait(false); } exchange.In.Headers[MailHeaders.MessageId] = message.MessageId; if (_options.Disconnect) { await client.DisconnectAsync(quit: true, ct).ConfigureAwait(false); client.Dispose(); lock (_lock) _client = null; } } private MimeMessage BuildMimeMessage(IExchange exchange) { var msg = new MimeMessage(); // ── Addressing (header > expression > static) ── var from = GetHeader(exchange, MailHeaders.From) ?? _options.ResolveOption(_options.From, exchange); if (!string.IsNullOrWhiteSpace(from)) msg.From.AddRange(InternetAddressList.Parse(from)); var to = GetHeader(exchange, MailHeaders.To) ?? _options.ResolveOption(_options.To, exchange); if (!string.IsNullOrWhiteSpace(to)) msg.To.AddRange(InternetAddressList.Parse(to)); var cc = GetHeader(exchange, MailHeaders.Cc) ?? _options.ResolveOption(_options.Cc, exchange); if (!string.IsNullOrWhiteSpace(cc)) msg.Cc.AddRange(InternetAddressList.Parse(cc)); var bcc = GetHeader(exchange, MailHeaders.Bcc) ?? _options.ResolveOption(_options.Bcc, exchange); if (!string.IsNullOrWhiteSpace(bcc)) msg.Bcc.AddRange(InternetAddressList.Parse(bcc)); var replyTo = GetHeader(exchange, MailHeaders.ReplyTo) ?? _options.ResolveOption(_options.ReplyTo, exchange); if (!string.IsNullOrWhiteSpace(replyTo)) msg.ReplyTo.AddRange(InternetAddressList.Parse(replyTo)); // ── Subject (header > expression > static) ── msg.Subject = GetHeader(exchange, MailHeaders.Subject) ?? _options.ResolveOption(_options.Subject, exchange) ?? ""; // ── In-Reply-To / References (threading) ── var inReplyTo = GetHeader(exchange, MailHeaders.InReplyTo); if (!string.IsNullOrWhiteSpace(inReplyTo)) msg.InReplyTo = inReplyTo; var references = GetHeader(exchange, MailHeaders.References); if (!string.IsNullOrWhiteSpace(references)) { foreach (var refId in references.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) msg.References.Add(refId); } // ── Priority ── var priority = GetHeader(exchange, MailHeaders.Priority); if (!string.IsNullOrWhiteSpace(priority) && Enum.TryParse(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); } Path: redb-route/redb.Route.Mail/redb.Route.Mail.csproj 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/redb.Route.Mail.csproj ---- redb.Route.Mail Email transport for redb.Route ESB framework. SMTP producer, IMAP/POP3 consumers with IDLE push, polling, attachments, TLS/SSL. Enterprise-grade email integration powered by MailKit. esb;messaging;email;smtp;imap;pop3;mailkit;redb README.md