Quantcast
Channel: Brian Pedersen's Sitecore and .NET Blog
Viewing all articles
Browse latest Browse all 286

Sitecore EXM: Send an email from code

$
0
0

The Sitecore Email Experience Manager is your way to send personalized emails to Sitecore users.   You do not need to send bulk emails, you can easily send single emails with contents like “Here is your new password” or “Your profile has been updated”.

The emails to send are “Standard Messages” so the email you create must be of the type “Triggered message”:

Triggered Message Settings

Triggered Message Settings

There is 2 ways of sending emails: To Sitecore users or Sitecore Contacts.

SEND AN EMAIL TO A SITECORE USER

Your Sitecore user must exist in the Sitecore User repository (usually as an “extranet” user).

using Sitecore.Data;
using Sitecore.Diagnostics;
using Sitecore.Modules.EmailCampaign;
using Sitecore.Modules.EmailCampaign.Messages;
using Sitecore.Modules.EmailCampaign.Recipients;

public void Send(ID messageItemId, string userName)
{
  MessageItem message = Factory.GetMessage(messageItemId);
  Assert.IsNotNull(message, "Could not find message with ID " + messageItemId);
  RecipientId recipient = new SitecoreUserName(userName);
  Assert.IsNotNull(recipient, "Could not find recipient with username " + userName);
  new AsyncSendingManager(message).SendStandardMessage(recipient);
}

You call the function like this:

Send(new ID("{12A6D766-CA92-4303-81D2-57C66F20AB12}"), "extranet\\user@domain.com");

SEND AND EMAIL TO A CONTACT

The contact must (obviously) contain an email address. To create a contact see Sitecore Contacts – Create and save contacts to and from xDB (MongoDB). The code is near identical to the previous, but the Receipient is retrieved by resolving the contact ID:

using Sitecore.Data;
using Sitecore.Diagnostics;
using Sitecore.Modules.EmailCampaign;
using Sitecore.Modules.EmailCampaign.Messages;
using Sitecore.Modules.EmailCampaign.Recipients;

public void Send(ID messageItemId, Guid contactID)
{
  MessageItem message = Factory.GetMessage(messageItemId);
  Assert.IsNotNull(message, "Could not find message with ID " + messageItemId);
  RecipientId recipient = RecipientRepository.GetDefaultInstance().ResolveRecipientId("xdb:" + contactID);
  Assert.IsNotNull(recipient, "Could not find recipient with ID " + contactID);
  new AsyncSendingManager(message).SendStandardMessage(recipient);
}

You call the function like this:

Send(new ID("{12A6D766-CA92-4303-81D2-57C66F20AB12}"), Guid.Parse("c3b8329b-7930-405d-8852-7a88ef4f0cb1"));

MORE TO READ:

 



Viewing all articles
Browse latest Browse all 286

Trending Articles