Skip to main content
global class Test_Batch implements Database.Batchable<sObject> {

    public static final String STATUS_SCHEDULED = 'Scheduled';

    global Database.QueryLocator start(Database.BatchableContext BC) {          
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<Assignment__c> scope) {
        
        //Use Advance For - loop , as it retrives records from DB using Query More.
        for(Assignment__cAccount  ass : [Select Id, Name, Contact__c, Contact__r.Email , (Select Id         
                                  FROM Timecards__r Contact__r
                                  WHERE CreatedDate__cCreatedDate != LAST_N_DAYS:7Today()) 
                                  FROM Assignment__cAccount  Where Id IN: assignById])
        {   
            mapIdByContact.put(ass.Contact__c, ass.Contact__r.Email);   
        }
        EmailTemplate tempId = [SELECT Id FROM EmailTemplate WHERE Name = : 'Rejection Letter'];
        if(mapIdByContact.Size()>0){
        //Declare List to handle bulk
           List<Messaging.SingleEmailMessage> emailmessageList = new List<Messaging.SingleEmailMessage>(); 
           try{
            for(Id ids : mapIdByContact.keySet()){
                // Create Email and Send
                Messaging.SingleEmailMessage msg = new Messaging.SingleEmailMessage();
                msg.setTemplateId('Your Email Template Id');
                msg.setCcAddresses(new String[] {'sumit.banerjee@mtxb2b'maggi@gmail.com'});
                msg.setTargetObjectId(ids);
                //msg.setWhatId('Your Record Id if applicable');
                msg.setSaveAsActivity(false);
                //Remove statement from here
                //Messaging.sendEmail(new Messaging.SingleEmailMessage[] { msg });
                
                //instead Use
                emailmessageList.add(msg);
             }
             //Send Email using collection
             Messaging.sendEmail(emailmessageList);
           }catch(Exception e){
               System.debug('An exception occurred: ' + e.getMessage());
           }      
        }

    }   

    global void finish(Database.BatchableContext BC) {
        System.debug('------Query----> 4');
    } 
    }
global class Test_Batch implements Database.Batchable<sObject> {

    public static final String STATUS_SCHEDULED = 'Scheduled';

    global Database.QueryLocator start(Database.BatchableContext BC) {          
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<Assignment__c> scope) {
        
        //Use Advance For - loop , as it retrives records from DB using Query More.
        for(Assignment__c  ass : [Select Id, Name, Contact__c, Contact__r.Email , (Select Id         
                                  FROM Timecards__r 
                                  WHERE CreatedDate__c != LAST_N_DAYS:7) 
                                  FROM Assignment__c Where Id IN: assignById])
        {   
            mapIdByContact.put(ass.Contact__c, ass.Contact__r.Email);   
        }
        EmailTemplate tempId = [SELECT Id FROM EmailTemplate WHERE Name = : 'Rejection Letter'];
        if(mapIdByContact.Size()>0){
        //Declare List to handle bulk
           List<Messaging.SingleEmailMessage> emailmessageList = new List<Messaging.SingleEmailMessage>(); 
           try{
            for(Id ids : mapIdByContact.keySet()){
                // Create Email and Send
                Messaging.SingleEmailMessage msg = new Messaging.SingleEmailMessage();
                msg.setTemplateId('Your Email Template Id');
                msg.setCcAddresses(new String[] {'sumit.banerjee@mtxb2b.com'});
                msg.setTargetObjectId(ids);
                //msg.setWhatId('Your Record Id if applicable');
                msg.setSaveAsActivity(false);
                //Remove statement from here
                //Messaging.sendEmail(new Messaging.SingleEmailMessage[] { msg });
                
                //instead Use
                emailmessageList.add(msg);
             }
             //Send Email using collection
             Messaging.sendEmail(emailmessageList);
           }catch(Exception e){
               System.debug('An exception occurred: ' + e.getMessage());
           }      
        }

    }   

    global void finish(Database.BatchableContext BC) {
        System.debug('------Query----> 4');
    } 
    }
    global void execute(Database.BatchableContext BC, List<Assignment__c> scope) {

        for(Account  ass : [Select Id, Name, Contact__c, Contact__r.Email , (Select Id         
                                  FROM Contact__r
                                  WHERE CreatedDate != Today()) 
                                  FROM Account  Where Id IN: assignById])
        {   
            mapIdByContact.put(ass.Contact__c, ass.Contact__r.Email);   
        }
        EmailTemplate tempId = [SELECT Id FROM EmailTemplate WHERE Name = : 'Rejection Letter'];
        if(mapIdByContact.Size()>0){
        //Declare List to handle bulk
           List<Messaging.SingleEmailMessage> emailmessageList = new List<Messaging.SingleEmailMessage>(); 
           try{
            for(Id ids : mapIdByContact.keySet()){
                Messaging.SingleEmailMessage msg = new Messaging.SingleEmailMessage();
                msg.setTemplateId('Your Email Template Id');
                msg.setCcAddresses(new String[] {'maggi@gmail.com'});
                msg.setTargetObjectId(ids);
                msg.setSaveAsActivity(false);
                //Messaging.sendEmail(new Messaging.SingleEmailMessage[] { msg });

                emailmessageList.add(msg);
             }
             //Send Email using collection
             Messaging.sendEmail(emailmessageList);
           }catch(Exception e){
               System.debug('An exception occurred: ' + e.getMessage());
           }      
        }

    }   
added 94 characters in body
Source Link

Sales force has limitations when it comes to sending emails
You will receive error SINGLE_EMAIL_LIMIT_EXCEEDED if you have consumed your daily limit

REF : Daily Limits for Email Alerts
The daily limit for emails sent through email alerts is 1,000 per standard Salesforce license per org—except for free Developer Edition and trial orgs, where the daily workflow email limit is 15. The overall org limit is 2,000,000. This limit applies to emails sent through email alerts in workflow rules, approval processes, flows, processes, or the REST API.

REF : Checking the SingleEmailMessage limit

Workbench

  1. Ensure you are logged into the organization where you want to verify your limits.
  2. Navigate to https://workbench.developerforce.com/login.php
  3. Accept any oauth prompts to complete authentication
  4. On the Jump to picklist select "REST Explorer".
  5. Click Select.
  6. From the options presented select: /services/data/vXX.0/limits
  7. Click "Execute".
  8. Select the SingleEmail area to view the daily maximum and remaining calls.

Note: SingleEmailMessage calls are calculated for a 24 hour period from 12 midnight UTC (00:00) and the limit will reset to zero at this time each day. Emails to each recipient of an email are counted such as addresses in the "to" and "cc". There is a default value for each organization the limit is not related to license count.

REF : Email Limits
Using the API or Apex, you can send single emails to a maximum of 5,000 external email addresses per day based on Greenwich Mean Time (GMT). Single emails sent using the email author or composer in Salesforce don't count toward this limit. There’s no limit on sending individual emails to contacts, leads, person accounts, and users in your org directly from account, contact, lead, opportunity, case, campaign, or custom object pages.
When sending single emails, keep in mind:

Sales force has limitations when it comes to sending emails

Daily Limits for Email Alerts
The daily limit for emails sent through email alerts is 1,000 per standard Salesforce license per org—except for free Developer Edition and trial orgs, where the daily workflow email limit is 15. The overall org limit is 2,000,000. This limit applies to emails sent through email alerts in workflow rules, approval processes, flows, processes, or the REST API.

Email Limits
Using the API or Apex, you can send single emails to a maximum of 5,000 external email addresses per day based on Greenwich Mean Time (GMT). Single emails sent using the email author or composer in Salesforce don't count toward this limit. There’s no limit on sending individual emails to contacts, leads, person accounts, and users in your org directly from account, contact, lead, opportunity, case, campaign, or custom object pages.
When sending single emails, keep in mind:

Sales force has limitations when it comes to sending emails
You will receive error SINGLE_EMAIL_LIMIT_EXCEEDED if you have consumed your daily limit

REF : Daily Limits for Email Alerts
The daily limit for emails sent through email alerts is 1,000 per standard Salesforce license per org—except for free Developer Edition and trial orgs, where the daily workflow email limit is 15. The overall org limit is 2,000,000. This limit applies to emails sent through email alerts in workflow rules, approval processes, flows, processes, or the REST API.

REF : Checking the SingleEmailMessage limit

Workbench

  1. Ensure you are logged into the organization where you want to verify your limits.
  2. Navigate to https://workbench.developerforce.com/login.php
  3. Accept any oauth prompts to complete authentication
  4. On the Jump to picklist select "REST Explorer".
  5. Click Select.
  6. From the options presented select: /services/data/vXX.0/limits
  7. Click "Execute".
  8. Select the SingleEmail area to view the daily maximum and remaining calls.

Note: SingleEmailMessage calls are calculated for a 24 hour period from 12 midnight UTC (00:00) and the limit will reset to zero at this time each day. Emails to each recipient of an email are counted such as addresses in the "to" and "cc". There is a default value for each organization the limit is not related to license count.

REF : Email Limits
Using the API or Apex, you can send single emails to a maximum of 5,000 external email addresses per day based on Greenwich Mean Time (GMT). Single emails sent using the email author or composer in Salesforce don't count toward this limit. There’s no limit on sending individual emails to contacts, leads, person accounts, and users in your org directly from account, contact, lead, opportunity, case, campaign, or custom object pages.
When sending single emails, keep in mind:

added 564 characters in body
Source Link

Update your code as follow, I have added comments:

global class Test_Batch implements Database.Batchable<sObject> {

    public static final String STATUS_SCHEDULED = 'Scheduled';

    global Database.QueryLocator start(Database.BatchableContext BC) {
        System.debug('------Query----> 2');
        String query ='SELECT Id, Name, Contact__c FROM Assignment__c WHERE Status__c = \'STATUS_SCHEDULED\' AND Contact__c != NULL';
        System.debug('------Query---->'+query);
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<Assignment__c> scope) {
        System.debug('------Query----> 3');
        Set<Id> assignById = new Set<Id>();
        Map<Id,String> mapIdByContact = new Map<Id,String>();

        for(Assignment__c assig: scope)
        {
            assignById.add(assig.Id);   
        }   
        
        //Use Advance For - loop , as it retrives records from DB using Query More.
        for(Assignment__c  ass : [Select Id, Name, Contact__c, Contact__r.Email , (Select Id         
                                  FROM Timecards__r 
                                  WHERE CreatedDate__c != LAST_N_DAYS:7) 
                                  FROM Assignment__c Where Id IN: assignById])
        {   
            mapIdByContact.put(ass.Contact__c, ass.Contact__r.Email);   
        }
        EmailTemplate tempId = [SELECT Id FROM EmailTemplate WHERE Name = : 'Rejection Letter'];
        if(mapIdByContact.Size()>0){
        //Declare List to handle bulk
           List<Messaging.SingleEmailMessage> emailmessageList = new List<Messaging.SingleEmailMessage>(); 
           try{
            for(Id ids : mapIdByContact.keySet()){
                // Create Email and Send
                Messaging.SingleEmailMessage msg = new Messaging.SingleEmailMessage();
                msg.setTemplateId('Your Email Template Id');
                msg.setCcAddresses(new String[] {'[email protected]'});
                msg.setTargetObjectId(ids);
                //msg.setWhatId('Your Record Id if applicable');
                msg.setSaveAsActivity(false);
                //Remove statement from here
                //Messaging.sendEmail(new Messaging.SingleEmailMessage[] { msg });
                
                //instead Use
                emailmessageList.add(msg);
             }
             //Send Email using collection
             Messaging.sendEmail(emailmessageList);
           }catch(Exception e){
               System.debug('An exception occurred: ' + e.getMessage());
           }      
        }

    }   

    global void finish(Database.BatchableContext BC) {
        System.debug('------Query----> 4');
    } 
    }

Sales force has limitations when it comes to sending emails
 

Daily Limits for Email Alerts
The daily limit for emails sent through email alerts is 1,000 per standard Salesforce license per org—except for free Developer Edition and trial orgs, where the daily workflow email limit is 15. The overall org limit is 2,000,000. This limit applies to emails sent through email alerts in workflow rules, approval processes, flows, processes, or the REST API.

Email Limits
Using the API or Apex, you can send single emails to a maximum of 5,000 external email addresses per day based on Greenwich Mean Time (GMT). Single emails sent using the email author or composer in Salesforce don't count toward this limit. There’s no limit on sending individual emails to contacts, leads, person accounts, and users in your org directly from account, contact, lead, opportunity, case, campaign, or custom object pages.
When sending single emails, keep in mind:

Update your code as follow:

global class Test_Batch implements Database.Batchable<sObject> {

    public static final String STATUS_SCHEDULED = 'Scheduled';

    global Database.QueryLocator start(Database.BatchableContext BC) {
        System.debug('------Query----> 2');
        String query ='SELECT Id, Name, Contact__c FROM Assignment__c WHERE Status__c = \'STATUS_SCHEDULED\' AND Contact__c != NULL';
        System.debug('------Query---->'+query);
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<Assignment__c> scope) {
        System.debug('------Query----> 3');
        Set<Id> assignById = new Set<Id>();
        Map<Id,String> mapIdByContact = new Map<Id,String>();

        for(Assignment__c assig: scope)
        {
            assignById.add(assig.Id);   
        }   
        
        //Use Advance For - loop , as it retrives records from DB using Query More.
        for(Assignment__c  ass : [Select Id, Name, Contact__c, Contact__r.Email , (Select Id         
                                  FROM Timecards__r 
                                  WHERE CreatedDate__c != LAST_N_DAYS:7) 
                                  FROM Assignment__c Where Id IN: assignById])
        {   
            mapIdByContact.put(ass.Contact__c, ass.Contact__r.Email);   
        }
        EmailTemplate tempId = [SELECT Id FROM EmailTemplate WHERE Name = : 'Rejection Letter'];
        if(mapIdByContact.Size()>0){
        //Declare List to handle bulk
           List<Messaging.SingleEmailMessage> emailmessageList = new List<Messaging.SingleEmailMessage>(); 
           try{
            for(Id ids : mapIdByContact.keySet()){
                // Create Email and Send
                Messaging.SingleEmailMessage msg = new Messaging.SingleEmailMessage();
                msg.setTemplateId('Your Email Template Id');
                msg.setCcAddresses(new String[] {'[email protected]'});
                msg.setTargetObjectId(ids);
                //msg.setWhatId('Your Record Id if applicable');
                msg.setSaveAsActivity(false);
                //Remove statement from here
                //Messaging.sendEmail(new Messaging.SingleEmailMessage[] { msg });
                
                //instead Use
                emailmessageList.add(msg);
             }
             //Send Email using collection
             Messaging.sendEmail(emailmessageList);
           }catch(Exception e){
               System.debug('An exception occurred: ' + e.getMessage());
           }      
        }

    }   

    global void finish(Database.BatchableContext BC) {
        System.debug('------Query----> 4');
    } 
    }

Sales force has limitations when it comes to sending emails
 Email Limits
Using the API or Apex, you can send single emails to a maximum of 5,000 external email addresses per day based on Greenwich Mean Time (GMT). Single emails sent using the email author or composer in Salesforce don't count toward this limit. There’s no limit on sending individual emails to contacts, leads, person accounts, and users in your org directly from account, contact, lead, opportunity, case, campaign, or custom object pages.
When sending single emails, keep in mind:

Update your code as follow, I have added comments:

global class Test_Batch implements Database.Batchable<sObject> {

    public static final String STATUS_SCHEDULED = 'Scheduled';

    global Database.QueryLocator start(Database.BatchableContext BC) {          
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<Assignment__c> scope) {
        
        //Use Advance For - loop , as it retrives records from DB using Query More.
        for(Assignment__c  ass : [Select Id, Name, Contact__c, Contact__r.Email , (Select Id         
                                  FROM Timecards__r 
                                  WHERE CreatedDate__c != LAST_N_DAYS:7) 
                                  FROM Assignment__c Where Id IN: assignById])
        {   
            mapIdByContact.put(ass.Contact__c, ass.Contact__r.Email);   
        }
        EmailTemplate tempId = [SELECT Id FROM EmailTemplate WHERE Name = : 'Rejection Letter'];
        if(mapIdByContact.Size()>0){
        //Declare List to handle bulk
           List<Messaging.SingleEmailMessage> emailmessageList = new List<Messaging.SingleEmailMessage>(); 
           try{
            for(Id ids : mapIdByContact.keySet()){
                // Create Email and Send
                Messaging.SingleEmailMessage msg = new Messaging.SingleEmailMessage();
                msg.setTemplateId('Your Email Template Id');
                msg.setCcAddresses(new String[] {'[email protected]'});
                msg.setTargetObjectId(ids);
                //msg.setWhatId('Your Record Id if applicable');
                msg.setSaveAsActivity(false);
                //Remove statement from here
                //Messaging.sendEmail(new Messaging.SingleEmailMessage[] { msg });
                
                //instead Use
                emailmessageList.add(msg);
             }
             //Send Email using collection
             Messaging.sendEmail(emailmessageList);
           }catch(Exception e){
               System.debug('An exception occurred: ' + e.getMessage());
           }      
        }

    }   

    global void finish(Database.BatchableContext BC) {
        System.debug('------Query----> 4');
    } 
    }

Sales force has limitations when it comes to sending emails

Daily Limits for Email Alerts
The daily limit for emails sent through email alerts is 1,000 per standard Salesforce license per org—except for free Developer Edition and trial orgs, where the daily workflow email limit is 15. The overall org limit is 2,000,000. This limit applies to emails sent through email alerts in workflow rules, approval processes, flows, processes, or the REST API.

Email Limits
Using the API or Apex, you can send single emails to a maximum of 5,000 external email addresses per day based on Greenwich Mean Time (GMT). Single emails sent using the email author or composer in Salesforce don't count toward this limit. There’s no limit on sending individual emails to contacts, leads, person accounts, and users in your org directly from account, contact, lead, opportunity, case, campaign, or custom object pages.
When sending single emails, keep in mind:

Source Link
Loading