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
kgrasukgrasu 

Can I use email templates for custom objects, from a trigger or apex class?

Hi,
 
We need to use salesforce email templates from a trigger or Apex class. The template has most of the merge fields from a custom object named "Assignment__c" and the email needs to be sent to the custom email field in another custom object named "Contractor__c".
 
Is this possible using the following code snippet?  We tried it but was throwing exception saying that it supports only standard objects by Users, Lead and Contacts.
 
   mail.setTemplateId(templateId);
   mail.setTargetObjectId ('01I700000002M9A');
   mail.setWhatId(AssignmentId);
 
Any help or guidelines with some sample code on how this can be done will be greatly appreciated. Thanks and let me know if you need any other information.
 
Regards,
Rasu
EmsEms
Did you ever resolve this question? I'm trying to do exactly the same thing and I'd love to hear how you solved it!
sureshcsksureshcsk

Hi

I dont know whether this help you...!!!??

In the Email template I added {!Contact.name},the email is sent throught Apex coding.
We need to merege {!Contact.name} before the email is sent.

Logic:
1.check whether the template contains the {!Contact.name} .
2.If so replace the {!Contact.name}  with Contact.Name which is got by quering.
3.Then pass the replaced template to mail body.

so in Apex I just made a simple code as follows
public class Mail_Contorller
{
String contact_fullname;
Boolean contact_fullname_result;

contact_fullname='{!Contact.Name}';

/**checking whether {!Contact.name} is present in the template**/
contact_fullname_result=template_body.contains(contact_fullname);

if(contact_fullname_result)
{
usercontact = [Select name From Contact Where email =: email_id;
template_body=template_body.replace(contact_fullname,usercontact.name);
}

Then pass the replaced template_body to Mail Message body.
Like this you can check '{!Contact.LastName}','{!Contact.FirstName}'...etc

cheers
suresh