• Kinik, Gorky
  • NEWBIE
  • 0 Points
  • Member since 2010

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 1
    Replies
I am running into an issue in Apex outbound email. If I have an email message that is using a template, and that I am sending to a User (via setTargetObjectId), Apex won't let me set WhatId -- if I do, it gives me this error message

"System.EmailException: SendEmail failed. First exception on row 0; first error: INVALID_ID_FIELD, WhatId is not available for sending emails to UserIds."

Is there any easy way around this limitation? Obviously via workflow rules I am able to send emails to users that have a "What" context sent (for instance, send an email to Opportunity owner when stage change X occurs). Seems like a big limitation of the Apex email service to not allow this.

For now, I am intending to set up temporary Contact objects for Users who do not have them, just so I can send them email.

Here is the code that is hitting this error. "UserId" is the ID of a User object and "WhatId" is the ID of an Opportunity.

Code:
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
EmailTemplate template = [select Id from EmailTemplate where DeveloperName = :emailTemplateUniqueName];
mail.setTemplateId(template.Id);
mail.setReplyTo('no-reply@mycompany.com');
mail.setSenderDisplayName('Salesforce');
mail.setTargetObjectId(userId);
mail.setWhatId(whatId);
mail.setSaveAsActivity(false);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
 
Any pointers much appreciated. If (as I suspect) this is just a straight Apex issue and cannot be done, I'll open an Idea to fix it.

Jeremy Kraybill
Austin, TX