[SalesForce] Passing parameters to a Visualforce email template within Apex class

I am working on setting up a scheduled apex class to send out emails to me every day. I have a visualforce template that takes a user and an opportunity as parameters that I would like to use. The scheduler works great and an email gets sent but the message body is blank. Here is my code that builds the email. Is there something I am doing wrong? I have tested the visualforce template by sending it to myself through the salesforce UI and it works fine.

          public static void mail60(Opportunity op)
{

    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
    string [] toaddress= New string[]{'my email address'};
    email.settemplateid(' template ID here'); //In the real code I have the correct IDs in place
    email.setSubject( 'Blah - Maintenance and Support Renewal');
    email.setToAddresses(toaddress);
    email.setTargetObjectId(' contact ID here '); //In the real code I have the correct IDs in place
    email.setWhatId(' opportunity ID here '); //In the real code I have the correct IDs in place
    email.saveAsActivity = false;
    Messaging.sendEmail(New Messaging.SingleEmailMessage[]{email});

}

Best Answer

There are few things wrong,

  1. when using template you dont have to set subject.
  2. When you use setTargetObjectId, your email is sent to that contact/lead or user. You dont have to set toAddress

Instead of such complex code, you can do it

Messaging.SingleEmailMessage email = 
            Messaging.renderStoredEmailTemplate(templateId, whoId, whatId);

So your code will be like

public static void mail60(Opportunity op){

    Messaging.SingleEmailMessage email = 
                Messaging.renderStoredEmailTemplate('templateId', ' contact ID here ', op.Id);

    string [] ccAddress= new string[]{'my email address'};
    email.setccAddresses(ccAddress);
    email.saveAsActivity = false;
    Messaging.sendEmail(New Messaging.SingleEmailMessage[]{email});

}

SRC: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_email_outbound_single.htm

SRC:https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_email_outbound_messaging.htm

Related Topic