Introduction
This error is thrown while sending email using apex if you are setting User Id in target recipient: setTargetObjectId(usr.Id)
and also specifying target record id as: setWhatId(opp.Id)
. As per Salesforce documentation if you are passing record id in WhatId then you can only pass Contact Id in setTargetObjectId
.
Here is Salesforce article:
Workaround
- Send to Contacts: If you can send it to contact instead of user then it’s ok to use WhatId along with email template.
- Send to users with custom email body: If you are supposed to send it to Users only then do not set WhatId, instead prepare email body in apex and pass it as below:
Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage(); message.setTargetObjectId(targetId);//DIRECT USER message.setSubject('Email from Salesforce'); message.setPlainTextBody('A record has been updated'); message.saveAsActivity = false;
- Send to users with template: If you are supposed to send it to Users only then do not set WhatId, instead get the email content from template as below and set it as Body as below:
Messaging.SingleEmailMessage message = Messaging.renderStoredEmailTemplate(TEMPLATEID, USERID, RECORDID); String emailSubject = message.getSubject(); String emailTextBody = message.getPlainTextBody(); Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage(); message.setTargetObjectId(targetId);//DIRECT USER message.setSubject(subject); message.setPlainTextBody(emailTextBody); message.saveAsActivity = false;