How to send html em...
 
Notifications
Clear all

[Solved] How to send html email from Apex using templates?

2 Posts
1 Users
0 Likes
868 Views
Posts: 205
 CWL
Admin
Issue starter
(@cwl)
Member
Joined: 11 years ago

Having trouble sending html email from Apex using classic email templates from the org.

Issue Tags
1 Reply
Posts: 205
 CWL
Admin
Issue starter
(@cwl)
Member
Joined: 11 years ago

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());
     }
}
Reply
Share: