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
Ido Greenbaum 10Ido Greenbaum 10 

Help with setting Email TO address in customized Email Publisher Quick Action

Hey all, 

I have a running implementation of a customized Email Publisher in the Case Feed, which implement QuickActionDefaultHandler to pre-populate Email Templates based on my Cases Record Type. Below is the Apex Class:
global class EmailPublisherLoader implements QuickAction.QuickActionDefaultsHandler {
// Empty constructor
    global EmailPublisherLoader() { }

// The main interface method
    global void onInitDefaults(QuickAction.QuickActionDefaults[] defaults) {
        QuickAction.SendEmailQuickActionDefaults sendEmailDefaults = null;

        // Check if the quick action is the standard Case Feed send email action
        for (Integer j = 0; j < defaults.size(); j++) {
            if (defaults.get(j) instanceof QuickAction.SendEmailQuickActionDefaults && 
               defaults.get(j).getTargetSObject().getSObjectType() == 
                   EmailMessage.sObjectType && 
               defaults.get(j).getActionName().equals('Case.Email') && 
               defaults.get(j).getActionType().equals('Email')) {
                   sendEmailDefaults = 
                       (QuickAction.SendEmailQuickActionDefaults)defaults.get(j);
                   break;
            }
        }

         if (sendEmailDefaults != null) {
            Case c = [SELECT Status, contact.Email, Additional_To__c, Additional_CC__c, Additional_BCC__c, RecordType.name FROM Case WHERE Id=:sendEmailDefaults.getContextId()];
            EmailMessage emailMessage = (EmailMessage)sendEmailDefaults.getTargetSObject();  
    //set TO address
         if (c.contact.Email == c.Additional_To__c){
            emailMessage.toAddress = (c.contact.Email);
            }
            else{
            if (c.Additional_To__c != null){
            emailMessage.toAddress = (c.contact.Email+' '+c.Additional_To__c);
            }
            }

In addition, I am setting the TO address according a combination of the Case Contact and the custom field - 'Additional_To__c'. The above solution is setting the TO properly, but when the Case Contact does exist in the 'Additional_To__c' as follows:

User-added image

The outcome is a duplicity of the Case Contact - 'test@test.com': 
User-added image

How can I change the IF statement to avoid the above duplicitity? 
Best Answer chosen by Ido Greenbaum 10
NagendraNagendra (Salesforce Developers) 
Hi Ido,

Please find below post which was addressed in the stack exchange community.

I was able to resolve this by using 'indexOf' for String 'includes' condition as follows:
//set TO address
     String contactEmail = c.contact.Email; 
     if (c.contact.Email == c.Additional_To__c){
        emailMessage.toAddress = (c.contact.Email);
        }
        else{
            if (c.Additional_To__c != null){
                //contactEmail is included in Additional TO
                if (c.Additional_To__c.indexOf(contactEmail) != -1){
                    emailMessage.toAddress = (c.Additional_To__c);
                    }
            else{
                emailMessage.toAddress = (c.contact.Email+' '+c.Additional_To__c);
                }
            }
        }

Please mark this post as solved so that it gets removed from unanswered queue and will be available as proper solution so that other can benefit from this.

Regards,
Nagendra.P

All Answers

NagendraNagendra (Salesforce Developers) 
Hi Ido,

Please find below post which was addressed in the stack exchange community.

I was able to resolve this by using 'indexOf' for String 'includes' condition as follows:
//set TO address
     String contactEmail = c.contact.Email; 
     if (c.contact.Email == c.Additional_To__c){
        emailMessage.toAddress = (c.contact.Email);
        }
        else{
            if (c.Additional_To__c != null){
                //contactEmail is included in Additional TO
                if (c.Additional_To__c.indexOf(contactEmail) != -1){
                    emailMessage.toAddress = (c.Additional_To__c);
                    }
            else{
                emailMessage.toAddress = (c.contact.Email+' '+c.Additional_To__c);
                }
            }
        }

Please mark this post as solved so that it gets removed from unanswered queue and will be available as proper solution so that other can benefit from this.

Regards,
Nagendra.P
This was selected as the best answer
Ido Greenbaum 10Ido Greenbaum 10
This was actually my answer  :-) 

Thanks for the assistance. 
NightFoxNightFox
How to pre-populate FROM address in Email Publisher in the Case Feed. 
As far as I know My below code is correct. 

Here is the place where im passing the value for FROM Address fields. 
EmailMessage emailMessage = (EmailMessage)sendEmailDefaults.getTargetSObject();    
// Set bcc address to make sure each email goes for audit
emailMessage.FromAddress = ('security@test.com');
emailMessage.ValidatedFromAddress = ('ValidatedFrom@address.com'); emailMessage.BccAddress = 'ff1@gmail.com';
emailMessage.CCAddress = 'bb1@gmail.com';
emailMessage.subject= 'Testing ';
emailMessage.ToAddress = 'toAdd@gmail.com';

Here is the Email publisher action page. See, all oher fields are populated as per Apex definition. From address is only considering the ORG WIDE ADDRESS.

Emailpub

Here is my full APEX code:
global class EmailPublisherLoader implements QuickAction.QuickActionDefaultsHandler {
    // Empty constructor
    global EmailPublisherLoader(){}
    
    // The main interface method
    global void onInitDefaults(QuickAction.QuickActionDefaults[] defaults){
        QuickAction.SendEmailQuickActionDefaults sendEmailDefaults = null;
    
        // Check if the quick action is the standard Case Feed send email action
        for (Integer j = 0; j < defaults.size(); j++) {
            if (defaults.get(j) instanceof QuickAction.SendEmailQuickActionDefaults && defaults.get(j).getTargetSObject().getSObjectType() == 
                   EmailMessage.sObjectType && defaults.get(j).getActionName().equals('Case.Email') &&  defaults.get(j).getActionType().equals('Email')){
                   sendEmailDefaults = (QuickAction.SendEmailQuickActionDefaults)defaults.get(j);
                   break;
            }
        }
        
        if(sendEmailDefaults != null){
            system.debug(' sendEmailDefaults # ' + sendEmailDefaults  );
            system.debug(' sendEmailDefaults ID # ' + sendEmailDefaults.getcontextId()); 
            Case c = [SELECT Status, Casenumber,Reason FROM Case WHERE Id=:sendEmailDefaults.getContextId()];
            system.debug(' Case '+ c.CaseNumber);
            system.debug(' sendEmailDefaults.getTargetSObject() '+ sendEmailDefaults.getTargetSObject());
        
            EmailMessage emailMessage = (EmailMessage)sendEmailDefaults.getTargetSObject();    
            // Set bcc address to make sure each email goes for audit
            system.debug(' getBccAddress(c.Reason) # ' + getBccAddress(c.Reason) );
            system.debug(' getFromAddress(c.Reason) # ' + getFromAddress(c.Reason));
            //emailMessage.BccAddress = getBccAddress(c.Reason);
            //emailMessage.FromAddress = getFromAddress(c.Reason);
            emailMessage.FromAddress = ('security@test.com');
            emailMessage.ValidatedFromAddress = ('ValidatedFrom@address.com');
            emailMessage.BccAddress = 'ff1@gmail.com';
            emailMessage.CCAddress = 'bb1@gmail.com';
            //emailMessage.ValidatedFromAddress = 'tt1@gmail.com';
            emailMessage.subject= 'Testing ';
            emailMessage.ToAddress = 'toAdd@gmail.com';
            system.debug(' emailMessage '+ emailMessage );
            
            //sendEmailDefaults.ValidatedFromAddress = 'tt1@gmail.com';
            
            /* 
            Set Template related fields 
            When the In Reply To Id field is null we know the interface 
            is called on page load. Here we check if 
            there are any previous emails attached to the case and load 
            the 'New_Case_Created' or 'Automatic_Response' template.
            When the In Reply To Id field is not null we know that 
            the interface is called on click of reply/reply all 
            of an email and we load the 'Default_reply_template' template
            */
            
            system.debug(' sendEmailDefaults get Reply To '+ sendEmailDefaults.getInReplyToId());
            system.debug(' sendEmailDefaults getFrom Address '+ sendEmailDefaults.getFromAddressList());
            
            Integer emailCount = [SELECT count() FROM EmailMessage WHERE ParentId=:sendEmailDefaults.getContextId()];
            
            system.debug(' emailCount ' + emailcount );
            
            if(emailCount!= null && emailCount > 0){
                sendEmailDefaults.setTemplateId(
                getTemplateIdHelper('Send_Personal_Loan_Details'));
            }else{
                sendEmailDefaults.setTemplateId(
                getTemplateIdHelper('New_Case_Created'));
            }
            
            sendEmailDefaults.setInsertTemplateBody(false);
            sendEmailDefaults.setIgnoreTemplateSubject(true);
            
            system.debug(' sendEmailDefaults ### ' + sendEmailDefaults);
            
            /*
            if(sendEmailDefaults.getInReplyToId() == null){
                
            }else{
                sendEmailDefaults.setTemplateId(
                getTemplateIdHelper('Default_reply_template'));
                sendEmailDefaults.setInsertTemplateBody(false);
                sendEmailDefaults.setIgnoreTemplateSubject(true);
            }*/
        }
    }
    
    private Id getTemplateIdHelper(String templateApiName){
        Id templateId = null;
        try{
            templateId = [select id, name from EmailTemplate where developername = : templateApiName].id;
            system.debug(' Temp id # '+ templateId );   
        }catch(Exception e){
            system.debug('Unble to locate EmailTemplate using name: ' + templateApiName + ' refer to Setup | Communications Templates ' + templateApiName);
        }
        return templateId;
    }
    
    private String getBccAddress(String reason){
        return 'support_technical@mycompany.com, tt@gmail.com'; 
    }
    
    private String getFromAddress(String reason){
        return 'loan@mycompany.com, personalloan@gmail.com'; 
    }
}