Salesforce: Send Email when Adding Contact to Event in Apex

In this post, we are going to see how to write Apex code so that when a Contact gets invited to an Event, he or she receives an email with the details of the event.

This is important because contacts typically are not users of our Salesforce org, therefore, they have no access to Salesforce calendar functionality, which means they have no way to find out they have been invited to an event.  So, when we are building a custom applications that uses events and contacts, we may want to leverage from this capability of Salesforce.

In order to be able to accomplish that, we need to use Database.DMLOptions class. This class allows us to configure certain functionalities when a DML operation occurs. In our case, we are going to set it in a way that an email gets sent when we add a contact to an event. Then, you need to pass the instance of the Database.DMLOptions to the Database.Insert.

To make the example simple, I’ll just create an Event, and immediately add the Contact Invitee. Here is some example code that accomplish this:

public class ContactToEvent {
   public static void AddContactToEventExample(){
      Event ev = new Event();
      ev.Subject = 'Test Subject';
      ev.Description = 'description';
      ev.Location = 'location';
      ev.StartDateTime =;
      ev.EndDateTime =;
      insert ev;

      // Here below is the code that 'invites' the contact
      Database.DMLOptions dmo = new Database.DMLOptions();
      dmo.EmailHeader.triggerOtherEmail = true;

      List relations = new List();
      EventRelation r = new EventRelation();
      r.EventId = ev.Id;

      // The RelationId field can have the Id of a User, Contact or Lead.
      // In our case we are using the Id of a Contact as an example.
      // If you want to invite several people, create one EventRelation
      // for every single person to be invited to the event.
      r.RelationId = '0036A00000QvmLX';
      database.insert(relations, dmo);

As you can see, all you have to do is to set the EmailHeader.triggerOtherEmail to true and Salesforce will handle the rest.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s