Wednesday, August 26, 2020

Send Custom Notifications Using Apex in Salesforce

From Winter'21 onwards we can use the Messaging.CustomNotification class to create, configure, and send custom notifications directly from Apex code, such as a trigger.

Using Messaging.CustomNotification class to create and send custom notifications from Apex is easy. Create a new instance of CustomNotification, configure a few notification details, and call the send() method.


Before Customizing the Custom Notification you need to define custom notification type in notification types.
From Setup, enter Notification builder in the Quick Find box, and then Select Notification types

After creating the Notification type get the Id of the notification type Using SOQL

Use below SOQL Query to get the notification type Id.
SELECT Id, CustomNotifTypeName, DeveloperName from CustomNotificationType WHERE DeveloperName = '<Dev_Name>'

Note: Use Tooling API to Query

Apex Class

public inherited sharing class SendCustomNotification {
    public static void sendNotifications(String strBody, String strSenderId, String strTargetId, String strTitle, String strNotificationId, set<String> setUserIds) {
        Messaging.CustomNotification obj = new Messaging.CustomNotification();
        // Custom notification type Id
        // when we click on the notification it will redirect to the specified targetId
        // Notification Title
        // Notification Body
        // send used to send the notification, pass the set of user ids , Group or Queue member

Sample test 

SendCustomNotification.sendNotifications('This is Test Body', '', userinfo.getUserId(), 'This is Test Message', '0MLB00000004CrSOAU', new set<String>{UserInfo.getUserId()});