Hello friends, In this post we will learn, how to send custom notification using apex code. This is really helpful for you when you want to notify any user either on desktop or on mobile through code logic. so let's get started.

Send custom notification using apex

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

Using Messaging.CustomNotification class to send custom notifications from Apex is too easy. Create a new instance of CustomNotification, configure a few notification parameters, and call the send() method. Let's understand this process using code example.

Follow the below steps to implement this example.

Step 1. Navigate to Setup | Notification Builder | Custom Notification. Create a new notification type like below image(In below image i just marked desktop checkbox, if you need notification for mobile, mark mobile checkbox also).


Step 2. Create an apex class and replace the following code.

NotificationHandler.apxc

 public class NotificationHandler {

public static void notifyUsers() {
// Get the Id of custom notification type
CustomNotificationType notificationType = [SELECT Id, DeveloperName FROM CustomNotificationType WHERE DeveloperName='MyNotification'];
// Create a new custom notification
Messaging.CustomNotification notification = new Messaging.CustomNotification();
//Set the contents for the notification
notification.setTitle('Apex Custom Notification');
notification.setBody('The notifications are coming through the Apex!');
// Set the notification type and target
notification.setNotificationTypeId(notificationType.Id);
notification.setTargetId('0016F00002x1j7mQAA'); //Replace this record id with your org record id
try {
notification.send(new Set<String>{Userinfo.getUserId()});
}
catch (Exception e) {
System.debug('Problem while sending notification: ' + e.getMessage());
}
}
}

Output: On executing the above code, you will see the notification in your salesforce org like below image.

 

Hope you like this post, for any feedback or suggestions please feel free to comment. I would appreciate your feedback and suggestions.
Thank you.