I'm trying to send a Messaging.SingleEmailMessage in Apex using a Custom Email Template to a specific User and using a defined OrgWideEmailAddress.
The simple code is here:
List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setTargetObjectId('UserIdRetrievedWithASOQL');
mail.setOrgWideEmailAddressId('OWEAIdRetrievedWithASOQL');
mail.setTemplateId('EmailTemplateIDRetrievedWithASOQL');
mail.setSaveAsActivity(false);
mails.add(mail);
Messaging.SendEmailResult[] ser = Messaging.sendEmail(mails, false);
The User record is:
- Firstname: John
- Lastname: White
- Email: test@test.com
Inside the Custom Email Template I have two merged fields:
- {!User.Firstname}
- {!User.Lastname}
The issue is: when I run this code, the merged fields inside the Email Custom Template are rendered using the current user (the user invokes this Apex code) and not the user defined with the setTargetObjectId() method.
Do you have any suggestions? Thanks!