setWhatId in salesforce using email template

Ritesh Mehandiratta picture Ritesh Mehandiratta · Jun 19, 2012 · Viewed 16.7k times · Source

i have to send an email to a user in salesforce using email template.this template contain merge field type of custom object.

 Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setTargetObjectId(user.get(0).id);


mail.setTargetObjectId(user.get(0).Id)
mail.setTemplateId(specifier.get(0).Template_id__c);
mail.saveAsActivity = false;
mail.setWhatId(custom_object.Id);

i read in documentation 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. The value must be one of the following types: Account Asset Campaign Case Contract Opportunity Order Product Solution Custom

but if we are sending email to a user not to contact then how to assign a custom object for merge field type in custom objects as in the above code

Answer

Ralph Callaway picture Ralph Callaway · Jun 20, 2012

This is a GIGANTIC whole in their email methods, and one that has annoyed me for years. Particularly given workflow email alerts seem to have no problem sending an email template for a user. Alas, you can't use setWhatId() if your target is a user. But you can vote for them to add that functionality,

I've worked around this I typically create a contact with the same name and email as the user, use it to send the email, and then delete it. This works well, although dealing with validation rules on the contact object can be a challenge. See their dev boards for a full discussion.