Thursday 6 November 2014

Salesforce Apex Code for Email Template | How to send

  1. trigger LeadBeforeUpdate on Lead (before update)
  2. {      
  3.  
  4. //Prefetch email Template id
  5. EmailTemplate et = [SELECT id FROM EmailTemplate WHERE Name = 'Lead_Rejected'];
  6.  
  7. //Grab the recipient as Contact
  8. Contact recipient = [SELECT id, firstname FROM Contact where id in :Trigger.newMap.keySet()];    
  9.  
  10. //Map the profile
  11. Map<Id, Profile> ProfileOwner = new Map<Id, Profile>([Select p.Id, p.Name from Profile p where Id =: userinfo.getProfileId()]);
  12.  
  13. //Lead Object Map
  14. Map<Id, Lead> LeadMap = new Map<Id,Lead>([Select Id, From Lead WHERE id in :Trigger.newMap.keySet()]);
  15.  
  16. for (lead myLead : Trigger.new)
  17.     {  
  18.        
  19.         Lead testLead = LeadMap.get(myLead.id);
  20.  
  21.         if(testLead.Status__c=='Approved') {
  22.            
  23.     /*---Mail to the Lead Owner **********/
  24.    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); // new mail object
  25.  
  26.    //Depending on Schema your organization have
  27.    recipient.AccountId = opp.AccountId;  // receipient would be owner of Lead  
  28.     mail.setSenderDisplayName(ProfileOwner.get(userInfo.getUserId).Name);//Sender would be owner of Profile
  29.  
  30. //Notice : How I retrieve profile by passing value of current user id (using UserInfo Method)
  31.   mail.setTargetObjectId(recipient.id); //target to receipient
  32.   mail.setTemplateId(et.id);           // pull the email template through id
  33.   Messaging.sendEmail(new Messaging.Singleemailmessage[] {mail});  //send single email
  34.  
  35. } // end if
  36. } // end for

No comments:

Post a Comment