# Email Notifications

The Sudo Platform Email Service sends push notifications on receipt of each email message to registered devices. These notifications contain metadata about the received email message encrypted using the public key registered with the email address that received the message.

There are three aspects to adding Sudo Platform Email Service push notification support to your application:

1. Notification registration\
   This aspect records your application's interest in Sudo Platform Email Service notifications with the Sudo Platform Notification Service.
2. Notification configuration\
   This aspect allows you to configure filtering of specific notifications. In particular, Sudo Platform Email SDK allows you to enable and disable transmission of message received notifications for particular email addresses.
3. Notification reception\
   This aspect allows you to decrypt the push notification payload and decide how to render the information in a notification displayed to the user.

## Notification Registration

Registering for notifications is performed using the Sudo Platform Notification SDK. Each platform has a slightly different way of doing this. See the platform specific descriptions below for the specific way required to integrate notifications for a particular language environment.

{% tabs %}
{% tab title="iOS" %}
The Sudo Notification Platform SDK for iOS takes as input a`NotificationFilterClient` provided by each Sudo Platform service that an application will receive notifications for. Each service's SDK provides a service specific filter client for this purpose.

The Sudo Platform Email Service SDK for iOS provides the `DefaultSudoEmailNotificationFilterClient` . The following sample code shows how this is registered with the Sudo Platform Notification Client SDK for iOS.

```swift
import SudoNotification
import SudoEmail

let emailNotificationFilterClient = DefaultSudoEmailNotificationFilterClient()

let notificationClient = try DefaultSudoNotificationClient(
  userClient: userClient,
  notifiableServices: [emailNotificationFilterClient]
)
```

{% endtab %}

{% tab title="Android" %}
The Sudo Notification Platform SDK for Android takes as input a`SudoNotificationClient` provided by each Sudo Platform service that an application will receive notifications for. Each service's SDK provides a service specific notification client for this purpose.

The Sudo Platform Email Service SDK provides the `SudoEmailNotificationClient` . The following sample code shows how this is registered with the Sudo Platform Notification Client SDK within the context of your `android.app.Application`:

```kotlin
import com.sudoplatform.sudoemail.SudoEmailClient
import com.sudoplatform.sudoemail.SudoEmailNotifiableClient
import com.sudoplatform.sudologging.AndroidUtilsLogDriver
import com.sudoplatform.sudologging.LogLevel
import com.sudoplatform.sudologging.Logger
import com.sudoplatform.sudonotification.SudoNotificationClient
import com.sudoplatform.sudouser.SudoUserClient

val logger = Logger("my-sudo-platform-application", AndroidUtilsLogDriver(LogLevel.DEBUG))

val sudoUserClient = SudoUserClient.builder(this)
    .setNamespace("my-sudo-platform-application")
    .setLogger(logger)
    .build()

val sudoEmailNotifiableClient = SudoEmailNotifiableClient.builder()
    .setContext(this)
    .setNotificationHandler(notificationHandler)
    .build()

val sudoNotificationClient = SudoNotificationClient.builder()
    .setContext(this)
    .setSudoUserClient(sudoUserClient)
    .setLogger(logger)
    .setNotifiableClients(listOf(sudoEmailNotifiableClient))
    .build()
```

The `notificationHandler` is an instance of a `SudoEmailNotificationHandler` that you will write to handle reception of Sudo Platform Email Service notifications. See [#notification-reception](#notification-reception "mention") for information on writing a `SudoEmailNotificationHandler` for your application.
{% endtab %}
{% endtabs %}

## Notification Configuration

Before your application will receive Sudo Platform Email Service notifications, you must enable them for the device's notification configuration. In addition to that you may choose to allow suppression sending of notifications for particular email addresses. Both of these tasks are accomplished with extensions to the Sudo Platform Notification SDK `NotificationConfiguration` class.

### Enabling Sudo Platform Email Notifications

The `.initEmailNotifications` extension is used to ensure a `NotificationConfiguration` object includes registering interest in all the notification types sent by the Sudo Platform Email Service.

This operation is non-destructive if other services' notification configuration is also present. It is also non-destructive to any email address specific configuration that may already be present in the notification configuration object.

{% tabs %}
{% tab title="iOS" %}

```swift
import SudoNotification
import SudoEmail

var configuration = NotificationConfiguration(configs: [])
do {
    configuration = try await sudoNotificationClient
        .getNotificationConfiguration(device: device)
} catch let error as SudoNotificationError {
    // Tolerate .notFound error
    guard case .notFound = error else {
        // Handle error
    }
}

// Ensure Sudo Platform Email Service notifications are enabled
configuration = configuration.initEmailNotifications()

let services = sudoNotificationClient.notifiableServices.map { $0.getSchema() }

do {
    configuration = try await sudoNotificationClient.setNotificationConfiguration(
        config: NotificationSettingsInput(
            bundleId: "<bundle-identifier>",
            deviceId: "<device-identitifier>",
            filter: configuration.configs,
            services: services
        )
    )
} catch {
   // Handle error
}
```

{% endtab %}

{% tab title="Android" %}

```kotlin
import com.sudoplatform.sudonotification.SudoNotificationClient

val configuration =
    try {
        // Retrieve this device's current configuration and ensure it is
        // initialized to receive email notifications
        sudoNotificationClient
            .getNotificationConfiguration(deviceInfo)
            .initEmailNotifications()
    } catch (e: SudoNotificationClient.NotificationException.NoDeviceNotificationException) {
        // If there is no current configuration, set default configuration which enables
        // all notifications
        NotificationConfiguration(configs = emptyList())
            .initEmailNotifications()
    }

sudoNotificationClient.setNotificationConfiguration(
    NotificationSettingsInput(
        bundleId = "<bundle-identitifier>",
        deviceId = "<device-identifier>",
        services = listOf(sudoEmailNotifiableClient.getSchema()),
        filter = configuration.configs,
    ),
)
```

{% endtab %}
{% endtabs %}

### Managing notification configuration for specific Sudos

Whether or not notifications for email addresses associated with a particular Sudo are sent by the Sudo Platform Email Service can be controlled by adjusting the notification configuration for the device.

Whether or not notifications are currently enabled for a particular Sudo can be determined as follows for each platform:

{% tabs %}
{% tab title="iOS" %}

```swift
import SudoNotification
import SudoEmail

let configuration: NotificationConfiguration

if configuration.areNotificationsEnabled(
       forSudoWithId: sudoId
   ) {
   // Notifications are enabled
} else {
   // Notifications are not enabled
}
```

{% endtab %}

{% tab title="Android" %}

```kotlin
import com.sudoplatform.sudoemail.isEmailNotificationForSudoIdEnabled
import com.sudoplatform.sudonotification.types.NotificationConfiguration

val configuration: NotificationConfiguration

if (configuration.isEmailNotificationForSudoIdEnabled(sudoId)) {
   // Notifications are enabled
} else {
   // Notifications are not enabled
}
```

{% endtab %}
{% endtabs %}

Notifications can be enabled or disabled for a particular Sudo by modifying and updating the `NotificationConfiguration` for the device:

{% tabs %}
{% tab title="iOS" %}

```swift

import SudoNotification
import SudoEmail

let configuration: NotificationConfiguration

let newConfiguration = configuration.setEmailNotificationsForSudoId(
    sudoId: sudoId,
    enabled: true or false
)

try await notificationClient.setNotificationConfiguration(
    config: NotificationSettingsInput(
        bundleId: "<bundle-id>",
        deviceId: "<device-id>",
        filter: newConfiguration.configs,
        services: [sudoEmailNotificationFilterClient.getSchema()]
    )
)
```

{% endtab %}

{% tab title="Android" %}

```kotlin
import com.sudoplatform.sudoemail.setEmailNotificationsForSudoId
import com.sudoplatform.sudonotification.types.NotificationConfiguration

val configuration: NotificationConfiguration

val newConfiguration = configuration.setEmailNotificationsForSudoId(
    sudoId = sudoId,
    enabled = true or false
)

// Call setNotificationConfiguration in IO context
sudoNotificationClient.setNotificationConfiguration(
    NotificationSettingsInput(
        bundleId = "<bundle-id>",
        deviceId = "<device-id>",
        services = listOf(sudoEmailNotifiableClient.getSchema()),
        filter = newConfiguration.configs,
    ),
)
```

{% endtab %}
{% endtabs %}

### Managing notification configuration for specific email addresses

Whether or not notifications that pertain to a particular email address are sent by the Sudo Platform Email Service can be controlled by adjusting the notification configuration for the device.

Whether or not notifications are currently enabled for a particular email address can be determined as follows for each platform:

{% tabs %}
{% tab title="iOS" %}

```swift
import SudoNotification
import SudoEmail

let configuration: NotificationConfiguration

if configuration.areNotificationsEnabled(
       forEmailAddressWithId: emailAddressId
   ) {
   // Notifications are enabled
} else {
   // Notifications are not enabled
}
```

{% endtab %}

{% tab title="Android" %}

```kotlin
import com.sudoplatform.sudoemail.isEmailNotificationForAddressIdEnabled
import com.sudoplatform.sudonotification.types.NotificationConfiguration

val configuration: NotificationConfiguration

if (configuration.isEmailNotificationForAddressIdEnabled(emailAddressId)) {
   // Notifications are enabled
} else {
   // Notifications are not enabled
}
```

{% endtab %}
{% endtabs %}

Notifications can be enabled or disabled for a particular email address by modifying and updating the `NotificationConfiguration` for the device:

{% tabs %}
{% tab title="iOS" %}

```swift

import SudoNotification
import SudoEmail

let configuration: NotificationConfiguration

let newConfiguration = configuration.setEmailNotificationsForAddressId(
    emailAddressId: emailAddressId,
    enabled: true or false
)

try await notificationClient.setNotificationConfiguration(
    config: NotificationSettingsInput(
        bundleId: "<bundle-id>",
        deviceId: "<device-id>",
        filter: newConfiguration.configs,
        services: [sudoEmailNotificationFilterClient.getSchema()]
    )
)
```

{% endtab %}

{% tab title="Android" %}

```kotlin
import com.sudoplatform.sudoemail.setEmailNotificationsForAddressId
import com.sudoplatform.sudonotification.types.NotificationConfiguration

val configuration: NotificationConfiguration

val newConfiguration = configuration.setEmailNotificationsForAddressId(
    emailAddressId = emailAddressId,
    enabled = true or false
)

// Call setNotificationConfiguration in IO context
sudoNotificationClient.setNotificationConfiguration(
    NotificationSettingsInput(
        bundleId = "<bundle-id>",
        deviceId = "<device-id>",
        services = listOf(sudoEmailNotifiableClient.getSchema()),
        filter = newConfiguration.configs,
    ),
)
```

{% endtab %}
{% endtabs %}

## Notification Reception

Sudo Platform notification messages contain encrypted content that needs to be decoded. The specific ways that notifications are received and decoded is platform specific. See the platform specific sections below for information on receiving and decoding Sudo Platform Email Service notifications.

{% tabs %}
{% tab title="iOS" %}
On iOS, in order to decode the notification you must implement a notification service app extension as described in [Modifying content in newly delivered notifications](https://developer.apple.com/documentation/usernotifications/modifying-content-in-newly-delivered-notifications) in the iOS developer documentation. This allows you to use information in the encrypted payload of the notification to modify the notification for display to the user.

If you receive notifications from other sources, you must first determine the source of the notification.

The Sudo Platform Notification SDK for iOS provides a `DefaultSudoNotifiableClient` class that decodes all Sudo Platform notifications. It is initializes with a service SDK specific implementation of `SudoNotifiableClient`. The Sudo Platform Email SDK provides `DefaultSudoEmailNotifiableClient` for this purpose.

To initialize the `DefaultSudoNotifiableClient` to decode email service notifications, do the following within your `UNNotificationServiceExtension` implementation's `didReceive` method.

Separate `SudoNotificationExtension` and `SudoEmailNotificationExtension` PODs are provided containing the minimal code needed to implement the notification service app extension with minimal overhead.

```swift
import SudoNotificationExtension
import SudoEmailNotificationExtension

class MyNotificationServiceExtension: UNNotificationServiceExtension {

    override func didReceive(
        _ request: UNNotificationRequest,
        withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void
    ) {

    let bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
    guard let bestAttemptContent = bestAttemptContent else {
        contentHandler(request.content)
        return
    }

    let sudoEmailNotifiableClient = DefaultSudoEmailNotifiableClient(keyNamespace: "eml")
    let sudoNotifiableClient = try DefaultSudoNotifiableClient(
        notifiableClients: [sudoEmailNotifiableClient]
    )

```

The `keyNamespace` specified in the construction of the `DefaultSudoEmailNotifiableClient` must match the `keyNamespace` you use to construct `DefaultSudoEmailClient` in the main application. If the key namespaces do not match then the `DefaultSudoEmailNotifiableClient` will not be able to access the keys needed to decrypt the notification payload.

{% hint style="info" %}
To access the keys, the application and the notification service app extension must both have the Keychain Sharing capability and have the same Keychain group.
{% endhint %}

Once you have initialized the `DefaultSudoNotifiableClient` you can then extract any Sudo Platform notification data from the notification. If no data is extracted then the notification has come from a source other than a Sudo Platform service.

```swift
    guard let sudoNotificationData = sudoNotifiableClient.extractData(
        fromNotificationContent: bestAttemptContent
    ) else {
        // Handle non-Sudo Platform notification
    }
```

Once you have identified the notification as originating at a Sudo Platform service, you can then decode it to a specific notification class:

```swift
    switch sudoNotifiableClient.decodeData(data: sudoNotificationData) {
    case let decoded as EmailMessageReceivedNotification:
        // handle EmailMessageReceivedNotification
    case let decoded as ....
        // handle other Sudo Platform notification
    }
```

{% endtab %}

{% tab title="Android" %}
On Android, a `SudoEmailNotificationHandler` specific to your application is required to be implemented.

This class will contain method of the form `on<notification-type>` for each type of notification your application is interested in handling.

An instance of this class is passed to `SudoEmailNotifiableClient` when it is constructed as part of initializing the `SudoNotificationClient`. See [Notification Registration](#notification-registration).

Within your application's `FirebaseMessagingService` implementation you call the `SudoNotificationClient`'s `process` method to examine the notification payload, extract any Sudo Platform notification payload, decrypt and decode it, and then pass it to the appropriate registered `SudoNotifiableClient`.

```kotlin
class MyFirebaseMessagingService implements FirebaseMessagingService {
    override fun onMessageReceived(message: RemoteMessage) {
        sudoNotificationClient.process(message)
    }
}

```

{% endtab %}
{% endtabs %}

### Notification Types

The Sudo Platform Email Service supports the following notification types

EmailMessageReceivedNotification

Sent on receipt of an email message, this notification contains metadata about the message that was received.

<table data-full-width="false"><thead><tr><th>Property</th><th>Description</th></tr></thead><tbody><tr><td>emailAddressId</td><td>ID of the email address to which the notification pertains</td></tr><tr><td>sudoId</td><td>ID of the Sudo owner of the email address to which the notification pertains</td></tr><tr><td>messageId</td><td>ID of the message to which the notification pertains</td></tr><tr><td>folderId</td><td>ID of the folder in which the message to which the notification pertains is stored</td></tr><tr><td>encryptionStatus</td><td>End-to-end encryption status of the message to which the notification pertains</td></tr><tr><td>subject</td><td>Subject, if any, of the message to which the notification pertains</td></tr><tr><td>from</td><td>Sender of the message to which the notification pertains</td></tr><tr><td>replyTo</td><td>Reply-To address, if any, of the message to which the notification pertains</td></tr><tr><td>hasAttachments</td><td>Whether or not the message to which the notification pertains has any attachments</td></tr><tr><td>sentAt</td><td>Date when the message to which the notification pertains was sent - the message's <code>Date</code> header</td></tr><tr><td>receivedAt</td><td>Date when the message to which the notification pertains was received</td></tr></tbody></table>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.sudoplatform.com/guides/email/email-notifications.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
