According to this Know issue(https://trailblazer.salesforce.com/issues_view?id=a1p3A0000018BuDQAU), I cannot set the flag IsExternallyVisible to false via the EmailsMessage trigger. The workaround is a Future method that I created. This does not work for all emails. Some emails can be changed and others not. But there is no recognisable pattern. I wrote a test and it failed. But I do not understand why. This is my test:
@isTest
public class EmailMessageTest {
@testSetup
static void setup() {
TestDataFactory.prepareForTest();
} @isTest
static void mailExternalyVisible() {
List<Id> emailIds = new List<Id>();
Case c = new Case();
c.Subject = 'Test';
c.Description = 'testing';
c.Status ='New';
c.Priority = 'Medium';
c.Origin = 'Email';
insert c; //Insert emailmessage for case
EmailMessage email = new EmailMessage();
email.FromAddress = 'test@abc.org';
email.Incoming = True;
email.ToAddress= 'test@xyz.org';
email.Subject = 'Test email';
email.HtmlBody = 'Test email body';
email.ParentId = c.Id;
insert email;
emailids.add(email.id);
Test.startTest();
//call future methode
EmailMessageTriggerHandler.changeVisibility(emailIds);
Test.stopTest(); EmailMessage emailRec = [Select id, IsExternallyVisible from EmailMessage where parentId = :c.id limit 1];
System.assertEquals(false,emailRec.IsExternallyVisible, 'Email should not be externally visible'); }
}
This is the future methode:
@future
public static void changeVisibility(List<ID> emailIds){
System.debug('changeVisibility');
List<EmailMessage> emailsToUpdate = [SELECT Id,Incoming,IsExternallyVisible,Status FROM EmailMessage WHERE Id IN :emailIds];
System.debug('emailsToUpdate before');
System.debug(emailsToUpdate);
for(EmailMessage em : emailsToUpdate){
System.debug('loop setting mail to false');
em.IsExternallyVisible = false;
}
System.debug('emailsToUpdate after');
System.debug(emailsToUpdate);
update emailsToUpdate;
emailsToUpdate = [SELECT Id,Incoming,IsExternallyVisible,Status FROM EmailMessage WHERE Id IN :emailIds];
System.debug('emailsToUpdate after update');
System.debug(emailsToUpdate);
}
When I check the debug message I see that it has been reseted to true again. See attached image.
My Trigger for EmailMessages looks like that:
trigger EmailMessageTrigger on EmailMessage (after insert,before insert) { if(Trigger.isAfter && Trigger.isInsert){
EmailMessageTriggerHandler.createCaseNotifications( Trigger.new );
List<Id> emailIds = new List<Id>();
for(EmailMessage email:Trigger.new){
emailIds.add(email.Id);
}
if(!System.isFuture() && !System.isBatch()){
EmailMessageTriggerHandler.changeVisibility(emailIds);
}
}
#Sales Cloud}