I am trying to run below code in trigger.

List<User> recipients = [SELECT id FROM User WHERE UserRoleId=:operationsRole.Id];
for (User usr:recipients) 
  Messaging.SingleEmailMessage notification = new Messaging.SingleEmailMessage();
   notification.setSenderDisplayName('SF Robot');

List<Messaging.SendEmailResult> postStats =
    Messaging.sendEmail(new Messaging.SingleEmailMessage[] {notification});
for (Messaging.SendEmailResult r:postStats)
    System.Debug('************postStat:' + r.isSuccess());



This error is because the method notification.setTargetObjectId(usr.Id) uses User Id and as per documentation you need to use notification.setWhatId(updatedOpp.Id) only when setTargetObjectId is contact.

Refer documentation below


If you specify a contact for the targetObjectId field, you can specify a whatId as well. This helps to further ensure that merge fields in the template contain the correct data.

  • 1
    Then how to display merge field values from template if we can't use setWhatId.
    – sfdc
    Dec 16 '13 at 18:47
  • I fear you can achieve this without custom coding the message .public Void setHtmlBody(String htmlBody) i would use this instead as workaround and never use template . Dec 16 '13 at 18:50
  • 1
    You might find helpful my project APEX Templates, that initially was meant to overcome the limits with sending dynamic emails to internal users.
    – endrju
    Dec 16 '13 at 22:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.