1

I am trying to send emails from trigger. Below is my code. I can see in the debug log that the email is sent out but I am not receiving any emails. When I ran the same code for sending out emails from developer console , it works absolutely fine. Please help to understand what can be wrong here.

trigger BlacklistWordFilterOnPost on FeedItem (before insert, before update) {
    String profileID = '00e280000028D6E';
    //String profileID = '00e0K000002ECcs';
    List<Messaging.Email> emailList = new List<Messaging.Email>();
    //can query on user and get the profile before calling the below method
    //Also it has to be on update as well
    Set<ID> setUserID = new Set<ID>();
    Map<ID,ID> mapUserID = new Map<ID,ID>();
    if(trigger.isbefore && (trigger.isInsert || trigger.isUpdate)){
        for(FeedItem  i : trigger.new){
            setUserID.add(i.ParentId);
        }
        for(User p : [Select id,ProfileID  from User where id in : setUserID]){
            mapUserID.put(p.id,p.ProfileID);
        }
        for(FeedItem  i : trigger.new){
            if(mapUserID.get(i.ParentId).equals(profileID)){
                try{
                    emailList.addAll(new BlacklistFilterDelegate().filterFeedItemsNew(trigger.new));
                }
                catch(Exception e){
                    system.debug('==== Exception  '+e.getMessage());
                }

            }  
        }
    }
    system.debug('==== emailList '+emailList);
    if(!emailList.isEmpty()){
        List<Messaging.SendEmailResult> results = Messaging.sendEmail(emailList);
       for(Messaging.SendEmailResult r: results ){
            if(!r.isSuccess()){
                system.debug('==== Error '+r.getErrors()[0].Message);
            }
            else{
                system.debug('Email is sent');
            }
        }
    }
}
  • I found the reason, that is, in filterFeedItemsNew method I have called addError method. When addError is there every thing that I am doing is getting rolled back. Can someone please let me know how to get over it. Thanks in advance. – Rijia Apr 6 '19 at 6:48
  • 1
    Hi, could you add this detail to the question please? Additionally, it is normal for an error during execution to prevent further processing, including notifications, since it prevents the DML operation's success. If the situation is not an error, then perhaps use of addError is incorrect. You might be able to have a partial continuation of trigger execution by ensuring you use Database.update/insert/upsert type DML operations with allOrNothing set false. – Phil W Apr 6 '19 at 8:20
  • My requirement is to restrict user from posting any inappropriate words and at the same time notifying system admin about the user who tried doing so. Do you have any suggestion as in how can I achieve this. – Rijia Apr 6 '19 at 12:31
1

Given that you want to send an email to an admin whilst blocking the posting of some user generated content, you do need to split the emailing into a separate session. I know there are some permission issues involved but what I do know is that you can raise a platform event and this is processed outside the current session. Basically you can add your error in the main transaction to prevent the DML operation whilst also creating and firing a platform event; the platform event will go through still. Your challenge is that an Apex trigger used to consume the event is run as the Automated Process user and this user's hard coded profile has some permission deficiencies. This may cause you trouble in sending the email, but worth a shot.

|improve this answer|||||
  • Hello, I tried it and now getting an exception which says "INSUFFICIENT_ACCESS_OR_READONLY, Not profiled to access this Org-wide Email Address". I have given access of the Oge-Wide Email to every profile in my org. – Rijia Apr 6 '19 at 18:25
  • Hello, I tried it and now getting an exception which says "INSUFFICIENT_ACCESS_OR_READONLY, Not profiled to access this Org-wide Email Address". I have given access of the Org-Wide Email to every profile in my org. Any solution for this exception? – Rijia Apr 6 '19 at 18:26
  • Hmmm. Probably not. This is what I was talking about with the permission deficiencies with the Automated Process user. This user uses a hard-coded profile that isn't visible and cannot be changed (from what I can determine). Perhaps using the Database.insert/update/upsert DML operations with allOrNothing false would dig you out of this hole? – Phil W Apr 6 '19 at 18:36
  • I can do DML with no issue, the issue is with sending out email with setOrgWideEmailAddressId. So, what I did, I have inserted the data into an object and then created a workflow on that object which triggers the email. – Rijia Apr 6 '19 at 19:16
  • BDW thanks a ton for giving me the idea. Really appreciate your suggestions. Will look forward to you for future help. :) – Rijia Apr 6 '19 at 19:18
0

Just to give an idea, not much a proper answer (I would prefer doing as a comment but I don't have enough rep).

I have been working today in a Email Handler class that is invoked from a trigger upon certain conditions, I had to use @Future(Callout=true) annotation for some reason (crashing with asynchronous procession of a process builder) and seems to be working, so my suggestion is, maybe you should try to build a Email Handler class with that annotation and call it from the trigger perhaps.

|improve this answer|||||
  • Hello, thanks for commenting. But I have tried that as well. But it is not working as well. I did the below. I got the job id in my log but the job submission is getting rolled back as well. if(!emailList.isEmpty()){ ID jobID = System.enqueueJob(new SendEmails(emailList)); system.debug('=== jobID '+jobID); } – Rijia Apr 6 '19 at 7:00
0

In case, if someone facing an issue now(v47.0) We do have an alternate solution.

Please have those addError method in try-catch-finally block. Finally has higher preferences so it would execute anyway. Now you can publish a Platform event. Now write a platform event trigger which will have the code to send the email.

Following is the dummy code working:

Account.trigger

trigger AccountTrigger on Account (before insert) {
    try{
        trigger.new[0].addError('bad');
    }
    catch(Exception e){
        System.debug('Test');
    }finally{
        System.debug('TestFinally');
        EventBus.publish(new SendEmail__e () ); //there is a platform event created named as - SendEmail         
    }
}

SendEmail - Platform Event trigger

trigger sendEmail on SendEmail__e (after insert) {
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        string[] to = new string[] {'trysocialme@gmail.com'};
        string[] cc = new string[] {'trysocialme@gmail.com'};

        email.setToAddresses(to);       
        email.setCcAddresses(cc);
        email.setInReplyTo('trysocialme@gmail.com');

        email.setSubject('Test Acct Mail ');

        email.setHtmlBody('Hello World');
        Messaging.SendEmailResult[] results = Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });
        System.debug('TestEmail0' + results);
}
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.