+ Start a Discussion
Avinash RaviAvinash Ravi 

Batch Apex not sending out email

I have this batch class that is not sending out an email when I query for an email template. The batch gets processed succcessfully with no errors but still doesn't send out an email.

It works when I use a plaintextbody instead of querying for a template. Can someone help me out?
 
global class sendEmailtoVolntr implements schedulable,Database.Batchable<sObject>,Database.Stateful
{

    global String Query = null;

    global sendEmailtoVolntr (){
  
       Query='Select Id,Name,For_Centre__c,For_Date__c,Leap_Centre__c,Leap_Centre__r.Name,Send_Email__c,Short_Description__c,Uploaded_By__c from Leap_Weekly_Curriculum__c where Send_Email__c = FALSE and For_Date__c >= TODAY';
   
    }
    
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator(Query);
    }
    
    global void execute(SchedulableContext SC){
        sendEmailtoVolntr sendEmail= new sendEmailtoVolntr ();
        database.executebatch(sendEmail,1);
     }
    
    global void execute(Database.BatchableContext BC, List<sObject> scope){
    
        List<Attachment> attachments = new List<Attachment> ();
        Map<Id,Attachment> attachmentId = new Map<Id,Attachment> ();
        Set<Id> LeapIds = new Set<Id> ();
        List<Leap_Weekly_Curriculum__c> leapCurrilist = new List<Leap_Weekly_Curriculum__c> ();
        List<Leap_Weekly_Curriculum__c> updateLeapList = new List<Leap_Weekly_Curriculum__c> ();
    
        for(sObject so : scope){ 
    
            Leap_Weekly_Curriculum__c leapCurri= (Leap_Weekly_Curriculum__c)so;
            LeapIds.add(leapcurri.Id);
            leapCurrilist.add(leapCurri);
           } 
        attachments = [SELECT Id,ParentId, Name, Body, ContentType FROM Attachment WHERE Parentid IN :LeapIds];
          //Assuming that there will be only one attachment for each Leap Curriculum record           
        for(Attachment att : attachments)
        {
            attachmentId.put(att.ParentId,att);
        }
        attachments.clear();
        
        for(Leap_Weekly_Curriculum__c LWC: leapCurrilist)
        {
            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
            List<Messaging.SingleEmailMessage> theEmails = new List<Messaging.SingleEmailMessage> ();
            List<Messaging.EmailFileAttachment> emailAttachments = new List<Messaging.EmailFileAttachment>();
            Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
            List<String> toAddresses = new List<String> ();
            String emailErrorReport = null;
            
            for(Volunteers__c vol: [Select Email__c from Volunteers__c WHERE Centre_Allocation__c includes(:LWC.Leap_Centre__r.Name)])
            toAddresses.add(vol.Email__c);
            //List<Volunteers__c> volListTeamp = [Select Email__c from Volunteers__c WHERE Centre_Allocation__c includes(:LWC.Leap_Centre__r.Name)];
            system.debug(toAddresses);
    
            efa.setFileName(attachmentId.get(LWC.Id).Name);
            efa.setBody(attachmentId.get(LWC.Id).Body);
            efa.setContentType(attachmentId.get(LWC.Id).ContentType);
            emailAttachments.add(efa);
            
            EmailTemplate template = [Select id, Body from EmailTemplate
                          where DeveloperName = 'Volunteer_Requirement_Update'];
            
            if(emailAttachments.size() > 0)
            {
                email.setToAddresses(toAddresses);
                //email.setSubject('test');
                email.setTemplateId(template.Id);
                email.setFileAttachments(emailAttachments);
                theEmails.add(email);
            }
            
            if(theEmails.size() > 0)
            {
                
                Messaging.SendEmailResult[] results = Messaging.sendEmail(theEmails,false);
                Messaging.SendEmailError[] errors = new List<Messaging.SendEmailError>();
                
                for( Messaging.SendEmailResult currentResult : results ) 
                {
                    errors = currentResult.getErrors();
                    if( null != errors ) 
                    {
                        for( Messaging.SendEmailError currentError : errors ) 
                        {
                            emailErrorReport = emailErrorReport + '(' +  currentError.getStatusCode() + ')' + currentError.getMessage() + '\r' ;
                        }
                    }
                }
    
                system.debug('error : ' + emailErrorReport);

             }

            System.debug('HEAP_SIZE Used:'+ Limits.getHeapSize()); 
            
            if(emailErrorReport != null){
                break;
            }
            else
            {
                LWC.send_EMail__c = TRUE;
                updateLeapList.add(LWC);  
            }
            
            if(updateLeapList.size()>0)
            update updateLeapList;
            
           /* if(emailErrorReport != null){
                System.abortJob(BC.getJobId()); 
                List<sObject> so = scope;
                Leap_Weekly_Curriculum__c lwcr= (Leap_Weekly_Curriculum__c )so[0];          
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                String[] toAddresseser = new String[] {'rahmeshms@outlook.com'};
                mail.setToAddresses(toAddresseser);
                mail.setSubject('Email Job is aborted'); 
                mail.setPlainTextBody('The send email job is aborted due to Leap Curriculum : '+lwcr.Name+' '+lwcr.Short_Description__c+ ' '+lwcr.Id+ 'Please check the error report and take action accordingly.\n\n\t Error - '+emailErrorReport);
                Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            }*/
       } 
       
   }
global void finish(Database.BatchableContext BC){

    }


    
        }

 
Mahesh DMahesh D
Hi Avinash,

Try to use below methods while using the Template.
 
email.setTargetObjectId(ObjectId); 
email.setWhatId(contactId);
Please do let me know if it helps.

Regards,
Mahesh
Amit Chaudhary 8Amit Chaudhary 8
Please check below post. I hope that will help you
1) http://amitsalesforce.blogspot.in/search/label/Email

Try code like below
List<contact> lstcon=[Select id from contact limit 2];
 List<Id> lstids= new List<Id>();
 for(Contact c:lstcon)
 {
  lstids.add(c.id);
 }
 EmailTemplate et=[Select id from EmailTemplate where name = 'EmailTemplatename' limit 1];
 
 Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
 mail.setTargetObjectIds(lstIds);
 mail.setSenderDisplayName('System Admin');
 mail.setTemplateId(et.id);
 Messaging.sendEmail(new Messaging.MassEmailMessage[] { mail });