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
SalesforceCrm AccountCRMSalesforceCrm AccountCRM 

how to send email to Account Owner from contract object in Batch Class

Can any one help me out . How to send an email to Account Owner from contract object in Batch Class.Im using templateid ,in target object im giving the contact id ,in whatid im sending the Account owner email ,but the Account owner is not getting any email.What im doing is correct .Any help very much appreciated.
Portion of the Code :
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.contact__r.Id)');
                     mail.setWhatId(c.Account.Owner.Manager.Email));
                     mail.setTemplateId('00X4B000000M3go');
                     mail.setSaveAsActivity(false);
                mailList.add(mail);
                 }
            }
             Messaging.sendEmail(mailList);
         }

 
Abhi_TripathiAbhi_Tripathi
Hi, 

I have tested this code now by running in my dev org, this will be working for sure, few small mistakes that you need to modify

1. At line no. 14 it should be Id, not string.
2. Line 15 an  extra ')'

Other things are fine, please make sure that you are querying the field in the start method those you are using in this method

Here is the code, slightly modified
List < Messaging.SingleEmailMessage > mailList = new List < Messaging.SingleEmailMessage > ();
for (Contract c: [Select Id, Email__c, Account.Owner.Manager.Email, contact__r.Id, Account.Owner.Email From Contract]) {
                 
                if (c.Email__c != null) {
                    
                    List < String > toAddresses = new List < String > ();
                     List < String > CcAddresses = new List < String > ();
                    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                    toAddresses.add('abhi.rec08@gmail.com');
                     ccAddresses.add(c.Account.Owner.Email);
                    //toAddresses.add(c.Account.Owner.Manager.Email);
                    // mail.setToAddresses(toAddresses);
                     mail.setCcAddresses(CcAddresses);
            		mail.setTargetObjectId(c.contact__r.Id);
                     mail.setWhatId(c.Account.Owner.Manager.Email);
                     mail.setTemplateId([Select Id From EmAILtEMPLATE lIMIT 1].iD);
                     mail.setSaveAsActivity(false);
                mailList.add(mail);
                 }
            }
             Messaging.sendEmail(mailList);

 
Srinivas SSrinivas S
In you Contract query you should include Account.Owner.Manager.Email.

------------
Thanks,
Srinivas
- Please mark as solution if your problem is resolved.
SalesforceCrm AccountCRMSalesforceCrm AccountCRM
@Abhi_Tripathi ,@Srinivasa Reddy S :Thanks for your response.It was a typo mistake in  the code.I would like to send the email to the Account owner.When we use TemplateId ,TargetObjectId ...in doc it states that it should be of (a contact , lead or user) and toAddresses doesnot work when we use template id.

This is the complete Code :
global class  NotificationEmailtoOwner 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(110);
        System.debug(Date.today().addDays(110));
        
        set<Id> setContractIds = new set<Id>();

        for(Contract_role__c objContract: [SELECT  Contract__c FROM Contract_role__c WHERE Role__c = 'Subscription Administrator' 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__c,ContractNumber,Contact__r.ID,Account_Owner_Email__c ,Account.ownerid FROM Contract  WHERE Id IN: setContractIds ]);
       
    }

    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();
               mail.setTargetObjectId(c.Account.OwnerID);
                 mail.setWhatId(c.Account.Owner.Email);
                 mail.setTemplateId('00X4B000000Dl3p');
                 mail.setSaveAsActivity(false);
                 mail.setSubject('Action Required - Renewal Alert Program Option');

                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.setccAddresses(CCAddresses);
        mail.setSubject('JOB Salesforce NotificationEmailtoOwner 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) {
         NotificationEmailtoOwner batchable = new  NotificationEmailtoOwner();
        database.executebatch(batchable);
    }
}

When i execute the code ,the Account owner is not recevining any email.But my goal is to send an email to the Account owner.The code is correct or is that something im missing out .Any help very much appreciated.