function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
IvanWuIvanWu 

How to send Email with email template in apex

Hello everyone ,
I created a email template ,in this email template ,i set some merge fields ,they are reference from two object 
what i want to do is using this emai template  to send email via apex ,i have tried the SingleEmailMessage  class and i know i can set the value of merge field throughout the whatid ,
the problem is that i  can only set the whatid with only one vlaue ,this means the merge fields in email template can only receive the value from one object,which will cause some merge fields without values

so ,can anybody help me to resolve this problem? anys sugguestions would be appreciate, thanks.
Vinod ChoudharyVinod Choudhary
Hi  IvanWu,

This may help you.
Create Visualforce email template:
<messaging:emailTemplate subject="your subject" 
    recipientType="Contact" relatedToType="Object API name">

<messaging:plainTextEmailBody >

Mail content 


</messaging:attachment>

</messaging:emailTemplate>
Apex Class:
// In a separate class so that it can be used elsewhere
Global class emailHelper {

public static void sendEmail(ID recipient, ID candidate) {

  //New instance of a single email message
 Messaging.SingleEmailMessage mail = 
            new Messaging.SingleEmailMessage();
 
// Who you are sending the email to
   mail.setTargetObjectId(recipient);

   // The email template ID used for the email
   mail.setTemplateId('your template ID');
          
   mail.setWhatId(ContactId);    
   mail.setBccSender(false);
   mail.setUseSignature(false);
   mail.setReplyTo('reolttoemailID');
   mail.setSenderDisplayName('NAME');
   mail.setSaveAsActivity(false);  
 
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

    }  
}

Thanks
Vinod