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
UrvikUrvik 

Apex Class for Sending Email

Hi everyone,
I have the following controller for sending emails for our custom approval process. There are two emails going out - for Approver and Reviewer. The first issue is, Approvers are getting Approver email and Reviewer email too. The second issue is, Reviewers are getting emails based on number of Approvers. e.g. If there are three approvers then reviewer gets three emails, which is incorrect. Each reviewer should get only one email. Could someone please tell me what is incorrect in my controller?

---------

global class Submit_Form_For_Approval
{
    webService static String submitForApproval(String govID, String attIDs)
    {
        Messaging.SingleEmailMessage attMail = new Messaging.SingleEmailMessage();
        List<Messaging.SingleEmailMessage> allMails = new List<Messaging.SingleEmailMessage>();
        List<Messaging.SingleEmailMessage> bccMails = new List<Messaging.SingleEmailMessage>();
        List<Messaging.EmailFileAttachment> attList = new
        List<Messaging.EmailFileAttachment>();
        List<Project_Governance_Form_Approval_Request__c> requestsToAdd = new List<Project_Governance_Form_Approval_Request__c>();
        List<Project_Governance_Form_Approval_Request__c> formReq = new List<Project_Governance_Form_Approval_Request__c>();
        Set<String> bccEmails = new Set<String>();
        Boolean sendFailMail = false;
        Decimal attSize = 0.0;
        String emailToApexEmailAddress = '';
        String templateID = '';
        String BcctemplateID = '';
        String roleName = '';
        String msg = System.Label.Approval_Process_Request_Submitted_Success_Msg;
        Approval_Process_Setting__c appSetting = Approval_Process_Setting__c.getInstance();


      
        if(appSetting != null)
            roleName = appSetting.Leadership_Role_Name__c;
        
        Project_Governance_Form__c govForm = [SELECT id,Name, Date_of__c,Date_of_Commitment_Request__c,
        Date_of__c,Project__c,isLocked__c,Project__r.Name,Project__r.Owner.Email,
        Project__r.Lead__r.Email,Project__r.Transaction_Lead__r.Email, Override_Lock_Toggle__c,
        Project__r.External_Company_Contact__r.Email, Project__r.Addiitonal__r.Email,
        Project__r.Additional__r.Email, Project__r.Additional__r.Email,
        Recordtype.DeveloperName FROM Project_Governance_Form__c WHERE id = :govID LIMIT 1];

        try
        {
            UserRecordAccess usr = [SELECT HasEditAccess,RecordId FROM UserRecordAccess WHERE UserId = :UserInfo.getUserID() AND RecordId =:govForm.Project__c LIMIT 1];
          
            if(!usr.HasEditAccess)
            {
                return 'NOACCESS';
            }
        }
        catch(Exception e)
        {
            system.debug('**************Exception encountered**************'+e.getMessage());
        }

        if(govForm.Project__r.ERDI_S_E_Lead__r.Email != null)
            bccEmails.add(govForm.Project__r.ERDI_S_E_Lead__r.Email);

        if(govForm.Project__r.Transaction_Lead__r.Email != null)
            bccEmails.add(govForm.Project__r.Transaction_Lead__r.Email);
      
        if(govForm.Project__r.Addiitonal_ERDI_member_1__r.Email != null)
            bccEmails.add(govForm.Project__r.Addiitonal_ERDI_member_1__r.Email);
          
        if(govForm.Project__r.Additional_ERDI_Member_2__r.Email != null)
            bccEmails.add(govForm.Project__r.Additional_ERDI_Member_2__r.Email);
        
        if(govForm.Project__r.Additional_ERDI_Member_3__r.Email != null)
            bccEmails.add(govForm.Project__r.Additional_ERDI_Member_3__r.Email);
      
                     
        if(appSetting != null)
        {
            emailToApexEmailAddress = appSetting.Email_to_Apex_Email_Address__c;
           
            try
            {
                templateID = [SELECT id FROM EmailTemplate WHERE DeveloperName = :appSetting.Email_Template_Developer_Name__c].id;
                BcctemplateID = [SELECT id FROM EmailTemplate WHERE DeveloperName = :appSetting.Bcc_Email_Template_Developer_Name__c].id;
            }
            catch(Exception e)
            {
                msg =System.Label.Approval_Process_Email_Template_Not_Found_Msg;
                return msg;
            }
        }
        else
        {
            msg = System.Label.Approval_Process_Custom_Setting_Not_Defined_Msg;
            return msg;
        }

        formReq = [SELECT id,Approver__c, Reviewer__c, Status__c FROM Project_Governance_Form_Approval_Request__c WHERE Project_Governance_Form__c = :govID AND Status__c = 'Pending for Submission'];

        if(!formReq.isEmpty() && attIDs != '' && attIDs != null)
        {
            List<String> attIDList = attIDs.split(';');
            for(Attachment att : [SELECT Id,Body,Name,BodyLength FROM Attachment WHERE ID IN :attIDList])
            {
                Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
                attSize = attSize + Double.ValueOF(att.BodyLength/1024);
                efa.setFileName(att.Name);
                efa.setBody(att.Body);
                attList.add(efa);
            }
        }
      
        system.debug('***********form data************'+formReq);
        for(Project_Governance_Form_Approval_Request__c req : formReq)
        {
            Project_Governance_Form_Approval_Request__c reqUpdate = new Project_Governance_Form_Approval_Request__c(id = req.id);
            reqUpdate.Status__c = 'Pending Approval';
            requestsToAdd.add(reqUpdate);

            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            mail.setWhatID(req.id);
            //if(!bccEmails.isEmpty())
                //mail.setBCCAddresses(new List<String>(bccEmails));
            mail.setTemplateID(templateID);
            mail.setSaveAsActivity(true);
            mail.setTargetObjectId(req.Approver__c);
            mail.setReplyTo(emailToApexEmailAddress);

          
          

            Messaging.SingleEmailMessage mailbcc = new Messaging.SingleEmailMessage();
            if(!bccEmails.isEmpty()){
                mailbcc.setWhatID(req.id);
                mailbcc.setTemplateID(BcctemplateID);
                mailbcc.setBccAddresses(new List<String>(bccEmails));
                mailbcc.setTargetObjectId(req.Approver__c);
                //mail.setCcAddresses(ccAddresses);
            }

            system.debug('*************created email***************************'+bccEmails);
            if(!attList.isEmpty())
            {
                if(attSize > 9216)
                {
                    String[] toAddresses = new String[]{govForm.Project__r.Owner.Email};
                    attMail.setToAddresses(toAddresses);
                    attMail.setSubject('Attachments not sent for Project ' + govForm.Project__r.Name);
                    attMail.setHTMLBody('Attachment were not sent for the project ' + govForm.Project__r.Name + ' - you have exceeded size limit of 10MB');
                    sendFailMail = true;
                }
                else
                {
                    mail.setFileAttachments(attList);
                }
            }
            
         if(mailbcc!=null){
             // bccMails.add(mailbcc);
             allMails.add(mailbcc);
             }
             allMails.add(mail);
        }

    if(!govForm.isLocked__c)
        {
            govForm.isLocked__c = true;
            if(govForm.Recordtype.DeveloperName=='AIP_Form')
            govForm.Date_of_AIP_request__c=system.today();
            if(govForm.Recordtype.DeveloperName=='Commitment_Form')
            govForm.Date_of_Commitment_Request__c=system.today();
            if(govForm.Recordtype.DeveloperName=='FMA_Form' ||govForm.Recordtype.DeveloperName=='FMA_Commitment')
            govForm.Date_of_FMA_Request__c=system.today();
            govForm.Override_Lock_Toggle__c =!(govForm.Override_Lock_Toggle__c);
            try
            {
                update govForm;
            }
            catch(Exception e)
            {
                system.debug('*********Exception encountered********'+e.getMessage());
            }
        }

        if(!requestsToAdd.isEmpty())
        {
            try
            {
                update requestsToAdd;
                Messaging.sendEmail(allMails);
                //Messaging.sendEmail(bccMails);

            }
            catch(Exception e)
            {
                system.debug('*********Exception encountered********'+e.getMessage());
                msg = e.getMessage();
            }
        }

        if(sendFailMail)
        {
            try
            {
                Messaging.sendEmail(new Messaging.SingleEmailMessage[]{ attMail });
            }
            catch(Exception e)
            {
                system.debug('*********Exception encountered********'+e.getMessage());
                msg = e.getMessage();
            }
        }
        system.debug('msg:'+msg);
        return msg;
    }
}
ShashForceShashForce
Hi,

