0

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!

1 Answer 1

5

This is expected behavior the User fields you are referencing are the sending user fields

User fields are also known as Sending User fields for administrators and users with the “Manage Users” permission. Use them in email templates when referencing the person sending the email.

https://help.salesforce.com/articleView?id=merge_fields_email_templates_cex.htm&type=5 under General section

Try using the {!Receiving_User.field_name} fields instead

3
  • Does it mean that it is impossible to reference User fields for other user records?
    – vt89
    Nov 14, 2019 at 9:52
  • 1
    No, I don't believe so I've added a solution I think will work but haven't tried. See updated reply.
    – thegogz
    Nov 14, 2019 at 9:54
  • Great! It works. Thank you so much for your time.
    – vt89
    Nov 14, 2019 at 9:58

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.