You need to sign in to do that
Don't have an account?
Sending email from apex class using template.
Hi I'd appreciate it if anybody can shed any light on this problem. I am trying to send a email from a Apex class using a template. See code below.
APEX CLASS--------------------- global someapexclass { someCustomObject cust = [Select name,attr1, attr2 from someCustomObject] for(User usr : [Select u.Id, u.email, u.name From User u where u.profile.Name = 'System Administrator']){ Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); mail.setTargetObjectId(usr.Id); EmailTemplate et = [SELECT id from emailtemplate where name='MyEmailTemp']; mail.setTemplateId(et.Id); mail.setSaveAsActivity(false); Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); } EMAIL TEMPLATE--------------------------- Dear {!usr.name} This is a test email. . Thanks.
The problem is the email is sent where the {!usr.name} not substitued at runtime hence the email just says 'Dear' instead of 'Dear <the user name>'
My question is Can I reference cust and usr (variables in the apex class) in a email template ? is this even possible ? if so what am i doing wrong. If not - then is my only alternative to set the email body at runtime inthe class and not use the template.
thanks
That merge field looks funny. It seems to be trying to refer to the Apex variable instead of just the object.
Try a more normal merge field like {!Receiving_User.Name}.
I have tried both {!User.Name} and {!usr.Name} with out luck, user being variable used in the script. Note
that I am trying to use the User objects fetched from the query.
Am what I doing fundamentally wrong... or is this the correct way to use template and that there may be something else wrong ?
Thanks
Here is one way to do it: You must get the email tample by using a SOQL query on the email Templat eobject and then use the Messaging class to send it like this segment which is based on portal user info: