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

Need help sending email via apex using a regular email template? Kudos of help!

The following code works as far as attaching a visualforce pdf and emailing it to who I want.  


What I need help with is that I would like to build a regular HTML email template and call it from my code.


Anyone that contributes will get kudos.


Here is the code:


 public PageReference emailPDF() {
    List<Contract> ContractToUpdate = new List<Contract>();
    for(Contract c : [Select Id, Invoice_Sent__c from Contract where Id =:ParentId])
            c.Invoice_Sent__c = True;

    update ContractToUpdate;
     ToAddresses = new List <String>();
     Subject = 'Hope this works';
     Body = 'This is a test';
     Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
     PageReference pdf = Page.ContractPDFCreation;
     Blob b; 

        b = pdf.getContent();

     Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
     email.setSubject( subject );
     email.setToAddresses( ToAddresses );
     email.setPlainTextBody( body );
     email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa}); 
     Messaging.SendEmailResult [] r = 
     Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email}); 
     return new PageReference('/'+parentId); 

 Thank you,

Steve Laycock



Best Answer chosen by Admin (Salesforce Developers) 

Try adding


setTargetObjectID( CONTACT ID);


//Set it to any contact if you are not using merge fields from contact


then add the 


setWhatID(ID of the Contract object);


then use




In theory it will work just fine.


The only other way is to use a VF template.