1

I am trying to send bulk email by the use of batch class.. my batch class is executed successfully but email are not going.

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);   
    }

    List<Assignment__c> listAssigByTimecard = new List<Assignment__c>();

    for(Assignment__c : listAssigByTimecard : [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){
       try{
        for(Id ids : mapIdByContact.keySet()){
            Messaging.SingleEmailMessage msg = new Messaging.SingleEmailMessage();
            msg.setTemplateId('Your Email Template Id');
            msg.setCcAddresses(new String[] {'[email protected]'});
            msg.setTargetObjectId(ids);
            msg.setSaveAsActivity(false);
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { msg });
        }
       }catch(Exception e){
           System.debug('An exception occurred: ' + e.getMessage());
       }      
    }  
}  
7
  • What did you learn from the debug logs e.g. System.debug('An exception occurred: ' + e.getMessage());?
    – Keith C
    Commented Jan 12, 2018 at 10:03
  • didn't get any logs Commented Jan 12, 2018 at 10:04
  • That would say the code is not running at all. Are you sure you had logging configured to be on?
    – Keith C
    Commented Jan 12, 2018 at 10:09
  • not sure, from where I can set logging configured ?? Commented Jan 12, 2018 at 10:13
  • See e.g. help.salesforce.com/….
    – Keith C
    Commented Jan 12, 2018 at 10:17

1 Answer 1

1

Update your code as follow, I have added comments:

    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[] {'[email protected]'});
                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());
           }      
        }

    }   

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:

  • You can specify up to 100 recipients for the To field and up to 25 recipients for the CC and BCC fields in each SingleEmailMessage.
  • If you use SingleEmailMessage to email your org’s internal users, specifying the user’s ID in setTargetObjectId means the email doesn’t count toward the daily limit. However, specifying internal users’ email addresses in setToAddresses means the email does count toward the limit.

If there is limit available and if still email is not going out check

Email Administration >> Deliverability >> Select Access level >> instead of system Email select All Emails. enter image description here

If this doesn't solve your problem
Go for testing Testing Deliverability
To test email deliverability permission needed: “Modify All Data”
1. From Setup, enter Test Deliverability in the Quick Find box, then select Test Deliverability.
2. Enter your business email address. Click Send. Salesforce sends a test message from all IP addresses to your business email address. Each test message specifies the IP address from which it was sent.
3. To make sure that you received all test messages, check your business email account.
4. If you didn’t receive all the test messages, your organization’s email administrator must whitelist the Salesforce IP ranges on your organization’s email server. Whitelisting an IP address allows the email server to receive email from an IP address that is otherwise blocked. For a current list of Salesforce IP ranges, see What are the Salesforce IP Addresses to whitelist?. Salesforce maintains separate IP addresses for inbound and outbound email. The IP addresses used for outbound email don’t accept inbound email connections.

REF: Test the Deliverability of Emails Sent Through Salesforce

7
  • Thanks a lots, I have gone through your code and It looks awesome, So I updated my code as per ur code but still not receiving email. I have also checked all the setting which you mentioned above. Commented Jan 12, 2018 at 11:00
  • did you get any exception ? did you check the email Limit through workbench? Commented Jan 12, 2018 at 11:01
  • No, I didn't and also received batch success id Commented Jan 12, 2018 at 11:04
  • did you check the debug logs ? did you see anything which has some error ? is your code executing this line Messaging.sendEmail(emailmessageList); Commented Jan 12, 2018 at 11:07
  • You might have seen something in your logs like "SerialBatchApexRangeChunkHandler" , check if it has any error Commented Jan 12, 2018 at 11:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .