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
computing cloudcomputing cloud 

HTML Email template Merge fields are not working in Batch class

Hello ,
Based on the requirement i have created few html email templates with the merge fields .When i use the templateid in the batch class and execute the batch class,the email which i get doesnot display the merge fields value .What may be issue .Any help very much appreciated.
Here is the code used to send an email notification for the 30 days .
Batch Class and Schedule Class :
global class ThirtyDaysNotificationEmail implements Database.Batchable < sObject >, Schedulable, Database.Stateful {
    global List<String> errorMessages = new List<String>();
    global Database.QueryLocator start(Database.BatchableContext bc) {
        
        Date ed = Date.today().addDays(30);
        System.debug(Date.today().addDays(30));
        
        set<Id> setContractIds = new set<Id>();

        for(Contract_role__c objContract: [SELECT  Contract__c FROM Contract_role__c WHERE Role__c = 'SA' AND Contract__r.EndDate =: ed]) {
            setContractIds.add(objContract.Contract__c);
        }
        
         return Database.getQueryLocator([Select  id, Contract_Name__c , EndDate ,Contact_Email__c, Contract_End_Date_2__c,  Account.Owner.Email ,Account.Owner.Manager.Email,Owner.Email,CustomerSignedId,OwnerId FROM Contract  WHERE Id IN: setContractIds AND SRR__c ='YES' AND Status__c IN('In Pipe','Pushed Forward ') AND Renewal_Status__c NOT IN ('Renewed','Renewed Lost')]);
    }

    global void execute(Database.BatchableContext bc, List < Contract > recs) {
        List < Messaging.SingleEmailMessage > mailList = new List < Messaging.SingleEmailMessage > ();
        for (Contract c: recs) {
            if (c.Contact_Email__c != null) {
                List < String > toAddresses = new List < String > ();
                List < String > CcAddresses = new List < String > ();
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                toAddresses.add(c.Contact_Email__c);
                ccAddresses.add(c.Account.Owner.Email);
               // toAddresses.add(c.Account.Owner.Manager.Email);
                mail.setToAddresses(toAddresses);
                mail.setCcAddresses(CcAddresses);
               // mail.setTargetObjectId(c.CustomerSignedId);
                mail.setTargetObjectId(c.OwnerId);
               // mail.setWhatId(c.Id);
                mail.setTemplateId('00X4B000000M3g7');
                mail.setSaveAsActivity(false);
               // mail.setSubject('Notification Before 100 Days of Contract End Date to Account Executive and Manager');
               // String messageBody = '<html><body>Hi ,The Contract Named ' + c.Contract_Name__c  + ',<br>Will get Expired within 100 Days . <br>Kindly take approriate action to inform the Customer.<br><br><b>Regards,</b><br>ADP</body></html>';
               // mail.setHtmlBody(messageBody);
                mailList.add(mail);
            }
        }
        Messaging.sendEmail(mailList);
    }

    global void finish(Database.BatchableContext bc) {
        AsyncApexJob aaj = [Select Id, Status, NumberOfErrors, JobItemsProcessed, MethodName, TotalJobItems, CreatedBy.Email from AsyncApexJob where Id =:BC.getJobId()];
        
        // Send an email to the Apex job's submitter notifying of job completion.
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {aaj.CreatedBy.Email};
        mail.setToAddresses(toAddresses);
        mail.setSubject('JOB Salesforce Thirty Days NotificationEmailtoCustomer Finished: ' + aaj.Status);
        String bodyText='Total Job Items ' + aaj.TotalJobItems + ' Number of records processed ' + aaj.JobItemsProcessed + ' with '+ aaj.NumberOfErrors + ' failures.\n';
        bodyText += 'Number of Error Messages ' + errorMessages.size() + '\n';
        bodyText += 'Error Message' + String.join(errorMessages, '\n');
        mail.setPlainTextBody(bodyText);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
    
    global void execute(SchedulableContext SC) {
        NotificationEmailtoAccountExecutive batchable = new NotificationEmailtoAccountExecutive();
        database.executebatch(batchable);
    }
}
HTML Email template Created :
User-added image

The output which i get without the merge fields is :
User-added image
Any help very much appreciated.
hari0853701703454959hari0853701703454959
Plz help  above scenario.
SalesforceCrm AccountCRMSalesforceCrm AccountCRM
@hari0853701703454959 : Refer this link which has answer for the merge fields.
http://salesforce.stackexchange.com/questions/118857/sendemail-failed-required-field-missing-missing-targetobjectid-with-template/118876#118876
hari0853701703454959hari0853701703454959
Hi, Please find the below Batch Apex and help me write test class for below code.It's very urgent. global class Batch_to_SentEmailNotify implements Database.Batchable { global Database.QueryLocator start(Database.BatchableContext BC) { string s='Blocked'; String query = 'Select Id,Resort_Master__r.Name,Executive_Name__r.Email__c,Name_of_the_Guest__c,Company_Name__c,Block_Release_Date__c,Check_In__c,Check_Out__c,Total_Number_of_Rooms_Booked__c,CV_Number__c,Booking_Status__c,Source__c,Market_Segment__c,Executive_Name__r.Name,createdDate FROM Non_Member_Booking_Request__c where Booking_Status__c=: s AND Email_Sent_Test__c != TRUE'; return Database.getQueryLocator(query); } global void execute(Database.BatchableContext BC, List scope) { ListlstNMBReq = new list< Non_Member_Booking_Request__c>(); for(Non_Member_Booking_Request__c c : scope) { system.debug('++++++++++++++system.today+2 ++++++++++++++'+system.today()+2); string email = c.Executive_Name__r.Email__c; // date d1 = date.ValueOf(c.Check_In__c); string date1 = (c.Check_In__c).format(); system.debug('date1'+date1); // date d2 = date.ValueOf(c.Check_Out__c); string date2 = (c.Check_Out__c).format(); system.debug('date2'+date2); string date3 = (c.Block_Release_Date__c).format(); system.debug('date3'+date3); string date4 = (c.createdDate).format('dd/MM/yyyy'); system.debug('date4'+date4); Integer tot = Integer.ValueOf(c.Total_Number_of_Rooms_Booked__c); if(email !=null &&(system.today()+2 == c.Check_In__c)) { Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); // Messaging.InboundEnvelope env = new Messaging.InboundEnvelope(); mail.setUseSignature(false); mail.setToAddresses(new String[] { email}); //env.fromAddress ='harishk968@gmail.com'; mail.setSenderDisplayName('Apex Batch Processing Module'); mail.setSubject('Your Block Status'); mail.setReplyTo('reddy.prasad@sterlingholidays.com'); mail.setCcAddresses(new String[] {'harishk968@gmail.com',' indupuru.hareesh@gmail.com' }); mail.setHtmlBody('Dear '+c.Executive_Name__r.Name + ',

' +'Your current tentative blocks are as under with the respective block release dates.

' +'
Name of Resort First Name Company /Travel Agent Block Release Date Check In Check Out Rooms CV-Number Booking Status Source Market Segment Executive Name Created Date
' +'
'+'
'+ c.Resort_Master__r.Name +'
'+'
'+ c.Name_of_the_Guest__c +'
'+'
'+ c.Company_Name__c +'
'+'
'+ date3 +'
'+'
'+ date1 +'
'+'
'+ date2 +'
'+'
'+ tot +'
'+'
'+ c.CV_Number__c+'
'+'
'+ c.Booking_Status__c+'
'+'
'+ c.Source__c +'
'+'
'+ c.Market_Segment__c +'
'+'
'+ c.Executive_Name__r.Name+'
'+'
'+ date4 +'
'+' ' +'
Please let us know of the payment and contract details in order to regularize & confirm the same on the system. In the event of the same not being regularized, the block will be automatically released from the system and further rooms will be subject to availability.' +'

Thank You.

' +'Regards
' +'SanjeeviKumar G'); Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail}); system.debug('@@@@@@@@@@@@@@@mail@@@@@@@@@@@@@@@'+mail); c.Email_Sent_Test__c = TRUE; lstNMBReq.add(c); } if(lstNMBReq.size() > 0){ update lstNMBReq; } } } global void finish(Database.BatchableContext BC) { } } Regards, *Hareesh*
computing cloudcomputing cloud
@hari0853701703454959 :Hey Hari ,just refer the link ...you can find the test class and modify it as per your requirement.
http://salesforce.stackexchange.com/questions/119599/test-class-is-not-getting-covered-messaging-singleemailmessage-in-batch-class/119664#119664