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
Prince VenkatPrince Venkat 

Apex Emails

HI 
Below is my code.
 
public class LeadEmail
{
public static void SendEmailTolead(list<lead> lstLead)
{
    if(! lstLead.isEmpty())
   {
        list<messaging.SingleEmailMessage> lstEmails = new list<messaging.SingleEmailMessage>();
    for(lead lr : lstLead)
    {
        messaging.SingleEmailMessage email = new messaging.SingleEmailMessage();
        string[] toEmailsIds = new string[]{lr.Email};
            email.settoAddresses(toEmailsIds);
        
        
        email.setSenderDisplayName('lead Record Creation Alert');
        
        email.setReplyTo('support@RFI.com');
        
        string emailsubject = 'congralutions'+lr.Name+'you have been registerd';
        
        email.setSubject(emailsubject);
        
        string emailHTMLContent = 'Dear'+lr.name+',<br/> <br/>'+
               '<br/><br/> here are your details... <br/><br/>'+
            
                '<br/> Your Company....'+lr.Company+
                '<br/> Your tile for the Role'+lr.Title+
                '<br/> your Status for The record'+lr.Status+
            'thanks & Regards';
        
        email.setHtmlBody(emailHTMLContent);
        
        lstEmails.add(email);
        
    }
   if(!lstEmails.isempty())
    {
        Messaging.sendEmail(lstEmails);    }
    
    } 
}
}

Execute window

list<lead> lstLead = [select id,name,email,company,title,status from lead];
LeadEmail.SendEmailTolead(lstLead);



Getting error 
Line: 38, Column: 1
System.EmailException: SendEmail failed. First exception on row 5; first error: SINGLE_EMAIL_LIMIT_EXCEEDED, Email limit exceeded: []

Any assistance

​​​​​​​Thanks in advance
Best Answer chosen by Prince Venkat
Maharajan CMaharajan C
Hi,

Add below line also:

email.setSaveAsActivity( false );
 
public class LeadEmail
{
public static void SendEmailTolead(list<lead> lstLead)
{
    if(! lstLead.isEmpty())
   {
        list<messaging.SingleEmailMessage> lstEmails = new list<messaging.SingleEmailMessage>();
    for(lead lr : lstLead)
    {
        messaging.SingleEmailMessage email = new messaging.SingleEmailMessage();
        string[] toEmailsIds = new string[]{lr.Email};
		email.settoAddresses(toEmailsIds);
        
        email.setTargetObjectId( UserInfo.getUserId() );
		
		email.setSaveAsActivity( false );

        email.setSenderDisplayName('lead Record Creation Alert');
        
        email.setReplyTo('support@RFI.com');
        
        string emailsubject = 'congralutions'+lr.Name+'you have been registerd';
        
        email.setSubject(emailsubject);
        
        string emailHTMLContent = 'Dear'+lr.name+',<br/> <br/>'+
               '<br/><br/> here are your details... <br/><br/>'+
            
                '<br/> Your Company....'+lr.Company+
                '<br/> Your tile for the Role'+lr.Title+
                '<br/> your Status for The record'+lr.Status+
            'thanks & Regards';
        
        email.setHtmlBody(emailHTMLContent);
        
        lstEmails.add(email);
        
    }
   if(!lstEmails.isempty())
    {
        Messaging.sendEmail(lstEmails);    }
    
    } 
}
}

Thanks,
Maharajan.C

All Answers

gaurav chaudhary 11gaurav chaudhary 11
Hi Prince,

There is a limit on the number of emails you can send from Apex, this is 5,000 per 24 hours.
Check this Link:-
https://help.salesforce.com/articleView?id=000323568&language=en_US&type=1&mode=1 (https://help.salesforce.com/articleView?id=000323568&language=en_US&type=1&mode=1)
In case you find any other issue please mention. 
If you find your Solution then mark this as the best answer. 

 
Naveen KNNaveen KN
Source: Salesforce Help
URL: https://help.salesforce.com/articleView?id=000331939&mode=1&sfdcIFrameOrigin=null&type=1

From time to time organizations may hit their SingleEmailMessage limit. When this happens, you will see the following email message:
 
 'SINGLE_EMAIL_LIMIT_EXCEEDED, The daily limit for the org would be exceeded by this request' 
 
Note: This limit applies only to email messages composed and sent through the API or Apex. This is not trackable currently in 'Setup.' However, there is a convenient way to track the limits and usage for the organization, using the Workbench tool.
 
Resolution
Use Workbench to track organization limits and usage
 
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.
Notes:
SingleEmailMessage calls are calculated for a 24 hour period from 12 midnight UTC (00:00) - the limit will reset to zero at this time each day.
Emails to each recipient are counted, such as addresses in the 'to' and 'cc' email fields.
There is a default value for each organization. the limit is not related to license count.

