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
aaronbaumanaaronbauman 

AfterInsert, AfterUpdate, and emails - how is it supposed to work?

I have a AfterInsert + AfterUpdate trigger designed to send an email under certain criteria.

After it was first built, double-emails were being sent, since these kinds of triggers can fire twice per operation.

So, I built a script (like so) to make sure the email is only sent once, and further I added a beforeInsert + beforeUpdate trigger that always changes a custom field to make sure the after* triggers always fire twice.

 

Now, sometimes the email gets sent and sometimes it doesn't:

 

  • When I setup the email to get sent during the first invocation, and I create a record via the web, the email gets sent.
    If I create a record via upsert() API method, it doesn't.

  • When I setup the email to get sent during the second invocation, the opposite happens.
    Creating via upsert() API sends the email, creating via the web doesn't. 

 

I'm using Messaging.sendEmail() method to do the actual sending.

The mail invocation limit is well under, and Apex Debug Logs do not report any errors.

But the activity is not recorded on the related object record, and I do not actually receive any email.

WTH?

 

I've spent hours already trying to debug this, and I have no idea how to go any further.

Plz halp.

Jeff MayJeff May

You can add System.debug() messages to your code, then open the Developer Console for the org you're testing in.  After the insert (or update), examine the debug log and you'll see the code decisions.

Vinit_KumarVinit_Kumar

This seems related to somelogic in your.As,Jeff suggested put some debug statements inside your code and see which method is being executed in API and UI transaction,then this would make things more clear.

aaronbaumanaaronbauman

As noted in the original post, I already have debugging logs in place, and they are already reporting that the email as being sent.

Jeff MayJeff May

Sorry, I am confused. The original post indicates that sometimes the email is not being sent.  That's where the debugging will help.  When you see a debug statement that you are in a "don't send" area of code, you'll be able to see what the conditions are. If emails are being sent, what is the problem you are trying to solve?

aaronbaumanaaronbauman

What I'm trying to say is Debug Logs indicate that the email is being sent, but it's not actually being sent.

The difference in behavior manifests between Update/Insert via the web UI, and Upsert via API.

 

When the email is correctly sent, I receive a copy, and an Activity log record is created and attached to the WhatID record.

I'm not sure how better to explain the situation.