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
priyanka.mv26priyanka.mv26 

Sending VisualForce Email template from trigger

I am trying to send an email from trigger using SingleEmailMessage.

 

As of now, I am composing my email body using the method setHTMLBody inside the trigger itself and the email recipients are user, contact and some hard-coded email address also.

 

My email has many recipients and I have some complex logic so i have to go for visualforce email template.

 

While i tried, I found the following points:

1. I have to use singleemailmessage only as i have to use VisualForce email template

2. More than one id cannot be added in the setTargetObjectId method so I cannot mail to more than one person.

3. Also if i use email template, i have to specify the recipient type as User/Lead/Contact but in my case I have to send email to user & contact & some email address. As of now, i am doing it using setToAddresses method.

 

Now, is it possible to replace the email body using VisualForce email template instead of composing it using setHTMLBody method?

Deshraj KumawatDeshraj Kumawat

Yes priyanka, you are right about VisualForce email templates:-

More then one id can not be set in to the setTargetObjectId and Also if you use email template, you have to specify the recipient type as User/Lead/Contact.

 

So you need to set the body using the setHTMLBody () method only but you can avoiod the afforts you are putting in creating the HTML body in the triugger.

 

What you need to do is :-

 

1.) Create a visualforce email template that will have all the layout formating and use indentifiers for the information you would like to change dynamically in the trigger.

i.e. if you want to show the Contact Name in the email template and your email. use  tetx [Contact Name] in ur email template.

 

2.) Get the email template body in the trigger by doing a query on the Email Template object. you will get the tamplate body as html string.

 

3.) Replace the indenfiers with the actual value using the String's replace() methods.

ie. bosyString  =  bodyString.replace('[Contact Name]', actual value of contact namei.e Contact.Name);

 

4.) Use this bodyString to set the HTML body of your email.

 

Thank You !!

 

Thanks & Regards,

Deshraj Kumawat

Certified Developer | Certified Administrator

Deshraj KumawatDeshraj Kumawat

Please mark this as solution if you find it usefull so other users can get the benefit.

 

Thanks

Deshraj Kumawat