Search code examples
salesforceapex-codeapex

Merge field value is not showing in email template when it send by apex


I have an email template which I want to send by apex class.I am getting an Email notification but merge field's value is not showing.I tried many solutions but not getting the result.Please, can anyone help me?

Here is the snap of my email template Email template

And apex code:-

global class sampleBatch implements Database.Batchable<sObject>{
global Database.QueryLocator start(Database.BatchableContext bc) {
    String query = 'Select id,Name from book__c;
    return Database.getQueryLocator(query);
}

global void execute(Database.BatchableContext bc, List<book__c> books){ 
    Map<Id, List<Case>> associatedCases = CaseHelperClass.getCase(new Map<Id,book__c>(books).keySet());
    Map<Id,book__c> bookMap= new Map<Id,book__c>(books);
    EmailTemplate emailTemplate = [SELECT Id,Subject,Description,HtmlValue,DeveloperName,Body FROM EmailTemplate WHERE DeveloperName =: 'sameple_template'];
    if(associatedCases <> null){
        for(Id bookId : associatedCases.keySet()){
            String headerAndAssociatedCases = 'CaseNumber,Type,Status,Subject,Description,CreatedDate\n';
            for(Case c : associatedCases.get(bookId)){
                headerAndAssociatedCases += c.CaseNumber+','+c.Type+','+c.Status+','+c.Subject+','+c.Description+','+c.CreatedDate+'\n';
            }
            Messaging.EmailFileAttachment csvAttachment = new Messaging.EmailFileAttachment();
            blob csvBlob = Blob.valueOf(headerAndAssociatedCases);
            csvAttachment.setFileName('Case.csv');
            csvAttachment.setBody(csvBlob);
            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
            list<string> toAddresses = new list<string>{name@test.com};
            email.setSubject(emailTemplate.Subject);
            email.setTemplateId(emailTemplate.Id);
            email.setPlainTextBody(emailTemplate.Body);
            email.setToAddresses(toAddresses);
            email.setFileAttachments(new Messaging.EmailFileAttachment[]{csvAttachment});
            Messaging.SendEmailResult [] result = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
       }
    }
}

global void finish(Database.BatchableContext bc){
    system.debug('Apex Job Done');
}}

Any help will be highly appreciable. Thank you!


Solution

  • Please refer to the requirements of the SingleEmail method:

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

    Specifically refer to the below:

    setTargetObjectId(targetObjectId)

    Required if using a template, optional otherwise. The ID of the contact, lead, or user to which the email will be sent. The ID you specify sets the context and ensures that merge fields in the template contain the correct data.

    setWhatId(whatId)

    If you specify a contact for the targetObjectId field, you can specify an optional whatId as well. This helps to further ensure that merge fields in the template contain the correct data.

    I don't see either of these methods in your code.