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.
Example:
Before Customizing the Custom Notification you need to define custom notification type in notification types.
Path:
From Setup, enter Notification builder in the Quick Find box, and then Select Notification types
Path:
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 obj.setNotificationTypeId(strNotificationId); // when we click on the notification it will redirect to the specified targetId obj.setTargetId(strTargetId); // Notification Title obj.setTitle(strTitle); // Notification Body obj.setBody(strBody); // send used to send the notification, pass the set of user ids , Group or Queue member obj.send(setUserIds); } }
Sample test
SendCustomNotification.sendNotifications('This is Test Body', '', userinfo.getUserId(), 'This is Test Message', '0MLB00000004CrSOAU', new set<String>{UserInfo.getUserId()});
Result