function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Noor FazliNoor Fazli 

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

Hi,

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.

Thanks
sandeep sankhlasandeep sankhla
Hi Noor,

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

https://developer.salesforce.com/forums/ForumsMain?id=906F000000090G6IAI

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.
KaranrajKaranraj
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
 mail.setTargetObjectId(sysAdminUser.Id); 
 mail.setSaveAsActivity(false);
 //email template id
 mail.setTemplateId(emailTemplateId); 
 //this is used to merge field values in email template
 mail.setWhatId( [select id from Account limit 1].id ); 
 mails.add(mail);

}
Messaging.sendEmail(mails);

Thanks,
Karanraj
Salesforce Technical Consultant
http://www.karanrajs.com
 
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.
SAHG-SFDCSAHG-SFDC
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?