Hi Everyone !!!
Today i am going to discuss one of the feature that is recently in winter 21. As i had previously discussed using custom notification from Process builder and Flows. You can read the blog from here if not read already.
So lets discuss the how can we use custom notification using apex .
- Create a custom notifications record.
- Write an apex class to query and send custom notification .
Steps to create the Custom notification can be found here in the first section.
Once the Notification is created. We need apex snippet to send notification.
public class SendCustomNotificationHandler {
public static void sendNotifs(){
CustomNotificationType objCustomNotif = [SELECT Id FROM CustomNotificationType
WHERE DeveloperName = 'Send_Notification_When_Oppty_is_Closed_Won_Lost'];
Messaging.CustomNotification sendNotification = new Messaging.CustomNotification();
sendNotification.setBody('Custom Notification -- Winter 21 Release');
sendNotification.setTitle('Custom Notifications By Apex');
sendNotification.setSenderId(Userinfo.getUserId());
sendNotification.setNotificationTypeId(objCustomNotif.id);
sendNotification.setTargetId(Userinfo.getUserId());
sendNotification.send(new Set { Userinfo.getUserId() });
}
}
On running this class using developer console using below code:
SendCustomNotificationHandler.sendNotifs();

Messaging.CustomNotification is the messaging class which we need to call and that will send notification.
Below are parameters that we use :
setBody – Body of the Notifications
setTitle – Title of Notification
setSenderId – One who has sent the Notifications
setNotificationTypeId – Notification which is queried and sent
setTargetId- Object on which we send the notification.