Search code examples
salesforceapex-codevisualforce

Can i use a field from a custom object in an Email Templates?


I'm writing an Email template that includes merged fields,

When I add an account field it works fine,

But when I try to add a field from a custom object it does not work,

As I mentioned above I have done it manually, by setting the "Related To" to the custom object record But when I use the following code, the included field is blank in the template

Inquery__c inquery = trigger.new[0];
 String[] toAddresses = new String[] {inquery.email__c};
 Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
  mail.setTargetObjectId(inquery.OwnerID);
 mail.setSenderDisplayName('Salesforce Support');
  mail.setUseSignature(false);
  mail.setBccSender(false);
  mail.setSaveAsActivity(false);
 EmailTemplate et=[Select id from EmailTemplate where DeveloperName=:'Invitation_to_register_for_Training'];
 mail.setTemplateId(et.id);
 Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});

I tried to add the setWhatID as follows,

mail.setWhatId(inquery.OwnerID);

But it gave me an error stating: WhatId is not available for sending emails to UserIds

Thanks


Solution

  • In the method setWhatId(), you have to insert the inquery ID instead OwnerID field:

    mail.setWhatId(inquery.ID);
    

    Try to fix it.