Trigger for E-Mail Notification in Salesforce

Trigger for E-Mail Notification in Salesforce

We can use SingleEmailMessage to send email notification from Salesforce Triggers.

The following sample trigger will send an email when the Case status is set to Escalated.

Sample Trigger:

trigger CaseTrigger on Case ( after update ) {

    List < Messaging.SingleEmailMessage > listMessages = new List < Messaging.SingleEmailMessage >(); 

    for ( Case objCase : trigger.new ) {
    
        if ( 
            objCase.Status == 'Escalated' &&
            objCase.Status != trigger.oldMap.get( objCase.Id ).Status
        ) {
    
            Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage(); 
            List < String > listToAddresses = new List < String > { 'Your Email Address' };
            message.setToAddresses( listToAddresses );  
            message.setSubject( 'Case Escalation' );   
            message.setUseSignature(false);   
            message.setHtmlBody( 
                'Case ' + objCase.CaseNumber + ' is escalated'
            );  
            listMessages.add( message );  
        
        }
    
    }
    
    if ( listMessages.size() > 0 ) {
    
        Messaging.sendEmail( listMessages );
        
    }

}

Leave a Reply