function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Shree KShree K 

need help with the trigger to send emails upon owner change

Hi ,
need help with the trigger to send emails upon Account owner change,
below is my trigger code,which is not working,
help will be appreciated,
 
trigger EmailSend on Account (after insert,after update) {

List<account> acclist  = new set<account>();
For(account a:trigger.new){
If (a.ownerid != oldmap.get (a.id).ownerid)
acclist.add (a.id);
}
Messaging.SingleEmailMessage mails = new Messaging.SingleEmailMessage(); 
for(account acc:acclist) { 
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();  mail.setTargetObjectId(acc.ownerid); 
mail.setTemplateId('templateid'); mail.setWhatId(acc.id); mail.setBccSender(false); mail.setUseSignature(false);  mail.setSaveAsActivity(false); 
mails.add(mail);
 } Messaging.sendEmail(mails);
}
Thanks


 
Tarun J.Tarun J.
Hello,

Why can not you use Workflow to send email notification on Owner Change? Any specific reason for using Trigger.

Also, for above trigger, setup a debug log and check if you are getting some issue or not. Also add try-catch block to handle any exception.

-Thanks,
TK
@GM@GM
Hi,

What is templateid? i dont see any assignment to this variable ? get the template id by putting query on EmailTemplate and assign it to this variable.

Always prefer to accomplish your requirements with available salesforce configuration and if it is not possible then go for apex coding (trigger,batch etc)
Amit Chaudhary 8Amit Chaudhary 8
Please try code like below
trigger Sampleemailtrigger on Account (after update) {
  
  List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
  List<ID> ownerids=new List<ID>();
  
  List<String> sendTo = new List<String>();
  List<User> users=new List<User>();
  
  for (Account myacc : Trigger.new) {
    Account oldcon = Trigger.oldMap.get(myacc.Id);
    if (myacc.ownerid != oldcon.ownerid ) {    
       ownerids.add(myacc.ownerid) ;  
       //ownerids.add(oldcon.ownerid) ;
    }
    }
    
    if(ownerids.size()>0 ){     
    users=[select name,id,email from user where id in:ownerids];
    system.debug('-------------users------'+users);
    if(users.size()>0){
     for(User u:users){
      sendTo.add(u.Email);
    }
    
     Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
     //mail.setReplyTo('ramanisetti@gmail.com');
      mail.setSenderDisplayName('Email alert');

      mail.setSubject('Owner change');
      String body = 'Dear User Owner changed';
      mail.setToAddresses(sendTo);
      mail.setHtmlBody(body);
      mails.add(mail);
      try{
      Messaging.sendEmail(mails);
      }
      catch(Exception e){
      system.debug('-------------exception------'+e);
       
      }
    
    }
    
    }
  
}

Let us know if this will help you