+ Start a Discussion
Faizan Ali 24Faizan Ali 24 

merge fields for send email class not displaying proper fields

Hi All,

I am still learning apex so I am sorry if there are any rookie mistakes. Learning as much as possible!

I have a controller that sends an email when a button is clicked. But the issue is that whenever the recipient receives the email the merge fields are not working at all. I have tried to follow documentation as much as possible but no luck.
 
public static void sendEmail(){
        
        Class_Register__c cont = [SELECT Id, Contact__c, Contact__r.Email, Contact__r.Id, Class__r.Name, Class__r.Event_Sub_Type__c FROM Class_Register__c];
        List<Class_Register__c> addCont = new List<Class_Register__c>();
        addCont.add(cont);
        
        List<String> toAddresses = new List<String>();
        
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        toAddresses.add(cont.Contact__r.Email);
        mail.setTargetObjectId(cont.Contact__r.Id);
        mail.setUseSignature(false);
        mail.setSaveAsActivity(false);
                
        EmailTemplate et = [SELECT Id, DeveloperName , Body, IsActive FROM EmailTemplate WHERE DeveloperName = 'Tools_Techniques_Webinar'];
             
        mail.setTemplateId(et.Id);
        mail.setPlainTextBody(et.Body);
        mail.setWhatId(cont.Contact__r.Id);
        mail.toAddresses = new String[]{cont.Contact__r.Email};
        Messaging.sendEmail(new Messaging.SingleEmailMessage[]{mail});
        
        
    }

 
ShirishaShirisha (Salesforce Developers) 
Hi Faizan,

Greetings!

I would suggest you to enable the debug logs and check,if you are able to get the data from the Contact Object to proceed further.

Reference:https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_debugging_debug_log.htm

Kindly mark it as best answer if it helps so that it can help others in the future.

Warm Regards,
Shirisha Pathuri