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
sandersensandersen 

Outbound emails and exception handling

I'm trying to send an outbound email to a developer when I handle an exception in Apex, but I am unsuccessful. I can send outbound emails, but if I try to addError() it seems that outbound emails are not sent out.

 

Here is my testing trigger:

 

 

trigger contactExceptionTest on Account (after insert) {

list<Account> myAccounts = new List<Account>();

try{

throw new MyException('this is bad');

} catch (MyException e){

trigger.new[0].addError('erroor!!');

} finally {

Messaging.SingleEmailMessage mail2= new Messaging.SingleEmailMessage();

String[] toAddresses2 = new String[] {'steve@gokubi.com'};

mail2.setToAddresses(toAddresses2);

mail2.setReplyTo('steve@gokubi.com');

// Specify the name used as the display name.

mail2.setSenderDisplayName('Salesforce Support');

// Specify the subject line for your email2 address.

mail2.setSubject('fake after');

// Set to True if you want to BCC yourself on the email2.

mail2.setBccSender(false);

// Optionally append the salesforce.com email2 signature to the email2.

// The email2 address of the user executing the Apex Code will be used.

 

mail2.setUseSignature(false);

// Specify the text content of the email2.

mail2.setPlainTextBody('fake email2');

mail2.setHtmlBody('fake email');

// Send the email you have created.

Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail2 });

}

}

 

This adds the 'erroor!!' message to the screen but doesn't send the email. If I comment out the addError(), the email goes out as expected.

 

Does addError() stop all outbound emails from going out, or is it broader than that? Does addError() stop execution of my trigger code generally?

 

Thanks,

 

Steve 

 

Best Answer chosen by Admin (Salesforce Developers) 
stwstw

Hi Steve,

 

When you use addError, you prevent the transaction from being committed. And, per the Apex documentation, emails are not sent until the Apex transaction is committed.

 

Hope this helps,

Sarah