2

I would know if it's possible set a "User" for an email template.

In a my email template I use {!User.Name}. I have a class and a trigger on CollaborationGroupMember and I send an email each time that a user is added in a chatter group:

Class

public with sharing class ClassToSendMail {

    public static void sendMail(String emailTemplate, String mailRecipient, Id targetObjectID) {

        Id templateId; 
        templateId = [select id, name from EmailTemplate where developername = : emailTemplate].id;

        OrgWideEmailAddress owa = [select id, Address, DisplayName from OrgWideEmailAddress limit 1];

        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        String[] toRecipients = new String[]{'[email protected]'};

        email.setToAddresses(toRecipients);
        email.setOrgWideEmailAddressId(owa.id);
        email.setTargetObjectId(targetObjectID);
        email.setTemplateId(templateId);    
        email.setSaveAsActivity(false);

        try 
        {
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
        }
        catch (EmailException e) {String errorMsg='Error in : '+e.getMessage();}
    }
}

Trigger

trigger TriggerSendMail on CollaborationGroupMember (after insert) {
    for(CollaborationGroupMember newMember : Trigger.new){
        System.debug('@@@ newMember: ' + newMember);
        User userToSendMail = [SELECT id, Email FROM User WHERE ID=:newMember.MemberID];
        ClassToSendMail.sendMail('UserAddedGroup', userToSendMail.Email , userToSendMail.Id);
    }
}

When I add an user in a chatter group, {!User.Name} is replace with name of the current user logged in org and not the user set as targetObject.

6
  • When you say current user it means the logged in user( the user in which this email will be send means the sender)? Mar 1, 2017 at 14:13
  • Did you try {!Receiving_User.Name} instead of {!User.Name}? Mar 1, 2017 at 14:22
  • 1
    @TusharSharma yes, "current user" means user logged in org.
    – vt89
    Mar 1, 2017 at 14:39
  • @MartinLezerno, I don't try {!Receiving_User.Name} but now I replace {!User.Name} with {!Contact.Name} and as targetObject I set Contact related to User and not User, and now it's ok. I don't understand why with User object not allow replace instead with Contact it works
    – vt89
    Mar 1, 2017 at 14:41
  • Glad your solution is working. It can't work with the User variable because it's related to the current user in the context. The one that triggered the send. Mar 1, 2017 at 14:45

0

You must log in to answer this question.

Browse other questions tagged .