Skip to content

Channels ​

GrydNotifications supports three notification channels out of the box: Email, Push, and In-App. Each channel has its own provider abstraction, allowing you to swap implementations without changing application code.

Channel Architecture ​

                    SendNotificationCommand
                            │
                    ┌───────┴───────┐
                    │  Channel      │
                    │  Resolver     │
                    └───┬───┬───┬───┘
                        │   │   │
              ┌─────────┘   │   └─────────┐
              ▼             ▼             ▼
        ┌──────────┐ ┌──────────┐ ┌──────────┐
        │  Email   │ │   Push   │ │  In-App  │
        │ Provider │ │ Provider │ │  Sender  │
        └────┬─────┘ └────┬─────┘ └────┬─────┘
             │             │             │
        ┌────┴────┐   ┌───┴────┐   ┌────┴────┐
        │ MailKit │   │  FCM   │   │ SignalR  │
        │ SendGrid│   │ (pkg)  │   │ + DB     │
        └─────────┘   └────────┘   └──────────┘

Email Channel ​

The email channel supports SMTP via MailKit when SmtpHost is configured and SendGrid via the optional HTTP provider package. With no SMTP host and no alternate sender, the default provider returns failure; it does not silently accept email.

MailKit (SMTP) — Default ​

MailKit is the default email provider, recommended by Microsoft over System.Net.Mail. It supports OAuth2, connection pooling, DKIM, and S/MIME.

csharp
options.Email.SmtpHost = "smtp.myapp.com";
options.Email.SmtpPort = 587;
options.Email.SmtpUseSsl = true;
options.Email.SmtpUsername = "user";
options.Email.SmtpPassword = configuration["Smtp:Password"]!;
options.Email.DefaultFrom = "noreply@myapp.com";
options.Email.DefaultFromName = "My App";

Sending Emails ​

csharp
// Via unified pipeline
await _mediator.Send(new SendNotificationCommand
{
    Channel = NotificationChannel.Email,
    Recipients = [
        new RecipientDto("john@example.com", "John Doe"),
        new RecipientDto("jane@example.com", "Jane Doe")
    ],
    Subject = "Weekly Report",
    HtmlBody = "<h1>Your weekly report is ready</h1>",
    TextBody = "Your weekly report is ready"
}, ct);

// Via direct email shortcut
await _mediator.Send(new SendEmailCommand
{
    To = ["john@example.com"],
    Cc = ["manager@example.com"],
    Bcc = ["audit@myapp.com"],
    Subject = "Quarterly Summary",
    HtmlBody = "<h1>Q4 2025 Summary</h1>",
    FromAddress = "reports@myapp.com",
    FromName = "Reports System"
}, ct);

Email with Attachments ​

Attachments are files kept by GrydFiles, never bytes in the request or in the notifications database. Upload each file first through POST /files under the gryd.notification-attachment profile, wait for the antivirus to release it (status: Available), then send its id:

csharp
await _mediator.Send(new SendEmailCommand
{
    To = ["user@example.com"],
    Subject = "Invoice Attached",
    HtmlBody = "<p>Please find your invoice attached.</p>",
    AttachmentFileIds = [invoiceFileId]
}, ct);

SendNotificationCommand accepts the same AttachmentFileIds for the Email channel. The module checks each file when the command arrives:

RefusalCode
The host did not register GrydFiles422 NOTIFICATION_ATTACHMENT_DISABLED_UNPROCESSABLE
Still being scanned409 FILE_NOT_AVAILABLE_CONFLICT — send again once it is released
Infected (quarantined)409 FILE_INFECTED_CONFLICT — never attached
Purged409 FILE_PURGED_CONFLICT
Another tenant's file, or none404 FILE_NOT_FOUND
Uploaded under another profile422 NOTIFICATION_ATTACHMENT_PROFILE_UNPROCESSABLE
Above MaxAttachmentSizeMb422 NOTIFICATION_ATTACHMENT_TOO_LARGE_UNPROCESSABLE
More than MaxAttachmentsPerEmail, or the same file twice422 NOTIFICATION_ATTACHMENT_LIMIT_UNPROCESSABLE
A channel other than e-mail422 NOTIFICATION_ATTACHMENT_CHANNEL_UNPROCESSABLE

