How to send email to a public group using apex?

How to send email to a public group using apex?

Sample Class:
public class Utility {

    public static Set < Id > fetchUserIdsOfPublicGroup( Id groupId ) {
    
        Set < Id > userIds = new Set < Id >();
        Set < Id > groupIds = new Set < Id >();
        groupIds.add( groupId );
         
        do {
            
            Set < Id > tempGroupIds = new Set < Id >();

            for ( GroupMember objGM : [ SELECT UserOrGroupId FROM GroupMember WHERE GroupId IN: groupIds AND Group.Type = ‘Regular’ ] ) {
                
                String strUserOrGroupId = objGM.UserOrGroupId;
                
                if ( strUserOrGroupId.startsWith( ‘005’ ) )
                    userIds.add( objGM.UserOrGroupId );
                else
                    tempGroupIds.add( objGM.UserOrGroupId );
            
            }
            
            groupIds = tempGroupIds;
            
        } while ( groupIds.size() > 0 );

        return userIds;
    
    }
    
    public static void sendMassEmail( List < Id > userIds, Id templateId ) {

         Messaging.MassEmailMessage objMail = new Messaging.MassEmailMessage();
         objMail.setTargetObjectIds( userIds );
         objMail.setTemplateId( templateId );
         objMail.setSaveAsActivity( false );
         Messaging.sendEmail( new Messaging.MassEmailMessage[] { objMail } );   
        
    }
    
}

To Test,
Id groupId = ’00G4x000001BVLH’;
Id templateId = ’00X4x0000012FhD’;
List < Id > userIds = new List < Id >();
userIds.addAll( Utility.fetchUserIdsOfPublicGroup( groupId ) );
Utility.sendMassEmail( userIds, templateId );

Leave a Reply