[SalesForce] Send Email from Apex Class in Sandbox not working

I'm wondering if anyone can help. I have a trigger that uses a helper class to send an email using the sendMail method. This code is written in one of my Sandboxes and when I test this functionality through my test classes and check the debug logs it looks like the send is successful.

I have also tested this by turning on the debug logs when doing a manual test through the Salesforce UI, again the debug logs show a successful send to my email address, however, I don't receive that email in my inbox.

I have tried to resolve this myself by looking up solutions from other people who have reported similar problems but so far I have been unsuccessful.

Deliverability is set to 'All Emails' and I have changed my email address in Sandbox to ensure that emails get sent to my actual email address. I have been able to receive other notification emails from my Sandbox but any time I try to run my apex code by inserting a duplicate lead with the same email address (this is one scenario), the addError appears on the record page and the logs indicate that the email was sent, but I don't receive the email and requesting email logs for the time it was sent don't show the email as being sent out of Salesforce.

Here's my code snippets:

if(existingLeadsByEmail.containsKey(l.Email){
    matchOnEmail = true;
    buildEmailMessage(existingLeadsByEmail.get(l.Email), l);    
    l.addError('A lead with this email address already exists.'); 
}

The buildEmailMessage creates the email and adds it to a list of emails to be sent after all incoming leads have been processed. Then to send the email I use the following:

if(allMails.size() > 0){
    List<Messaging.SendEmailResult> results = Messaging.sendEmail(allMails); 
    if(!results.get(0).isSuccess()){        
         System.debug('Send Error: ' + results.get(0).getErrors()[0].getMessage());     
    } else {        
         System.debug('Email Send Successful!');    
    } 
}

Any help on this would be greatly appreciated.

Many thanks guys!

Best Answer

You may want to check the "Access to Send Email" setting in your Setup -> Administration Setup -> Email Administration -> Delivery. Set it to "All email". I believe SendEmail does not work if this is set to "System email only".

I found in my sandbox, even though it was refreshed anew that this setting wasn't the same as my live environment, and caused the same issue as you are experiencing.

Related Topic