Each attachment of a persisted notification holds a reference on its file (owner scope gryd.notification-attachment) while the e-mail can still be delivered — including retries and a scheduled send — and lets go once the notification is Sent, Delivered, DeadLettered or Cancelled. From then on the file follows its profile's retention. The SMTP and SendGrid providers read each file's bytes from GrydFiles at the moment of sending; an attachment that is no longer available fails the send with the file module's code. The notification detail lists each attachment's storedFileId; its download URL comes from GET /files/{storedFileId}/download-url.

GrydFiles is optional, as SMTP is. Attachments are the only part of the module that needs it. A host that registers AddGrydFiles — before or after AddGrydNotifications, the order does not matter — gets attachments, and refuses to start unless the gryd.notification-attachment profile is declared with ScanRequired: true. A host that does not register it starts without any GrydFiles, object storage or ClamAV configuration: in-app, push and e-mail without attachments work as usual, and a send with AttachmentFileIds is refused with NOTIFICATION_ATTACHMENT_DISABLED_UNPROCESSABLE.

Email Limits ​

LimitDefaultConfigurable
Max attachment size10 MB✅ MaxAttachmentSizeMb
Max attachments/email5✅ MaxAttachmentsPerEmail
Max recipients (To+Cc+Bcc)50✅ MaxRecipientsPerEmail
Bulk batch size100✅ BulkBatchSize

SendGrid Provider ​

Use the SendGrid HTTP provider by installing GrydNotifications.Infrastructure.SendGrid and registering it after AddGrydNotifications:

csharp
builder.Services.AddGrydNotificationsSendGrid(options =>
{
    options.ApiKey = configuration["SendGrid:ApiKey"]!;
});

Sent means the email provider accepted the send request; it does not confirm the recipient's mailbox received or opened the message. Delivery feedback records what the provider reports afterwards, per recipient. SmtpUseSsl=true configures STARTTLS, not implicit TLS.


Push Channel ​

Push is a port, IPushNotificationSender, with one provider shipped as its own package: GrydNotifications.Infrastructure.Firebase (Firebase Cloud Messaging HTTP v1). FCM reaches Android, iOS (through FCM) and web browsers, so it also covers a web-only product. Without a provider the module keeps a no-op sender: every push fails with PUSH_NO_PROVIDER and the host logs a warning at startup.

Setup (FCM) ​

  1. Create a Firebase project and download a service account JSON.
  2. Reference GrydNotifications.Infrastructure.Firebase and register it, before or after AddGrydNotifications (the default no-op is only added when no sender is registered):
csharp
builder.Services.AddGrydNotificationsFirebase(firebase =>
{
    // One of the two. Keep the JSON in a secret store, never in appsettings committed to git.
    firebase.CredentialJson = builder.Configuration["Firebase:CredentialJson"];
    // firebase.CredentialPath = "/run/secrets/firebase-adminsdk.json";
});
  1. To refuse to start while push is on and no provider is registered:
json
"GrydNotifications": { "Push": { "Enabled": true, "RequireProvider": true } }

There is one Firebase credential per process (one per environment), not one per tenant.

Registering devices ​

The client registers its provider token after the user grants the permission, again whenever the token changes (and at each sign-in, which keeps it from going stale), and unregisters it at logout:

http
POST /api/v1/device-tokens
{ "token": "<fcm registration token>", "platform": "web", "deviceName": "Chrome on macOS" }

DELETE /api/v1/device-tokens/{id}

The registration belongs to the caller and to the session's tenant, the same tenant whose sends look the user's devices up: a user of several tenants registers the device in each. Registering a token again reactivates it; a token another user registered in the same tenant moves to the caller. In code, the same operations are RegisterDeviceTokenCommand and UnregisterDeviceTokenCommand.

For a browser, the client side (service worker, permission prompt, getToken with the VAPID key of the Firebase project) is the product's: the module only stores and uses the token.

Sending Push Notifications ​

csharp
// To a user: the module looks up the user's active devices in the current tenant
await _mediator.Send(new SendPushNotificationCommand
{
    UserId = userId,
    Title = "Approval pending",
    Body = "Purchase order 42 is waiting for you",
    Data = new Dictionary<string, string> { ["documentId"] = "42" }
}, ct);

// Via the unified pipeline: a recipient address that is a user id is resolved to the user's devices;
// any other address is used as a device token
await _mediator.Send(new SendNotificationCommand
{
    Channel = NotificationChannel.Push,
    Recipients = [new RecipientDto { Address = userId.ToString() }],
    Subject = "Approval pending",
    TextBody = "Purchase order 42 is waiting for you"
}, ct);

