+ Start a Discussion
Noor FazliNoor Fazli 

Example of Sending Email to a Profile using Template in Apex controller


Is there any example code that could be used to send Emails to a selected Profile(all the members in Profile) members with the email template(containing merged Fields) using apex Code in controller. I can find examples using hardcoded emails in code but couldn't find something relevant to my needs. Any pointer will be highly appreciated. Preferably in Java.

sandeep sankhlasandeep sankhla
Hi Noor,

Please check the below link and let me know if it works for you..


instead of hardocding you can simply collect all emails in list of string and then you can assign that list for sending an email...

Please mark this as solved if it works for you.
Below is the sample code which will send email to system administrator profile users
List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage> ();
List<Profile> userProfile = [select id from profile where Name='System Administrator'];
// getting email template id
List<Id> emailTemplateId = [select id from EmailTemplate where DeveloperName='My_Email_Template'].id; 
for(User sysAdminUser :[Select id from user where ProfileID IN:userProfile]) {
 Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
 string body = 'Hi '+ sysAdminUser.LastName;
 mail.setSubject('Test Subject');
 // assign user
 //email template id
 //this is used to merge field values in email template
 mail.setWhatId( [select id from Account limit 1].id ); 


Salesforce Technical Consultant
Noor FazliNoor Fazli
thanks sandeep and Karanraj for your replys. I have a question though How could we send the Emails to all the members in Public Group? Any thoughts on that.
How to route them to the Queue? or example if there is a lead that came in to the Queue that they are members of?