From what I understand from the code,

1.) You are sending emails using a FOR loop. The number of emails sent will depend on the number of rows returned by the SOQL query, which is stored in "formReq". Please check this.
2.) I do not see separate code logic for Reviewer email. To send 2 emails, the code logic to send 2 separate emails should also be separated.

Thanks,
Shashank
UrvikUrvik
Hi Shashank,
Thanks for your reply. The Reviewer get BCC on email and if you see I am passing the value of separate email template "inmailbcc.setTemplateID(BcctemplateID);" So Approvers should not get the email the Reviewers get and vice-versa. Currently its sending 2 emails to approvers... 
ShashForceShashForce
Hi,

In this code:

Messaging.SingleEmailMessage mailbcc = new Messaging.SingleEmailMessage();
            if(!bccEmails.isEmpty()){
                mailbcc.setWhatID(req.id);
                mailbcc.setTemplateID(BcctemplateID);
                mailbcc.setBccAddresses(new List<String>(bccEmails));
                mailbcc.setTargetObjectId(req.Approver__c);
                //mail.setCcAddresses(ccAddresses);
            }

You are setting the TargetObjectId as Approver__c. This should be the culprit, since you are passing the Approver user's ID. It should be a Reviewer's ID instead.

If this answers your question, please mark this as the Best Answer for this post, so that others can benefit from this post.

Thanks,
Shashank
UrvikUrvik
I have tried this before. If I change the TargetObjectId as Reviewer__c, it doesn't send any emails. Approver__c and Reviewer__c both are lookup to Contact. I am not able to figure out what should be the TargetObjectId for bcc recipients. As I said, Reviewer__c doesnt work at all.
ShashForceShashForce
Hi,

You should ensure that the Contact record populated as a reviewer has a valid email address, and most importantly, has "Email Opt Out" checkbox unchecked. Please check if this is the case.

Thanks,
Shashank
UrvikUrvik
Yes the contact has a valid email address and Email Opt Out checkbox is not checked. By setting TargetObjectId as Reviewer__c stopped sending emails completely.