Search code examples
emailsalesforceapexemail-templatessalesforce-communities

Merge fields do not appear when sending an email with apex using a template


I am sending a template email to some users, the template contains a merge field {{!Opportunity.custom__c}}. When sending it, the value of the field does not appear.

Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
    email.setTemplateId(et.Id); // Email Template ID
    email.setTargetObjectId(user.Id); // User ID to send
    //email.setWhatId(opp.Id); !Error!
    email.setSaveAsActivity(false);
    emails.add(email);  

So I want to know if there is any way to pass information about the opportunity to the template? Shouldn't I use a template?

I have searched and they say to add email.setWhatId(opportunity.Id), when adding it it gives me the following error: INVALID_ID_FIELD, WhatId is not available for sending emails to UserIds.: [whatId, XXXXXXXXXXX].


Solution

  • 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

    I don't think you can achieve this without custom coding the message. public Void setHtmlBody(String htmlBody) I would try and use this instead of the templates.