A send succeeds when at least one device accepted it. An https ClickAction becomes the link opened when the user clicks the browser notification; any other value stays an Android click action.

Failures ​

A provider never throws for a delivery failure: it returns one of the PushErrorCodes, which set the failure reason of the attempt and whether a durable delivery is dead-lettered (permanent) or left for reconciliation (transient):

CodeReasonPermanent
PUSH_NO_PROVIDERProviderUnavailableyes
PUSH_NO_DEVICE_TOKENSInvalidRecipientyes
PUSH_INVALID_DEVICE_TOKENInvalidDeviceTokenyes
PUSH_INVALID_PAYLOADUnknownyes
PUSH_AUTHENTICATION_FAILEDAuthenticationFailedyes
PUSH_RATE_LIMITEDRateLimitedno
PUSH_PROVIDER_UNAVAILABLEProviderUnavailableno
PUSH_SEND_FAILEDUnknownno

When some devices fail and none accepted, a transient code wins, so the delivery is not given up while one device could still take it.

Device token lifecycle ​

FeatureDescription
Dead tokensA token FCM reports as unregistered (or of another sender) is deactivated when AutoRemoveInvalidTokens is on. An invalid payload does not deactivate anything.
Stale tokensA token neither registered again nor used for StaleTokenThreshold (default 90 days, counted from registration when never used) is deactivated by the cleanup.
BatchingSends are split in batches of MaxDeviceTokensPerMulticast (at most 500, the FCM limit).
TTLA message without TimeToLive uses DefaultTimeToLive on Android and in the browser.

Your own provider ​

A product that uses another provider (Web Push with VAPID, APNs directly, a SaaS) implements IPushNotificationSender, registers it with services.AddScoped<IPushNotificationSender, MySender>() and keeps the contract above: PushErrorCodes for failures, success when one device accepted, dead tokens deactivated through IDeviceTokenStore, and the Push options honoured.


In-App Channel ​

The in-app channel creates notifications for the user's bell/drawer in your application. Notifications are persisted in the database and delivered in real-time via SignalR.

For a detailed guide on the In-App channel, see In-App & SignalR.

Quick Overview ​

csharp
// Send an in-app notification
await _mediator.Send(new SendInAppNotificationCommand
{
    UserId = userId,
    Title = "Task Assigned",
    Body = "You've been assigned to task #123",
    Icon = "📋",
    Category = "tasks",
    ActionUrl = "/tasks/123",
    Priority = NotificationPriority.High
}, ct);

Features ​

FeatureDescription
Read/Unread trackingMark individual or all as read
CategoriesFilter by category (alerts, tasks, comments, etc.)
ExpirationAuto-expire with ExpiresAfter
Collapse keysGroup related notifications
Real-time (SignalR)Instant delivery via WebSocket
Badge countUnread count endpoint for UI badge

Delivery Policy ​

Every channel asks the product's delivery policies before it delivers, so a preference or a repeat window applies whichever path the send takes.

Multi-Channel Sending ​

Send the same notification to multiple channels:

csharp
// Email + In-App
var notification = new SendNotificationCommand
{
    Channel = NotificationChannel.Email,
    Recipients = [new RecipientDto("user@example.com")],
    TemplateSlug = "order-confirmation",
    TemplateData = templateData
};

await _mediator.Send(notification, ct);

// Also create an in-app notification
await _mediator.Send(new SendInAppNotificationCommand
{
    UserId = userId,
    Title = "Order Confirmed",
    Body = $"Your order #{orderId} is confirmed",
    Category = "orders",
    ActionUrl = $"/orders/{orderId}"
}, ct);

Provider Abstraction ​

Each channel is defined by an abstraction in GrydNotifications.Core:

AbstractionDescription
IEmailSenderEmail delivery (MailKit, SendGrid)
IPushNotificationSenderPush delivery (FCM)
IInAppNotificationSenderIn-app create + SignalR broadcast
INotificationTemplateRendererTemplate compilation + rendering (Scriban)
INotificationQueueAsync processing queue

To swap a provider, register your implementation:

csharp
// Replace the default email sender
services.AddSingleton<IEmailSender, MyCustomEmailSender>();

Released under the MIT License.