Sitecore 9 Forms Part-3 – Send EXM E-mail Submit Action

Hello Sitecorians,

EXM can only send e-mails to a known contact. Sending the e-mails to the current user, should be registered as a contact in Sitecore. We can’t send the EXM e-mail while submitting the form.For this required to update the contact .In this custom action while submitting the form we will just update the contact and also send the EXM e-mail.

Sitecore 9 Forms introduced the few submit actions.Also there is one “Send Email Campaign Message” action .We can send the email to only predefined fixed  contacts from this action.

How to Solve this ?

To solve this problem we have to create the custom submit action.What are the things need to do for this activity

  1. Create the speak editor control for SendEmail action
  2. Create custom submit action class
  3. Create the client script for the editor
  4. Create the SendEmail action item.

Create the speak editor control for SendEmail action

We require Sitecore rocks Visual studio extension to create this fast.Please follow the below steps,

For Sitecore Forms, submit action editors are located in the core database:/sitecore/client/Applications/FormsBuilder/Components/Layouts/Actions

We need the below fields in this editor

  1. Firstname mapping field
  2. Lastname mapping field
  3. Email mapping field(required)
  4. Message selection field

To create the control:

  1. Navigate to /sitecore/client/Applications/FormsBuilder/Components/Layouts/Actions.
  2. Right-click Actions, click Add, and then click New Item.

New Base

3. Select the /sitecore/client/Speak/Templates/Pages/Speak-BasePage template, and in the Enter the name of the new item field, enter SendEmail and click ok

speak base page

4. Right-click the SendEmail item you just created and click Tasks, and click Design Layout.

Design layout.jpg

5. In the Layout dialog box, navigate to /sitecore/client/Speak/Layouts/Layouts and select the Speak-FlexLayout layout and click OK.

Layout selection

6. In the upper-left corner, click Add Rendering and in the Select Renderings dialog box, click All and search for PageCode:


7. Select PageCode and click OK.

8. In the PageCode rendering properties, set the PageCodeScriptFileName property to the JavaScript path that contains the page code script:


9. Set the SpeakCoreVersion property to Speak 2-x.

10. Search for and select the Text View rendering and click Add to add three items: HeaderTitleHeaderSubtitle, and ValueNotInListText.


11. For the three items, in the Properties section, set the following ID properties:

  • IsVisible – False
  • PlaceholderKey – Page.Body

12. Add the following renderings:

  • MainBorder of type Border.
  • MapContactForm of type Form. Set the FieldsLayout property to 1-1-1-1 and set the PlaceholderKey property to MainBorder.Content.

13. Click Add Rendering and in the Select Renderings dialog box, click All and search for GenericDatasource and set Id property as MessageDataSource


14. Your final rendering should be look like below.


Next, you must add a folder that contains the parameters for the editor.

To add the PageSettings folder:

  1. Navigate to /sitecore/client/Applications/FormsBuilder/Components/Layouts/Actions, and right-click the SendEmail item you created earlier, click Add, and click New item.
  2. Search for and select the PageSettings template, enter the name PageSettings and click OK.


3. Right-click the PageSettings item that you just created and click AddNew Item.

4. Search for and select the Text Parameters template and click Add three times and          name the items exactly the same as in the IDs in the layout you created previously:

  • HeaderTitle – double-click and in the Text field enter: Map form fields to contact details.
  • HeaderSubtitle – double-click and in the Text field enter: Map the fields in the form to the contact details that you want to update.
  • ValueNotInListText – double-click and in the Text field enter: value not in selection list.


5.  Right-click the PageSettings item that you just created and click AddNew Item and Search “GenericDataSource Parameters” and name it as MessagesDataSource.


6. Set the Service Url to “/sitecore/api/exm/campaigns/automated”


7. Navigate to /sitecore/client/Applications/FormsBuilder/Components/Layouts/Actions and right-click the PageSettings item that you just created.

8. Click New Folder and name it MapContactForm.

9. Click the MapContactForm folder and add three FormDropList Parameters templates with the following field values:


mapping field

10. Click the MapContactForm folder and add the FormDropList Parameters templates and name it Message and set the below values.

  • ValueFieldName – Id
  • DisplayFieldName – Name
  • Form Label – Select email campaign message
  • BindingConfiguration – messageId/Selectedvalue

