EXM - Send Email Programmatically
Suppose you are working on University website where you have to send a congratulation email upon every successful enrollment of a student in your system. In order to implement this first create a Email Campaign in sitecore. You can find all the details related email campaign here.
Now, you have to send an email through code. You must have student email address to create contact. Other thing that you have to make sure to define token in automated email campaign message and use it in code to replace with actual value.
MessageItem message = Sitecore.Modules.EmailCampaign.Factory.GetMessage("MessageTemplateId");
var customTokens = new Dictionary<string, object>
{
{ "StudentName", "Adam" },
{ "EnrollmentDate", "04/05-2019" }
}
new EmailManager().SendMessage(message, "studenemail@test.com", customTokens);
EmailManager class implementation url :
namespace University.EXM.Manager
{
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using Sitecore;
using Sitecore.DependencyInjection;
using Sitecore.EmailCampaign.Cd.Services;
using Sitecore.EmailCampaign.Model.Messaging;
using Sitecore.XConnect;
using Sitecore.XConnect.Client;
using Sitecore.XConnect.Collection.Model;
public class EmailManager {
private readonly IClientApiService _clientApiService;
private Contact _contact;
private const string Identifier = "test";
private const string EmailDescription = "test";
public EmailManager()
{
this._clientApiService = ServiceLocator.ServiceProvider.GetService<IClientApiService>();
}
public bool SendMessage(string messageId, string emailAddress, IDictionary<string, object> tokens)
{
IdentifyContact(emailAddress);
MissingThenCreateContact(emailAddress);
return result = DispatchEmail(messageId, emailAddress, tokens, false);
}
private bool DispatchEmail(string messageId, string emailAddress, IDictionary<string, object> tokens, bool result)
{
try
{
var contact = this._contact;
if (contact != null)
{
var messageInfo = new AutomatedMessage
{
MessageId = new Guid(messageId),
ContactIdentifier = contact.Identifiers.First(),
CustomTokens = tokens,
TargetLanguage = "en"
};
this._clientApiService.SendAutomatedMessage(messageInfo);
}
result = true;
}
catch (Exception exception)
{
}
return result;
}
private void MissingThenCreateContact(string emailAddress)
{
if (this._contact?.Identifiers?.Count == 0 || this._contact == null)
{
this._contact = this.CreateContact(emailAddress);
}
}
private void IdentifyContact(string emailAddress)
{
using (XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
{
try
{
var reference = new IdentifiedContactReference(Identifier, emailAddress);
this._contact = client.Get<Contact>(reference, new ContactExpandOptions() { });
}
catch (XdbExecutionException ex)
{
}
}
}
private Contact CreateContact(string email)
{
using (Sitecore.XConnect.Client.XConnectClient client =
Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
{
try
{
var identifier = new ContactIdentifier(Identifier, email, ContactIdentifierType.Known);
var newContact = new Contact(identifier);
client.AddContact(newContact);
var personalInfoFacet = new PersonalInformation()
{
PreferredLanguage = Context.Language.Name
};
var reference = new FacetReference(newContact, PersonalInformation.DefaultFacetKey);
client.SetFacet(reference, personalInfoFacet);
var emails = new EmailAddressList(new EmailAddress(email, true), EmailDescription);
client.SetFacet(newContact, emails);
client.Submit();
return newContact;
}
catch (XdbExecutionException ex)
{
return null;
}
}
}
}
}
One typo in this article - we have to pass MessageItemId in first line of code instead of MessageTemplateId