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
Eran VizelEran Vizel 

AddError and sending email doesn't work at same transaction

Hi all,

I'd like to prevent certain cases from coming in, and also notify the user about that.
Before insert trigger with AddError to prevent the case creation, also prevents the Messaging.SingleEmailMessage from being sent for some reason. Tried to run the message sending in a @future method, did not work either. Anybody has any idea or advice?

Thank you,
Allen li 3Allen li 3
Could you post your code?
Eran VizelEran Vizel

public static void blockEmailToCaseFromExternalDomains(List<Case> triggerNew)
        List<Case> lst_CasesForDelete = new List<Case>();
        for (Case c: triggerNew)

                if (c.Origin == 'email2case')
                    if (c.SuppliedEmail.split('@')[1] != '' && c.SuppliedEmail.split('@')[1] != '')
                        Utilities.sendTemplatedEmail(new List<String>{c.SuppliedEmail}, null, new List<String>{'', '', ''}, 'Email2Case_Retired_Auto_Response', '0032000000Vzw8X', null, '',false);            
                        c.addError('Cannot create external case with Email2Case');                        


public static void sendTemplatedEmail(String[] toRecipients, String[] ccRecipients, String[] bccRecipients, String templateApiName, ID targetObjId, Id whatId, String fromaddress, Boolean saveAsActivity) 
    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
    Id templateId = [select id, name from EmailTemplate where developername = : templateApiName].id;

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

James LoghryJames Loghry
Try adding the future method to the sendTemplatedEmail method to see if that works.  Also, you should move the call for the email method outside of a loop in order to properly bulkify your trigger.
Eran VizelEran Vizel
Thanks for your reply. Tried it, @future annotation does not resolve it. Also would like to point out that surrounding the "AddError" with TRY and calling the email method in CATCH - does not resolve it either. Any other ideas?