Message Binding

11. Navigate to the SendEmail layout and set the Form rendering ConfigurationItem property to the ID of the MapContactForm folder that contains the FormDropList parameters.


12. Navigate to /sitecore/client/Applications/FormsBuilder/Components/Layouts/Actions and right-click the PageSettings item that you created earlier.

13. Add a new item named Stylesheet of type Page-Stylesheet-File


14. Set the Stylesheet value to “/sitecore/shell/client/Applications/FormsBuilder/Layouts/Actions/Actions.css”

action css

Now our sitecore side work is done.Lets start the coding

To create a submit action class:

  1. Create the SendEmail class and inherit from the SubmitActionBase<TParametersData> class.
  2. Specify the SendEmailData parameter.
  3. Override the Execute method.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using Sitecore.Analytics;
using Sitecore.Analytics.Model;
using Sitecore.DependencyInjection;
using Sitecore.Diagnostics;
using Sitecore.EmailCampaign.Cd.Services;
using Sitecore.EmailCampaign.Model.Messaging;
using Sitecore.ExperienceForms.Models;
using Sitecore.ExperienceForms.Processing;
using Sitecore.ExperienceForms.Processing.Actions;
using Sitecore.XConnect;
using Sitecore.XConnect.Client;
using Sitecore.XConnect.Client.Configuration;
using Sitecore.XConnect.Collection.Model;

