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
Raj R.Raj R. 

Is there a way to use apex trigger or class to change the Workflow Email Alert Additional emails field?

Hi,

We have a multiselect picklist (custField1) in Salesforce that contains emails addresses on a custom object called "custObjA". Whenever custObjA is saved, the custField1 is required and users have the ability to select 1 or more email address values. We have a workflow email alert that was created so that on save of custObjA, an email is sent to user editing the record.

We wanted to know if there was a way through apex triggger or class to update the workflow email alert's "Additional Emails" field. Essentially when the custField1 (multiselect picklist) is updated, we want to use all the selected values to go into the "Additional Emails" field of the workflow. Is this possible?
Best Answer chosen by Raj R.
RohRoh
Hello rRup,
Yes this is possible, but instead of using a workflow email alert you need to build this inside your code logic.
please follow below steps :
1.Create a salesforce email template.
       List<Schema.EmailTemplate> template = [SELECT Id, Subject, HtmlValue, Body FROM EmailTemplate WHERE Id = :[please provide your template id here]];
2.Write code logic to get the email addresses input from the record just saved.
public static void sendEmailsUsingTargetObjectId(String emailSubject ,String emailBody,
                                                List<id> listofUserIdsAsRecipient,
                                                Boolean attachmentRequired,
                                                Boolean isPlainText,
                                                Messaging.EmailFileAttachment emailAttachment){
  List<Messaging.SingleEmailMessage> listOfEmailToBeSend = new List<Messaging.SingleEmailMessage>();
  List<id> uniqueRecipientList = new List<Id>();
  for(object__c str: Trigger.New[0].emailAddressField__c.split(';'))
  uniqueRecipientList.addAll(str);
  try{
    for(Id uniqueRecipientListInstance : uniqueRecipientList){
      if(uniqueRecipientListInstance!=null){
        Messaging.SingleEmailMessage emailsToBeSend = new Messaging.SingleEmailMessage();
        emailsToBeSend.setTargetObjectId(uniqueRecipientListInstance);
        emailsToBeSend.setSubject(emailSubject);
        if(isPlainText){
        emailsToBeSend.setPlainTextBody(emailBody);  
        }
        else{
        emailsToBeSend.setHtmlBody(emailBody);
        }
        emailsToBeSend.setSaveAsActivity(false);
        if(attachmentRequired){
          emailsToBeSend.setFileAttachments(new Messaging.EmailFileAttachment[]
                                            {emailAttachment});
        }
        listOfEmailToBeSend.add(emailsToBeSend);
      }
    }
    Messaging.sendEmail(listOfEmailToBeSend);
  }
  catch(Exception e){
    system.debug(e);
  }
 
}

PLEASE CHOOSE THIS AS THE BEST ANSWER IF IT WORKS FOR YOU.

Thanks,
Roh

All Answers

RohRoh
Hello rRup,
Yes this is possible, but instead of using a workflow email alert you need to build this inside your code logic.
please follow below steps :
1.Create a salesforce email template.
       List<Schema.EmailTemplate> template = [SELECT Id, Subject, HtmlValue, Body FROM EmailTemplate WHERE Id = :[please provide your template id here]];
