1. Create a custom object to hold the exception emails.
2. Create records in the custom object.
3. Use the below code.
- trigger EmailMessageTrigger on EmailMessage ( before insert ) {
- Set < Id > setEmailRecIds = new Set < Id >();
- Set < String > setEmailAddress = new Set < String >();
- Set < String > notAllowedEmails = new Set < String >();
- Map < Id, String > mapRecIdEmail = new Map < Id, String >();
- for ( EmailMessage objMsg : trigger.new ) {
- if ( String.isNotBlank( objMsg.ToAddress ) )
- setEmailAddress.addAll( objMsg.ToAddress.split( ‘;’ ) );
- if ( objMsg.ToIds.size() > 0 )
- setEmailRecIds.addAll( objMsg.ToIds );
- }
- if ( setEmailRecIds.size() > 0 ) {
- for ( Lead objLead : [ SELECT Id, Email FROM Lead WHERE Id IN: setEmailRecIds ] ) {
- setEmailAddress.add( objLead.Email );
- mapRecIdEmail.put( objLead.Id, objLead.Email );
- }
- for ( Contact objContact : [ SELECT Id, Email FROM Contact WHERE Id IN: setEmailRecIds ] ) {
- setEmailAddress.add( objContact.Email );
- mapRecIdEmail.put( objContact.Id, objContact.Email );
- }
- for ( User objUser : [ SELECT Id, Email FROM User WHERE Id IN: setEmailRecIds ] ) {
- setEmailAddress.add( objUser.Email );
- mapRecIdEmail.put( objUser.Id, objUser.Email );
- }
- }
- for ( Email_Exception__c objExcp : [ SELECT Email__c FROM Email_Exception__c WHERE Email__c IN: setEmailAddress ] )
- notAllowedEmails.add( objExcp.Email__c );
- for ( EmailMessage objMsg : trigger.new ) {
- if ( String.isNotBlank( objMsg.ToAddress ) ) {
- for ( String emailAddr : objMsg.ToAddress.split( ‘;’ ) ) {
- if ( notAllowedEmails.contains( emailAddr ) )
- objMsg.addError( ‘You cannot send email to this email address ‘ + emailAddr );
- }
- }
- if ( objMsg.ToIds.size() > 0 ) {
- for ( Id recId : objMsg.ToIds ){
- if ( mapRecIdEmail.containsKey( recId ) ) {
- if ( notAllowedEmails.contains( mapRecIdEmail.get( recId ) ) )
- objMsg.addError( ‘You cannot send email to this email address ‘ + mapRecIdEmail.get( recId ) );
- }
- }
- }
- }
- }
Output: