Send An Email to User and Public Group Using Apex in Salesforce

In Salesforce, we have a flow automation feature that allows us to automate processes such as record updates, task assignments, creation of related records, and sending automated emails.

However, we can use Salesforce Apex when the logic is complex or when working with a large number of records. Triggers are written in code, which provides more control and better performance.

In this tutorial, we will learn how to send an email to user and public group using Apex in Salesforce.

Messaging.SingleEmailMessage Class in Apex

To send an email from Salesforce Apex, we need to use the Messaging.SingleEmailMessage class, which is part of Salesforce’s messaging feature and is specifically used to construct and send single email messages within Salesforce.

This class allows us to customize email properties, including recipients, subject, body, and attachments, and send emails to internal Salesforce users or external addresses.

Methods Used to Send Email in Salesforce Apex

Now let’s see some methods used in Messaging.SingleEmailMessage class in Apex that is used to assign values to emails.

1. setTargetObjectId() Method

In Salesforce Apex, the setTargetObjectId() method in the Messaging.SingleEmailMessage class is used to specify the recipient of an email message. This method identifies a Salesforce user, lead, or contact who will receive the email.

When we set the target object ID, Salesforce automatically pulls in the email address associated with that object. Also, we can retrieve the field values dynamically to add in the email template based on that specific record.

Syntax: Declaring the setTargetObjectId() Method

Using an instance of Messaging.SingleEmailMessage class, we can use the setTargetObjectId() method to add an object from Salesforce from which we want to retrieve values, fields, or email addresses.

Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();          email.setTargetObjectId ( targetObjectId );

2. setToAddress() Method

The setToAddress() method is used to set the recipient email addresses for an email we send using the Messaging class. It does not require the recipients to be Salesforce records.

The setToAddress() method is commonly used in Messaging.SingleEmailMessage or Messaging.MassEmailMessage classes are designed to facilitate sending emails using the Apex code.

Syntax: Declaring the setToAddress() Method

Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setToAddresses ( List<String> EmailAddresses );

3. setSubject() Method

In Salesforce Apex, the setSubject() method is used to set the subject line for an email message. This method takes a single parameter, a string representing the subject line of the email, and assigns it to the email message being created. This subject will appear as the email’s subject line when the email is sent.

Syntax: Declaring the setSubject() Method

emailMessage.setSubject ( String subject );   //OR

Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setSubject(String subject);

4. setPlainTextBody() Method

The setPlainTextBody() method is used in Messaging.SingleEmailMessage class to set the plain text body of an email in Salesforce.

This method is useful when you want to send a plain-text email without any formatting, which can be helpful for straightforward email clients or for cases where text formatting is unnecessary.

Syntax: Declaring the setSubject() Method

Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setPlainTextBody ( String plainTextBody );

5. Messaging.sendEmail() Method

In Salesforce Apex, the Messaging.sendEmail() method is used to send emails programmatically from Apex.

This method is from the Messaging class and allows us to send either single or bulk emails with customizable parameters, such as recipients, subject, body content, and attachments.

Syntax to Send Email:

Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();     
email.setTargetObjectId ( targetObjectId );
email.setToAddresses ( List<String> EmailAddresses );
email.setSubject(String subject);
email.setPlainTextBody ( String plainTextBody );

Messaging.sendEmail ( new Messaging.SingleEmailMessage[] {email} ); // For single Email.
Messaging.sendEmail ( new Messaging.SingleEmailMessage[] {email, email1 , email2} ); //For Sending Multiple Emails.

Below, I will create an Apex class to send an email, utilizing all these methods to demonstrate their actual use.

Send An Email to a User Using Apex in Salesforce

In the Apex helper class below, I created a class to automate the process of sending an email to the user when the Account record is created and the account priority is high.

Then, an email should be sent to the account owner to notify them that a high-priority account has been assigned to them.

First, I created an Apex helper class named SendEmailTriggerHelper and the sendEmailTrigger() method, through which we passed the List Collection of accounts named NewAccounts.

Then, in the for each loop, I created an account instance named acc and assigned NewAccounts to it. So whenever a new account is created, it will be added to the acc instance.

Then, using the if condition, we checked whether the account priority is high, and as we wanted to send an email to the account owner for that, we also checked whether the account owner should not be null.

After that, we fetched user details from the account ownerID and checked whether the owner’s email was null.

Then, I created a Massaging class instance named email. Now, using this instance, we will create the content of an email, and for that, we need to use the methods that I explained above. Then, using the email instance, we declared methods to add content to the email.

Methods we used in the Apex class:

  • setToAddresses(): We provided the account owner’s email address as the recipient’s email.
  • setSubject(): Assigned subject to the mail.
  • setPlainTextBody(): Created email body in plain text without using any HTML text.

Now, we created a List to store the email message content named eMsg and then added the email instance to the eMsg list.

In the try block, we checked whether the list we created was not empty and then added it to the Messaging.sendEmail() method to send an email.

Now, save this Trigger and deploy it to the Salesforce org.

public class SendEmailTriggerHelper {

