Notifications
Clear all
Oct 21, 2021 3:46 pm
Having trouble sending html email from Apex using classic email templates from the org.
1 Reply
Oct 21, 2021 4:08 pm
Documentation: https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_classes_email_outbound_single.htm
DO NOT set these two values, so the subject and body will be retrieved from the template:
// mail.setSubject(et.subject);
// mail.setHTMLBody(et.Body);
Following is an example to send HTML email from Apex using templates in the Salesforce Org with quote record details. Merge fields in the classic email template are like: {!Quote.Opportunity_Amount__c}
for (Quote q: Qt){ EmailTemplate et = [SELECT Id, Subject, Body FROM EmailTemplate WHERE Name = 'My template name']; List toAddress = new List(); toAddress.add(q.Customer_Email__c); Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); mail.setTemplateId(et.Id); mail.setToAddresses(toAddress); mail.setTargetObjectId(q.ContactId); // This is the person receiving the email. Has to be User, Contact, Lead, or Person objects - or you will get INVALID_TYPE_FOR_OPERATION error. mail.setWhatId(q.Id); // Id of the Quote record. mail.setSaveAsActivity(false); mail.setUseSignature(false); List allmsg = new List(); allmsg.add(mail); try { Messaging.sendEmail(allmsg,false); return; } catch (Exception e) { System.debug(e.getMessage()); } }