[SalesForce] INVALID_ID_FIELD, WhatId is not available for sending emails to UserIds

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.setTargetObjectId(usr.Id);
   notification.setWhatId(updatedOpp.Id);
   notification.setTemplateId(msgTemplate.id);
   notification.setSaveAsActivity(False);                
   notification.setSenderDisplayName('SF Robot');

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

}

Best Answer

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

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_Messaging_SingleEmailMessage_setWhatId.htm

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.