I am trying to send an email using an Assignment Template from my trigger when the status is changed by the appropriate team.
I looked around and found 17047778: sending-email-with-template-using-trigger which is where I got some of the code from.
Here is the code in my trigger – it runs on Trigger.IsUpdate && trigger.isbefore
and the loop for (Request_for_System_Change__c rq : Trigger.new) {
:
// send conversion email
// 1. create a new single message
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
// 2. set the email addresses
List<String> sendTo = new List<String>();
string emailAddy=string.valueOf([SELECT Email from User where Id =: rq.Manager__c].Email);
sendTo.add(emailAddy);
emailAddy=string.valueOf([SELECT Email from User where Id =: rq.Originating_Owner__c].Email);
sendTo.add(emailAddy);
mail.setToAddresses(sendTo);
mail.setTargetObjectId(rq.Manager__c); // sendTo doesn't work either
// 3. set the template
EmailTemplate et=[Select id from EmailTemplate where DeveloperName ='Data_Request_Converted'];
mail.setTemplateId(et.id);
// 4. send the email
Messaging.SendEmailResult [] r =
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
Here is the error returned by SF:
Apex trigger System_Change_Request_Events caused an unexpected exception, contact your administrator: System_Change_Request_Events: execution of BeforeUpdate caused by: System.EmailException: SendEmail failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Missing targetObjectId with template: []: Trigger.System_Change_Request_Events: line 250, column 1
it seems to be saying something about the template… I got the template info from the query:
Select Id, Name from EmailTemplate where DeveloperName='Data_Request_Converted'
so I know the assignment template exists..
What am I doing wrong?
Best Answer
Cause
From the
Messaging.SingleEmailMessage
documentation, you cannot usesetToAddresses
in conjunction withsetTemplateId
:Limits
Note that you are blowing through email limits faster than you need to be because using a
targetObjectId
whose type isUser
is exempt from the daily send limit:Usage
If you want to send emails to multiple users, create multiple
SingleEmailMessages
for eachtargetObjectId
or oneMassEmailMessage
.