+ Start a Discussion
Staci CaraStaci Cara 

query recipients of an Email Alert/Template

Hi all, 

I want to send an email template to the user that is saved in the recipient field of Email alert. 
I don't know how to query the user in order to put him into:  mail.setToAddresses(user.email);    or  mail.setTargetObjectId(user.id);
Could please someone help me?

So far I have: Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
EmailTemplate template = [SELECT Id, Name, Body, Subject FROM EmailTemplate WHERE DeveloperName = : 'MyEmailTemplate']; EmailMessage message = [SELECT Id, TextBody, Subject, ToAddress FROM EmailMessage WHERE Subject =: template.subject];
mail.setTemplateId(template.id);
mail.setSubject(template.subject);
mail.setBody(template.body)
//mail.setTargetObjectId(recipient.id);
mail.setToAddresses(message.toAddress); //at this point it would need a user.email that I don't know how to query
mail.saveAsActivity = false;
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});

Can please someone help?

Thank you in advance.