namespace Sitecore.Scientist.Forms.SubmitActions

    /// <summary>
    /// Submit action for updating <see cref="PersonalInformation"/> and <see cref="EmailAddressList"/> facets of a <see cref="XConnect.Contact"/>.
    /// </summary>
    /// <seealso cref="Sitecore.ExperienceForms.Processing.Actions.SubmitActionBase{SendEmailData}" />
    public class SendEmail : SubmitActionBase<SendEmailData>
        private readonly IClientApiService _clientApiService;
        /// <summary>
        /// Initializes a new instance of the <see cref="SendEmailData"/> class.
        /// </summary>
        /// <param name="submitActionData">The submit action data.</param>
        public SendEmail(ISubmitActionData submitActionData) : base(submitActionData)
            _clientApiService= ServiceLocator.ServiceProvider.GetService<IClientApiService>();
        /// <summary>
        /// Gets the current tracker.
        /// </summary>
        protected virtual ITracker CurrentTracker => Tracker.Current;
        /// <summary>
        /// Executes the action with the specified <paramref name="data" />.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <param name="formSubmitContext">The form submit context.</param>
        /// <returns><c>true</c> if the action is executed correctly; otherwise <c>false</c></returns>
        protected override bool Execute(SendEmailData data, FormSubmitContext formSubmitContext)
            Assert.ArgumentNotNull(data, nameof(data));
            Assert.ArgumentNotNull(formSubmitContext, nameof(formSubmitContext));
            var firstNameField = GetFieldById(data.FirstNameFieldId, formSubmitContext.Fields);
            var lastNameField = GetFieldById(data.LastNameFieldId, formSubmitContext.Fields);
            var emailField = GetFieldById(data.EmailFieldId, formSubmitContext.Fields);
            if (firstNameField == null && lastNameField == null && emailField == null)
                return false;
            using (var client = CreateClient())
                    var source = "Subcribe.Form";
                    var id = CurrentTracker.Contact.ContactId.ToString("N");
                    CurrentTracker.Session.IdentifyAs(source, id);
                    var trackerIdentifier = new IdentifiedContactReference(source, id);
                    var expandOptions = new ContactExpandOptions(
                    Contact contact = client.Get(trackerIdentifier, expandOptions);
                    SetPersonalInformation(GetValue(firstNameField), GetValue(lastNameField), contact, client);
                    SetEmail(GetValue(emailField), contact, client);
                    if (data.MessageId == Guid.Empty)
                        Logger.LogError("Empty message id");
                        return false;
                    ContactIdentifier contactIdentifier = null;
                    if (contact != null)
                        contactIdentifier = contact.Identifiers.FirstOrDefault<ContactIdentifier>((ContactIdentifier c) => c.IdentifierType == ContactIdentifierType.Known);
                    if (contactIdentifier == null)
                        Logger.LogError("Contact id is null.");
                        return false;
                        _clientApiService.SendAutomatedMessage(new AutomatedMessage()
                            ContactIdentifier = contactIdentifier,
                            MessageId = data.MessageId
                    catch (Exception exception1)
                        Logger.LogError(exception1.Message, exception1);
                    return true;
                catch (Exception ex)
                    Logger.LogError(ex.Message, ex);
                    return false;
        /// <summary>
        /// Creates the client.
        /// </summary>
        /// <returns>The <see cref="IXdbContext"/> instance.</returns>
        protected virtual IXdbContext CreateClient()
            return SitecoreXConnectClientConfiguration.GetClient();
        /// <summary>
        /// Gets the field by <paramref name="id" />.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <param name="fields">The fields.</param>
        /// <returns>The field with the specified <paramref name="id" />.</returns>
        private static IViewModel GetFieldById(Guid id, IList<IViewModel> fields)
            return fields.FirstOrDefault(f => Guid.Parse(f.ItemId) == id);
        /// <summary>
        /// Gets the <paramref name="field" /> value.
        /// </summary>
        /// <param name="field">The field.</param>
        /// <returns>The field value.</returns>
        private static string GetValue(object field)
            return field?.GetType().GetProperty("Value")?.GetValue(field, null)?.ToString() ?? string.Empty;
        /// <summary>
        /// Sets the <see cref="PersonalInformation"/> facet of the specified <paramref name="contact" />.
        /// </summary>
        /// <param name="firstName">The first name.</param>
        /// <param name="lastName">The last name.</param>
        /// <param name="contact">The contact.</param>
        /// <param name="client">The client.</param>
        private static void SetPersonalInformation(string firstName, string lastName, Contact contact, IXdbContext client)
            if (string.IsNullOrEmpty(firstName) && string.IsNullOrEmpty(lastName))
            PersonalInformation personalInfoFacet = contact.Personal() ?? new PersonalInformation();
            if (personalInfoFacet.FirstName == firstName && personalInfoFacet.LastName == lastName)
            personalInfoFacet.FirstName = firstName;
            personalInfoFacet.LastName = lastName;
            client.SetPersonal(contact, personalInfoFacet);
        /// <summary>
        /// Sets the <see cref="EmailAddressList"/> facet of the specified <paramref name="contact" />.
        /// </summary>
        /// <param name="email">The email address.</param>
        /// <param name="contact">The contact.</param>
        /// <param name="client">The client.</param>
        private static void SetEmail(string email, Contact contact, IXdbContext client)
            if (string.IsNullOrEmpty(email))
            EmailAddressList emailFacet = contact.Emails();
            if (emailFacet == null)
                emailFacet = new EmailAddressList(new EmailAddress(email, false), "Preferred");
                if (emailFacet.PreferredEmail?.SmtpAddress == email)
                emailFacet.PreferredEmail = new EmailAddress(email, false);
            client.SetEmails(contact, emailFacet);
    public class SendEmailData
        public Guid FirstNameFieldId { get; set; }
        public Guid LastNameFieldId { get; set; }
        public Guid EmailFieldId { get; set; }
        public Guid MessageId { get; set; }

Now you must create the client script for the editor. In a previous step, when you created the SendEmail item, you set the path to the script as follows:


To create the script like below:

(function (speak) {
    var parentApp ='EditActionSubAppRenderer'),
     messageParameterName = "messageId";
        designBoardApp ='FormDesignBoard');
    var getFields = function () {
        var fields = designBoardApp.getFieldsData();
        return _.reduce(fields,
            function (memo, item) {
                if (item && item.model && item.model.hasOwnProperty("value")) {
                        itemId: item.itemId,
                return memo;
                    itemId: '',
                    name: ''
        function (_) {
            return {
                initialized: function () {
                        "loaded": this.loadDone
                    this.Fields = getFields();
                    this.MapContactForm.children.forEach(function (control) {
                        if (control.deps && control.deps.indexOf("bclSelection") !== -1) {
                            control.IsSelectionRequired = false;
                    var componentName = this.Form.bindingConfigObject[messageParameterName].split(".")[0];
                    this.MessagesList = this.MapContactForm[componentName];
                    this.MessagesList.on("change:SelectedItem", this.changedSelectedItemId, this);

                    this.MessagesDataSource.on("change:DynamicData", this.messagesChanged, this);
                    if (parentApp) {
                        parentApp.loadDone(this, this.HeaderTitle.Text, this.HeaderSubtitle.Text);
                        parentApp.setSelectability(this, true);
                changedSelectedItemId: function () {
                    var isSelectable = this.MessagesList.SelectedValue && this.MessagesList.SelectedValue.length;
                    parentApp.setSelectability(this, isSelectable);
                setDynamicData: function (propKey) {
                    var componentName = this.MapContactForm.bindingConfigObject[propKey].split(".")[0];
                    var component = this.MapContactForm[componentName];
                    var items = this.Fields.slice(0);
                    if (this.Parameters[propKey] &&
                        !_.findWhere(items, { itemId: this.Parameters[propKey] })) {
                        var currentField = {
                            itemId: this.Parameters[propKey],
                            name: this.Parameters[propKey] +
                                " - " +
                                (this.ValueNotInListText.Text || "value not in the selection list")
                        items.splice(1, 0, currentField);
                        component.DynamicData = items;
                        $(component.el).find('option').eq(1).css("font-style", "italic");
                    } else {
                        component.DynamicData = items;
                setMessageData: function (listComponent, data, currentValue) {
                    var items = data.slice(0);
                    items.unshift({ Id: "", Name: "" });

                    if (currentValue && !_.findWhere(items, { Id: currentValue })) {
                            Id: "",
                            Name: currentValue +
                                " - " +
                                (this.ValueNotInListText.Text || "value not in the selection list")

                        listComponent.DynamicData = items;
                        $(listComponent.el).find('option').eq(0).css("font-style", "italic");
                    } else {
                        listComponent.DynamicData = items;
                        listComponent.SelectedValue = currentValue;
                messagesChanged: function (items) {
                    this.setMessageData(this.MessagesList, items, this.Parameters[messageParameterName]);
                loadDone: function (parameters) {
                    this.Parameters = parameters || {};
                    this.MapContactForm.BindingTarget = this.Parameters;
                getData: function () {
                    var formData = this.MapContactForm.getFormData(),
                        keys = _.keys(formData);
                    keys.forEach(function (propKey) {
                        if (formData[propKey] == null || formData[propKey].length === 0) {
                            if (this.Parameters.hasOwnProperty(propKey)) {
                                delete this.Parameters[propKey];
                        } else {
                            this.Parameters[propKey] = formData[propKey];
                    return this.Parameters;

Update the CSS

You can update your custom CSS in the below path


To create the submit action item:

  1. Navigate to /sitecore/system/Settings/Forms/Submit Actions
  2. Right-click Submit Actions, click Insert, and click Insert from template.
  3. Select the /System/Forms/Submit Action template, in the Item Name field, enter the name SendEmail and click Insert.
  4. Navigate to the item you just created and in the Settings section, in the Model Type field, set the value to the class type name.

Email submit action

  1. In the Error Message field, enter an error message, for example, Sending Email failed!
  2. In the Editor field, select the editor that you just created, for example, SendEmail.
  3. In the Appearance section, select the icon that you want to display in the Form elements .

To execute this submit action , we required to create the  following things

  • Automated EXM Email Message
  • Email Subscription form

Create Automated EXM Email Message:

Initially we need to setup the EXM mail server settings.

If you are not configured the SMTP .Please follow the this blog .

automated email


I have created the automated email campaign named “welcome” without adding any recipient.

welcome automated


welcome automated detail.jpg

Create Email Subscription form

Now one thing is pending .Just create the form and add the newly created SendEmail action to submit button.

Select SendEmail


Send email mapping

Select the “Welcome Automated” and click OK.Save the form changes.

Finally we are done.Lets test the functionality.

Just fill the form and submit.

testing exm

For the testing purpose , i have used the yopmail account.Now i am going to open the yopmail inbox.

testing exm mail

I got the Email through EXM . Also it should created the contacts as well. Lets check the contact as well.If its not showing in Experience Profile just wait for 10-15 minutes or close the Session.

contact details

If you check the EXM Campaign message details.It looks like below.

Email activity


If you are feeling lazy to create the above steps, then just download the sitecore packages for SendEmail submit action from  Sitecore Exm email submit

Download the Source code from Github.

Thank you visiting this blog.Please share your thoughts in comments.