How to Send Custom Notifications from Apex in Salesforce

by Rijwan Mohmmed
0 comment
send-custom-notifications-from-apex-in-salesforce-techdicer

Hello friends today we will learn send Custom notifications from Apex. Custom notifications are a way to show information inside Salesforce by sending notifications to users with a short message (that can be linked to a record) which can be accessed in the small bell on the top right corner of the interface.

For send custom notifications first we need to create custom notification type.

Setup > Notification Builder > Custom Notifications

Click New and create custom notification type.

Now lets focus on our main aim on Apex class

public class SendCustomNotification{

	pubic static void sendNotofication(){
		User usr = [SELECT Id, Profile.Name FROM User WHERE Profile.Name = 'System Administrator' LIMIT 1]
	
	
		// Get the Id for our custom notification type
		CustomNotificationType notificationType = [SELECT Id, DeveloperName 
												FROM CustomNotificationType 
										WHERE DeveloperName='test_notification'];
																					  
		// Create a new custom notification
		Messaging.CustomNotification notification = new Messaging.CustomNotification();
					
		// Set the contents for the notification
		notification.setTitle('Test Title');
		notification.setBody('Test Body');
			 
		// Set the notification type and target
		notification.setNotificationTypeId(notificationType.Id);
		notification.setTargetId('ObjectId');
					
		Set<String> addressee = new Set<String>();
		addressee.add(usr.Id);
					
		// Actually send the notification
		try {
			notification.send(addressee);
		}
		catch (Exception e) {
			System.debug('Problem sending notification: ' + e.getMessage());
		}
	
	}
}

You may also like

Leave a Comment