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
John Lewis 29John Lewis 29 

Email-to-Case Identification in Trigger

When a Case is created by Email-to-Case, we find that the CreatedById is set to a special UserId which seems to refer to the Automated Case User 'System' which is configured at Customize > Cases > Support Settings.

I've found that in Apex Trigger code, running for the 'before insert' event on the Case object, this User can be identified by statements such as:

    if (UserInfo.getName() == 'System')
    if (UserInfo.getUserName().startsWith('automatedcase@'))
    if (UserInfo.getUserType() == 'AutomatedProcess')
    
However, I think that if changes are later made to the Case > Support Settings so that the Automated Case User is an actual User then the above code will no longer give the same result.

Is there, therefore, a reliable way to identify during trigger execution that the Case is being created by Email-to-Case rather than by some other method (manual entry, clone, visualforce, etc.)?

Thanks in advance for any suggestions.

Regards
John Lewis
Virender Singh 29Virender Singh 29
Hi John,

With help of below code snippet, you can find out whether the case is created with help of Email to Case functionality.

 
Case newCase= Trigger.New[0];
Boolean emailTocase = false;
EmailMessage ms= [select Id, ToAddress from EmailMessage where ParentId = :newCase.Id limit 1];
if ( ms.ToAddress == '#EmailAddressWhereUserSendEmail' ) {
  emailTocase = true;
}


Note : ** Please handle bulkification of code by yourself :P

Please select as best answer if it has solved your problem.

Regards,
Virender Singh
 
John Lewis 29John Lewis 29
Hello, I'll try this, but it seems to me that the problem might be that the EmailMessage record is created after the Case so at the moment I execute the above query in the Case trigger, the EmailMessage won't yet have been created...

I'll let you know how it turns out.

Regards
John Lewis
John Lewis 29John Lewis 29
In fact, there's another problem: when the before insert trigger runs, I find that not even the Case Id has been set (at this moment in execution, it has a NULL value) so it's not possible to retrieve EmailMessage records with ParentId = :newCase.Id

Regards
John Lewis