Stat Tracker

Monday, May 16, 2011

Setting the Email Bounced Alert in Salesforce Via Apex / API

Salesforce has a pretty nice feature called "Bounced Email Alerts" which can be configured using the declaritive setup menu in Salesforce. This allows emails which were bounced when being sent via Salesforce to popup alerts on the Email address field in the standard pages. It's pretty useful, especially if your sending emails via Salesforce.

Take a look at the email alert and prompt below for what it looks like.


And if a user clicks on the alert it gives them some details:



But many users have other 3rd party systems which sends the email. So the question is how do I get the "Bounced Email Alerts" in Salesforce if I'm using another system to send the emails?

The answer is you can use Apex code. It actually very simple but not documented anywhere that I saw. There are two fields on the Contact object which trigger the Email Bounce Alert functionality. They are EmailBouncedDate and EmailBounceReason. If you populate these two fields on a Contact record, the Email Bounce Alert functionality will fire. And vice versa, if you null out those two fields the alerts go away.

These fields are only visible in Apex code. You can't create a workflow rule / field update to do this unfortunately. Luckily, the Apex code is pretty simple. For example, below I added a boolean flag to Contact call "Invalid Email". Whenever I update this field, be it from the UI or a Web Service call from a 3rd party email system, the Bounce Alert functionality fires.

Sample Code to set the Email Bounced Alerts in Apex:

trigger ContactTrigger on Contact (after delete, after insert, after undelete,
after update, before delete, before insert, before update)
{
    if(Trigger.isBefore)
    {
        for(Contact contact : trigger.new)
        {
            if(contact.EmailBouncedDate == null && contact.EmailBouncedReason == null && contact.Invalid_Email__c == true)
            {
                contact.EmailBouncedDate = DateTime.now();
                contact.EmailBouncedReason = 'Invalid Email Address Set By User';
            }
            if(contact.Invalid_Email__c == false)
            {
                contact.EmailBouncedDate = null;
                contact.EmailBouncedReason = null;
            }
        }
    }
}


In conclusion, if you have a 3rd party email system with Salesforce but still want to use the Bounced Email Alert functionality, you can do it if you have Enterprise or Unlimited Editions' of Salesforce.