    public static void sendEmailTrigger (List<Account> NewAccounts) {
        
        for (Account acc : NewAccounts) { 
            if (acc.Account_Priority__c == 'High' && acc.OwnerId != null) {
               
                User owner = [SELECT Email, Name FROM User WHERE Id = :acc.OwnerId LIMIT 1];
                if (owner.Email != null) {
                    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
                    
                    email.setToAddresses (new String[] {owner.Email} );
                    email.setSubject ( 'New High Value Account Assigned' );
                    email.setPlainTextBody(
                        'Hello ' + owner.Name + ',\n\n' +
                        'A new Account with High Priority has been assigned to you.\n\n' +
                        'Account Details:\n' +
                        'Name: ' +  acc.Name + '\n' +
                        'Priority: ' + acc.Account_Priority__c + '\n' +
                        'Subscription Type: ' +  acc.Type + '\n\n' +
                        'Please review and take appropriate action.\n\n' +
                        'Thank you,'
                    );
     List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
                    emails.add ( email );
                }
            }
        }
        
        try {
            if ( !emails.isEmpty() ) {
                Messaging.sendEmail ( emails );
            }
        } catch (Exception e) {
            System.debug ( 'Error in sending email: ' + e.getMessage() );
        } 
    }
}

Then, I created an Apex Trigger named SendEmail on the Account object using the after insert event because an email should be sent to the record owner when the account is created.

Then, in the if condition, we called the helper class, and the method was created in the helper class.

trigger SendEmail on Account (after insert) {
        if ( Trigger.isAfter && Trigger.isInsert ) {
               SendEmailTriggerHelper.sendEmailTrigger (Trigger.new);   
    }
}

Navigate to Salesforce org and search for Apex Triggers in the Quick Find box. Open it, select the Trigger we created, and check whether it is Active. If it is reactive, it will not work.

Send An Email to User and Public Group Using Apex in Salesforce

I created a new account record with Account Priority as High and saved the record.

Send Email from Apex Trigger in Salesforce

As you can see in the image below, I received an email notifying me that a new account was created with high priority and that we added other details to the email messaging class.

How to Send Email to User Using Apex in Salesforce

In this way, we can send emails to users using the Apex trigger and Messaging.singleEmailMessage class and its methods.

Send An Email to Public Group Using Apex in Salesforce

In the below example, we want to send email notifications to all employees who are in the sales group regarding the group meeting. I have explained the Apex code for sending an email to the public group.

Here, I created the Apex class and method with groupName as a string parameter. Then, I declared a list to store the email addresses of users in the sales group and another list to store the group members.

In for each loop, we assigned a list of group members to the SObject GroupMember instance. Then, we fetched users’ email addresses and added them to the list we created using the add() method.

Using the if condition, we checked whether the email address list was empty. After that, again, we need to create a massaging class instance and add email methods to add email content.

Then, store that content in another list and use messaging.sendEmail is the method to send emails to the users. Now, save this Trigger and deploy it to the Salesforce org.

public class SendEmailNotification {
   
      public static void SendEmail (String groupName) {

            List<String> emailAddresses = new List<String>(); 
            List<GroupMember> ListgroupMembers = [ Select UserOrGroupId  from
                                                     GroupMember WHERE Group.Name = :groupName ];
                                                                               
        for ( GroupMember gm : ListgroupMembers ) {
            
                 User user = [ Select Email from User where Id = :gm.UserOrGroupId LIMIT 1];
                 emailAddresses.add ( user.Email );
        }
        if ( !emailAddresses.isEmpty() ) {
            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
 
            email.setToAddresses (emailAddresses);
            email.setSubject ('Reminder about Sales Group Meeting');
            email.setPlainTextBody (
                'Hello +,\n\n' +
                'We are pleased to invite you to our upcoming quarterly sales meeting. ' +
                'Please make sure to attend.\n\n' +
                'Best regards,\n' +
                'Sales Team'
            );
           
List<Messaging.SingleEmailMessage> emailmsg= new List<Messaging.SingleEmailMessage>();
            emailmsg.add (email);

            if ( !emailmsg.isEmpty() ) {
                try  {
                       Messaging.sendEmail( emailmsg );
                       System.debug ('Email has been successfully sent to the account owner');
                 }
                catch (Exception e) {
                      System.debug ('Error sending email: ' + e.getMessage() );
                 }  
            }
            else {
                  System.debug ('Email Not Sent...');
             }      
        }
    }
}

In the image below, you can see there are two users in the sales group. When we execute the above code, the email should be sent to these users.

Send Email to Public Group Using Apex in Salesforce

As I executed the Apex code we created in the output, I got the success message we entered in the debug method.

Send Email from Apex in Salesforce

Here is the proof of concept that the user has got an email with the content that we provided in the apex code.

How to send email to Public group in Salesforce Apex

In this way, we can send an email to a public group using Apex in Salesforce.

Conclusion

I hope you have an idea about sending an email to the user and public group using Apex in Salesforce. I have explained the Messaging.SingleEmailMessage class and its methods for creating email content and sending emails using Apex. After that, I explained the Apex code and how to execute it.

You may like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.