+ Start a Discussion

Using Email templates in Apex Code and change template values dynamically

I have created an email template where I wanted to have  values from 3 different objects(Contact, Opportunity, Custom_Obj__c)


Is there anyway  I can dynamially change the values of the template?


Any sample code would be appriciated.


thanks in advance.


Check out the documentation on APEX Email Classes HERE  .


Here is some example code to get you started.



Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setTemplateId(*put id of template here*);
mail.setwhatid(*put id of object record here*);





Thsnk you for your response

The basic emailing code I have got.

SetWhatId only we can set one type of objectid? How to set ids of 3different objects?

 I have 3 different objects how to put the values of 3 different objects and how can I replace the values dynamically on the template. ?


Is there any code you can send to me assigns values using apex code...?


You can only assign one object to the template but you can then traverse the relationships of that object to other objects.  So, for example, you could set the whatID to an opportunity in your apex code.  In your template you could then reference the opportunity via !RelatedTo.<fieldname> if you are using a visualforce template or !Opportunity.<fieldname> if you are using an HTML template.  Furthermore, if you wanted to access a second object like, say, the primary contact of the opportunity you could do !RelatedTo.Contact.FirstName in the template; you could even take the traversal deeper and get to the Account of the Contact !RelatedTo.Contact.Account.Name.


Because you are using a template you do not need to and cannot assign values through apex as far as I know.  You set the whatID and let the template do the rest of the work.  There have been some cases where i needed greater flexibility in the creation of the email so I used apex to build an HTML email and did not even use a template - this may be the  path for your needs.





I wanted to use Massemail functionality and wanted to use custom object values based on certain criteria from differnt objects. Massemail  only I think I have the option template. When I assign anything else get error.

Is there anyotherway I could assign values to the template fields?


I know of no other way.   :(