I'm in the process of writing a method that will send e-mails through Salesforce using E-mail templates. However, I'm getting the following error:

enter image description here

System.EmailException: SendEmail failed. First exception on row 0; first error: INVALID_ID_FIELD, Onl accounts, assets, campaigns, cases, opportunities, orders, productions, solutions and custom objects are allowed asWhatId.: [whatId, 003D000001tsKtd]

I'm currently iterating over sObject and obviously are setting a Contact Id as WhatId. Now I know I can simply do something like:

if (!(obj instanceOf Contact)) {

But what if something else gets passed in, like a Lead?

I figured the best thing to do would be to White List objects rather than include ones that'll cause problems. After all, I know I can only use Accounts, Assets, Campaigns etc...

Whilst I know I can do something like:

if ((obj instanceOf Account) || (obj instanceOf Asset) || (obj instanceOf Campaign)[...]) {

But then I was wondering, is there a better way? Also, how could I do something like (obj instanceOf Custom)? Does that exist?

Can I do something like (granted this will be wrong):

Set<sObject> whiteList = new Set<sObject>{

if (whiteList.get(obj)) {
  // Do something...

I guess I'm looking for the best, most future-proof way of handling this!


WhatId can be anything except Contact or Lead, so it'd be far more reasonable to simply check for that instead:

if(record.Id.getSobjectType() == Lead.SObjectType || record.Id.getSObjectType() == Contact.SObjectType) {
} else {

You can also describe the object to see if it's custom:

if(record.Id.getSobjectType().getDescribe().isCustom()) {

Of course, this won't cover all possible scenarios; it's possible that the object in question doesn't support tasks, in which case, this method may still fail, so I'm pretty sure you'll need a try-catch block anyways (but this should only occur in test/sandbox code/environments).

  • I guess it'd be more efficient to just exclude Contact and Lead objects and catch errors if a record doesn't, as you say, support Tasks. Thanks for this.
    – Dan Jones
    Nov 9 '16 at 9:45

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.