Tag Archives: Public Group

Send Email to a Public Group Using Apex in Salesforce

Sample Code:

//Get Email Addresses
public List<String> getMailAddresses(){
    List<String> idList = new List<String>();
    List<String> mailToAddresses = new List<String>(); 
    
    Group gp = [SELECT (SELECT UserOrGroupId FROM GroupMembers) FROM Group WHERE Name = 'MyPublicGroup'];
    for (GroupMember gm : gp.GroupMembers) {
        idList.add(gm.UserOrGroupId);
    }
    List<User> userList = [SELECT Email FROM User WHERE Id IN :idList];
    for(User u : userList) {
        mailToAddresses.add(u.email);
    } 
    return mailToAddresses;
}

//Send Email
public void sendMail() {
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    mail.setToAddresses(getEmailAddresses());
    mail.setSubject('This is the subject');
    mail.setPlainTextBody('This is the body.');
    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}