Category Archives: Salesforce

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 });
}

Undelete Records in Salesforce Using Batch Apex

Sample Code:

global class AccountUndeleteBatchApex implements Database.Batchable<sObject>{
    
    global Database.queryLocator start(Database.BatchableContext bc){
        String query = 'SELECT Id, Name FROM Account WHERE IsDeleted = True ALL ROWS';
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext bc, List<Account> scope){
        List<Account> accList = new List<Account>();
        for(Account s:scope){
            //Write your logic
            accList.add(s);
        }
        Undelete accList;
    }
    
    global void finish(Database.BatchableContext bc){
        
    }
}