2

It would be great if I could get help with the below requirement that I have to achieve.

The requirement is that I run a scheduler in a custom object called Project__c. Around 20+ projects pass the criteria for the email. Each Project has separate recipients based on a related list called clients__c.

I was using a visualforce email template to get some fields, but now I am not sure how do I Pass the correct Id to the template from the scheduler?

IREmailScheduler.cls

global class IREmailScheduler Implements Schedulable {

    global void execute(SchedulableContext sc)
    {

        List <id> lsAccountIds = new List <id>();
        List <String> ccEmails = new List <String>();
        List<pse__Proj__c> lsProject = [SELECT id,Name,pse__Practice__c,Service_Type__c,pse__Region__c,createdDate, pse__Is_Active__c,pse__End_Date__c,
                                        Remaining_Project_Hours__c, pse__Account__r.Account_Manager__r.Email
                                        FROM pse__Proj__c where  pse__End_Date__c != null AND Remaining_Project_Hours__c!=null
                                        AND createdDate > 2019-06-05T00:00:00Z AND id =: 'a21S00000011whx'];

        List <Project_Contacts__c> projectContactList = [ SELECT id, Email__c, Project_Contact__c FROM Project_Contacts__c WHERE project__c IN: lsProject And Project_Deliverables__c = true ];

        EmailTemplate et = [select id from EmailTemplate where DeveloperName =:'IMR_Scheduled_Email_Alert'];
        string [] toaddress= New string[]{};
            List <Id> lsAccTeamUserIds = new List <id>();

            for (pse__proj__c project : lsProject){
                ccEmailAddress.add(project.pse__Account__r.Account_Manager__r.Email);

                lsAccountIds.add(project.pse__Account__c);

            }

        List <AccountTeamMember> lsAccountTeam = [ SELECT UserId FROM AccountTeamMember WHERE AccountId IN: lsAccountIds AND TeamMemberRole = 'Sales Engineer' ];

        for (AccountTeamMember Tmember : lsAccountTeam ){
            lsAccTeamUserIds.add(Tmember.UserId);
        }
        List <User> lsTeam = [ SELECT Email FROM User WHERE Id IN: lsAccTeamUserIds ];

        for (User u : lsTeam){
            ccEmailAddress.add(u.Email);
        }

        System.debug('Before enetered for');

        try {

            for(pse__Proj__c project :lsProject){

                System.debug('enetered for');

                if(project.pse__Practice__c == 'a20360000016A8M' && project.Service_Type__c == 'Incident Management Retainer (IR)' && project.pse__Region__c != 'a2N36000001Yo8H' && project.pse__Is_Active__c == true ){
                    if(project.Remaining_Project_Hours__c >= 80.00 && project.Remaining_Project_Hours__c <= 159.00){

                        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();

                        system.debug('Remaining Hours Between 80 to 159');

                        for (Project_Contacts__c pc : projectContactList) {
                            system.debug('Contact Email: '+pc.Email__c);
                            toAddress.add(pc.Email__c);
                            email.setTargetObjectId(pc.Project_Contact__c);
                        }

                        email.setToAddresses(toAddress);

                        email.setCcAddresses(ccEmailAddress);

                        System.debug('Expiry Calculation: '+(project.pse__End_Date__c.DayOfYear()-Date.today().DayofYear()));

                        //120 Days For Expiry
                        if(project.pse__End_Date__c.DayOfYear()-Date.today().DayofYear()==120){
                            email.setTemplateId(et.Id);
                            Messaging.sendEmail(New Messaging.SingleEmailMessage[]{email});
                            system.debug('sent');
                        }

                        //105 Days for Expiry
                        if(project.pse__End_Date__c.DayOfYear()-Date.today().DayofYear()==105){
                            email.setTemplateId(et.Id);
                            Messaging.sendEmail(New Messaging.SingleEmailMessage[]{email});
                            system.debug('sent');
                        }

                        //90 Days For Expiry
                        if(project.pse__End_Date__c.DayOfYear()-Date.today().DayofYear()==90){
                            email.setTemplateId(et.Id);
                            Messaging.sendEmail(New Messaging.SingleEmailMessage[]{email});
                            system.debug('sent');
                        }
                    }

                    if(project.Remaining_Project_Hours__c >159.00){

                        system.debug('Remaining Hours Greater than 159');

                        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();

                        for (Project_Contacts__c pc : projectContactList) {
                            system.debug('Contact Email: '+pc.Email__c);
                            toAddress.add(pc.Email__c);
                            email.setTargetObjectId(pc.Project_Contact__c);
                        }

                        email.setCcAddresses(ccEmailAddress);
                       email.setToAddresses(toaddress);

                        System.debug('Expiry Calculation: '+(project.pse__End_Date__c.DayOfYear()-Date.today().DayofYear()));

                        //150 Days For Expiry
                        if(project.pse__End_Date__c.DayOfYear()-Date.today().DayofYear()==150){
                            email.setTemplateId(et.Id);
                            Messaging.sendEmail(New Messaging.SingleEmailMessage[]{email});
                            system.debug('sent');
                        }

                        //135 Days For Expiry
                        if(project.pse__End_Date__c.DayOfYear()-Date.today().DayofYear()==135){
                            email.setTemplateId(et.Id);
                            Messaging.sendEmail(New Messaging.SingleEmailMessage[]{email});
                            system.debug('sent');
                        }

                        //120 Days For Expiry
                        if(project.pse__End_Date__c.DayOfYear()-Date.today().DayofYear()==120){
                            email.setTemplateId(et.Id);
                            Messaging.sendEmail(New Messaging.SingleEmailMessage[]{email});
                            system.debug('sent');
                        }
                     }
                }
            }

        }
        catch(Exception e){
            system.debug('Exception'+e.getMessage());
            system.debug('Exception'+e.getLineNumber());
        }

    }

}

Following is the email template

<messaging:emailTemplate subject="Retainer hours expiring reminder email" recipientType="Contact" relatedToType="Project__c">
    <messaging:htmlEmailBody >
        <html>
            <body>
                <p>Hello {!recipient.Name},</p>
                <p>The Project {!relatedTo.Name} has {!relatedTo.Remaining_Project_Hours__c} remaining hours to expire </p>
            </body>
        </html>
    </messaging:htmlEmailBody>
</messaging:emailTemplate>
  • What is not working the way you expect it to? Is the email being sent to the correct reciepients? Associated with the correct record(s)? Please edit your question to clarify what the problem is. – Thomas Taylor Jul 22 at 9:25
  • Hi Thanks for the reply Thomas. The email is sent to correct recipients but it does not display the project name and remaining hours – Umair Ayaz Jul 22 at 9:39
1

You need to use the setWhatId() method to associate the email with the Project__c record.

Also, you shouldn't be calling email.setTargetObjectId(pc.Project_Contact__c); in a for loop - setTargetObjectId() should be set just once for the email. You can add additional recipients to the To and Cc headers, as you are doing, but only one TargetObjectId, which will populate the {!recipient.Name} in your email.

If you want each recipient to receive the email with their own name merged in, then you'll need to create a List of Messaging.SingleEmailMessages, one for each recipient.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.