Wednesday, June 19, 2013

Sending Email on field change using a trigger


How to send Email to current and former lead owner if there is a change in the owner of the lead record?????
               The answer in simple you can do this by a trigger using messaging.single email message class. The scenario for me was like this in a lead record if there is a change in the lead owner a notification email has to be sent to the previous owner and current owner i've posted the code below for your reference.
 /*************  
 *******Created by:Nirmal Christopher  
 *******Created Date:02.05.2013  
 *******Description:Email will be sent if the owner is changed to new owner and old owner of the respective lead record  
 *************/  
 trigger SendEmailOnOwnerChange on Lead (before update,After Update) {  
   if (trigger.old[0].OwnerId != trigger.new[0].OwnerId ) {  
     Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();  
     //Select the Email Address of the old owner  
     String emailAddrnew = [select Email from User where Id = :trigger.old[0].OwnerId].Email;  
     String emailAddrold = [select Email from User where Id = :trigger.new[0].OwnerId].Email;  
     //Select the new owner and old owner from user  
     String newOwnerName = [select Name from User where Id = :trigger.new[0].OwnerId].Name;  
     String oldownerName=[select name from User where Id =:trigger.old[0].OwnerId].Name;  
     //Store the email address  
     String[] emailAddrnew1 = new String[] {emailAddrnew};  
     String[] emailAddrold1 = new string[]{emailAddrold};  
     mail.setToAddresses(emailAddrnew1 );  
     mail.setCcAddresses(emailAddrold1 );  
     mail.setSubject('Owner Changed for Lead : ' + trigger.new[0].Name);  
     mail.setPlainTextBody('Owner of lead: ' + oldownerName + ' Changed to ' + newOwnerName);  
     mail.setHtmlBody('This is to notify that the Owner of lead: https://ap1.salesforce.com/ <b>' + trigger.new[0].Id+'<b>&nbsp;&nbsp;Changed from</b>&nbsp;&nbsp;'+oldownerName + '</b>&nbsp;&nbsp; Changed to <b>' + newOwnerName + '</b>');  
     Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });  
   }  
 }  

hope this helps 

1 comment:

Anonymous said...

This is an excellent post I seen thanks to share it. It is really what I wanted to see hope in future you will continue for sharing such a excellent post.
call center software in Nigeria