2.Write code logic to get the email addresses input from the record just saved.
public static void sendEmailsUsingTargetObjectId(String emailSubject ,String emailBody,
                                                List<id> listofUserIdsAsRecipient,
                                                Boolean attachmentRequired,
                                                Boolean isPlainText,
                                                Messaging.EmailFileAttachment emailAttachment){
  List<Messaging.SingleEmailMessage> listOfEmailToBeSend = new List<Messaging.SingleEmailMessage>();
  List<id> uniqueRecipientList = new List<Id>();
  for(object__c str: Trigger.New[0].emailAddressField__c.split(';'))
  uniqueRecipientList.addAll(str);
  try{
    for(Id uniqueRecipientListInstance : uniqueRecipientList){
      if(uniqueRecipientListInstance!=null){
        Messaging.SingleEmailMessage emailsToBeSend = new Messaging.SingleEmailMessage();
        emailsToBeSend.setTargetObjectId(uniqueRecipientListInstance);
        emailsToBeSend.setSubject(emailSubject);
        if(isPlainText){
        emailsToBeSend.setPlainTextBody(emailBody);  
        }
        else{
        emailsToBeSend.setHtmlBody(emailBody);
        }
        emailsToBeSend.setSaveAsActivity(false);
        if(attachmentRequired){
          emailsToBeSend.setFileAttachments(new Messaging.EmailFileAttachment[]
                                            {emailAttachment});
        }
        listOfEmailToBeSend.add(emailsToBeSend);
      }
    }
    Messaging.sendEmail(listOfEmailToBeSend);
  }
  catch(Exception e){
    system.debug(e);
  }
 
}

PLEASE CHOOSE THIS AS THE BEST ANSWER IF IT WORKS FOR YOU.

Thanks,
Roh
This was selected as the best answer
Raj R.Raj R.
Hello Roh,

Do you know if there are any limitations on what I can attach to the email? Currently, we have a button which renders a pdf via visualforce and has been styled through customization. Would it be possible to create a pdf similar to the visualforce page and email it as an attachment?
RohRoh
Hello rRup,
Thats should be a lot easier than the other requirement which i understood and gave you the code for.

1.You need to generate a class using WSDL for PDF.
https://jungleeforce.wordpress.com/2013/05/08/generate-a-pdf-and-attach-it-to-record-from-a-trigger-in-salesforce/
-The above link has WSDL through which you can generate the pdf Class and use it internally.
2.Create another global class to access the above class.
For example : Account
global class AccountTriggerController{
 
    @Future(callout=true)
    public static void addPDFAttach(string sessionId, list<id> accountId){
        addPDFStub.SessionHeader_element sessionIdElement= new addPDFStub.SessionHeader_element();
        sessionIdElement.sessionId = sessionId;
 
        addPDFStub.AddPdfToRecord stub= new addPDFStub.AddPdfToRecord();
        stub.SessionHeader= sessionIdElement;
        stub.addPDF(accountId);
    }
}

3.You can then simply call this method through your Apex class.
4.Remember you cannot directly send a pdf, try to save this into an attachment obj as a blob and then access the attachment and send it.
Here is the code to send the email from VF page.

public PageReference SubmitLetter()
            sendPDFEmail.addPDFmail(userInfo.getSessionId(),campaignId);
        PageReference pdf = new PageReference('/apex/Account.id);
        Blob b;
        if(!System.Test.isRunningTest()){
            b = pdf.getContentAsPDF()';
        }else{
            b = blob.valueof('asdf');
        }
        datetime currentTime = datetime.now();
        
        List<Attachment> Attachment=[select id from Attachment where Account=:account.Id and name='xyz'];
        if(Attachment.size()==0){
            Attachment obj=new Attachment();
            obj.name='xyz';
            try{
                insert obj;
            }
            catch(DMLException exc){
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, exc.getDMLMessage(0)));
                return ApexPages.currentPage();       
            }
            Attachment.add(obj);             
        }  
        
        Attachment attach=new Attachment();
        attach.parentId=mdtAttachment[0].id;
        if(!System.Test.isRunningTest()){
            attach.Body = pdf.getContent();
        }else{
            attach.Body = Blob.valueof('test');
        }
        attach.Name = 'rru'+MSTFormat+' +'.pdf';        
        try{
            insert attach;
            attach.body=null;
        }
        catch(DMLException exc){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, exc.getDMLMessage(0)));
            return ApexPages.currentPage();
        }
        return null;
    }

PLEASE CHOOSE THIS AS THE BEST ANSWER IF IT WORKS FOR YOU.

Thanks,
Roh