I want to send Email through Apex and attach 2 files.

Everything is working as expected but mail body part should come from Email Template but when I am getting the email, Email template part is not showing in mail body.

EmailTemplate et = [Select id,HtmlValue  
                        FROM EmailTemplate 
                        WHERE name = 'TEST' 
                        LIMIT 1];


enter image description here

I am not sure where I am doing wrong. I tried with changing the Encoding style and everything.

  • 1
    You should be using setTargetObjectId and/or setWhatId in order to make sure the template body merges correctly. – sfdcfox Sep 21 '17 at 18:44
  • setWhatId is used to specify the account, opportunity, case, contract, etc that the email is related to. This allows the merge fields to resolve correctly and also allows setSaveAsActivity to associate the task to the appropriate record's activity history related list. – sfdcfox Sep 21 '17 at 18:54
  • Hi @sfdcfox I tried using setTargetObjectId and setWhatId. My email templates pick values from one of the custom object named "Applications__c". What should be my value of setWhatId value? I tried to find online but I did not get any proper solutions – Sagar Sep 21 '17 at 21:23
  • Most likely, you need an Applications__c.Id value. Have you tried that? – sfdcfox Sep 21 '17 at 22:49

@sagar I was having the same issue. The issue I faced seems similar and is that the template is found but not returning any data. I suspect that your template does not have any text other than merge field syntax and we see no body because it is not merging properly.

Templated Apex Emails oddly don't merge data unless the recipient is a Lead, or Contact. If you want to send email templates via apex and have them merge data correctly from a record and send to arbitrary recipients then the only way I found is by using the savepoint and rollback trick along with setting whatid https://opfocus.com/sending-emails-in-salesforce-to-non-contacts-using-apex/

  • Thanks @SFDC_peter. But rather than going to Email Template, I choose to go with HTMLBody. I already have the html code, so just did little modification and used that itself. But Thanks for helping – Sagar Sep 25 '17 at 7:25

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.