Have you tried checking the limits in your sandbox?

Naveen
Maharajan CMaharajan C
Hi Prince,

Add the setTargetObjectId as cusrrent user info. May it will help you.

email.setTargetObjectId( UserInfo.getUserId() );
 
public class LeadEmail
{
public static void SendEmailTolead(list<lead> lstLead)
{
    if(! lstLead.isEmpty())
   {
        list<messaging.SingleEmailMessage> lstEmails = new list<messaging.SingleEmailMessage>();
    for(lead lr : lstLead)
    {
        messaging.SingleEmailMessage email = new messaging.SingleEmailMessage();
        string[] toEmailsIds = new string[]{lr.Email};
		email.settoAddresses(toEmailsIds);
        
        email.setTargetObjectId( UserInfo.getUserId() );

        email.setSenderDisplayName('lead Record Creation Alert');
        
        email.setReplyTo('support@RFI.com');
        
        string emailsubject = 'congralutions'+lr.Name+'you have been registerd';
        
        email.setSubject(emailsubject);
        
        string emailHTMLContent = 'Dear'+lr.name+',<br/> <br/>'+
               '<br/><br/> here are your details... <br/><br/>'+
            
                '<br/> Your Company....'+lr.Company+
                '<br/> Your tile for the Role'+lr.Title+
                '<br/> your Status for The record'+lr.Status+
            'thanks & Regards';
        
        email.setHtmlBody(emailHTMLContent);
        
        lstEmails.add(email);
        
    }
   if(!lstEmails.isempty())
    {
        Messaging.sendEmail(lstEmails);    }
    
    } 
}
}


https://salesforce.stackexchange.com/questions/130447/how-can-be-avoided-error-single-email-limit-exceeded-email-limit-exceeded-if-nee

https://salesforce.stackexchange.com/questions/17133/single-email-limit-exceeded-salesforce-very-frequently/17143#17143


Thanks,
Maharajan.C
Prince VenkatPrince Venkat
Hi maharajan
When trying to implement your changes getting an error
Line: 40, Column: 1
System.EmailException: SendEmail failed. First exception on row 0; first error: INVALID_SAVE_AS_ACTIVITY_FLAG, saveAsActivity must be false when sending mail to users.: [saveAsActivity, true]
Maharajan CMaharajan C
Hi,

Add below line also:

email.setSaveAsActivity( false );
 
public class LeadEmail
{
public static void SendEmailTolead(list<lead> lstLead)
{
    if(! lstLead.isEmpty())
   {
        list<messaging.SingleEmailMessage> lstEmails = new list<messaging.SingleEmailMessage>();
    for(lead lr : lstLead)
    {
        messaging.SingleEmailMessage email = new messaging.SingleEmailMessage();
        string[] toEmailsIds = new string[]{lr.Email};
		email.settoAddresses(toEmailsIds);
        
        email.setTargetObjectId( UserInfo.getUserId() );
		
		email.setSaveAsActivity( false );

        email.setSenderDisplayName('lead Record Creation Alert');
        
        email.setReplyTo('support@RFI.com');
        
        string emailsubject = 'congralutions'+lr.Name+'you have been registerd';
        
        email.setSubject(emailsubject);
        
        string emailHTMLContent = 'Dear'+lr.name+',<br/> <br/>'+
               '<br/><br/> here are your details... <br/><br/>'+
            
                '<br/> Your Company....'+lr.Company+
                '<br/> Your tile for the Role'+lr.Title+
                '<br/> your Status for The record'+lr.Status+
            'thanks & Regards';
        
        email.setHtmlBody(emailHTMLContent);
        
        lstEmails.add(email);
        
    }
   if(!lstEmails.isempty())
    {
        Messaging.sendEmail(lstEmails);    }
    
    } 
}
}

Thanks,
Maharajan.C
This was selected as the best answer
Prince VenkatPrince Venkat
Thanks maharajan

Can you help me with a test class for it
Maharajan CMaharajan C
Use the below test class:

Add if there is any other fields are required to create the Lead. Change the lead status as per your org.
 
@isTest
public class LeadEmailTest {
    @isTest static void SendEmailToleadTest(){
        List<Lead> leadlist = new List<Lead>();
        for(integer i = 0; i < 5 ; i++ ){
            Lead leadrec = new Lead( FirstName = 'Test',status ='Open - Not Contacted', LastName = 'Sample' + i , Company = 'Testing Lead Company' + i, Email = 'Test' + i +  '@test.com');  
			leadlist.add(leadrec);
        }
        
        if(!leadlist.isEmpty())
            insert leadlist;
        
        Test.startTest();
        	LeadEmail.SendEmailTolead(leadlist);
        Test.stopTest();
    }
}

Thanks,
Maharajan.C