I am trying to send email through email template to user but It is always replacing the user merge fields by org admin's user name instead of targetobjectID user.

Org admin : luke wright

Email template Body :

Dear {!User.Name} ,
Hearty Congratulations on this beautiful occasion. May your marriage bring great joy, love and passion in your life. I wish to God to bless you with a wonderful marriage and a happy life ahead.
Thanks and Regards.

OrgWideEmailAddress owa = [select id, DisplayName, Address from OrgWideEmailAddress limit 1];
List<Messaging.SingleEmailMessage> allmsg = new 
Messaging.SingleEmailMessage mail = new 
mail.setTemplateID('00X0S000000iBYB'); // Template Id
mail.setTargetObjectId('0050S0000023KS9'); // UserId  Name: John Doe

Issue: Dear {!User.Name} should be replace by john doe while it is replacing by luke wright and email goes to correct user i.e. john doe

P.S. User's merge fields is not replacing by that record ID


You're just using the wrong merge field. The User field tree is for the Sending User. When you edit a Classic Email Template, you'll see it listed as such in Available Merge Fields:


What you want are the Receiving User fields under Receiving_User:

Receiving User

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.