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

Sitecore 8 EXM Get the email recipient from a Sublayout

$
0
0

The Sitecore 8 Email Experience Manager (EXM) is not only about sending bulk emails. It can be used to send one-time messages like “Thank you for signing up” or “forgot your password?” directly from code.

In the previous versions of EXM, back when it was called ECM, the sublayouts of an email could get the email address of the recipient directly from the querystring parameter “ec_recipient“. But with the introduction of the xDB and the Contacts, things have complicated.

This method will return the username (not the email address) of the recipient of the email:

using System;
using System.Text;
using System.Web;
using Sitecore;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Modules.EmailCampaign;
using Sitecore.Modules.EmailCampaign.Core;
using Sitecore.Modules.EmailCampaign.Factories;
using Factory = Sitecore.Configuration.Factory;

namespace MyEXMService
{
  public class RecipientService
  {
    public string GetRecipientName(HttpRequest request)
    {
      string contactIdValue = request.QueryString[GlobalSettings.AnalyticsContactIdQueryKey];
      string itemId = Context.Request.QueryString["sc_itemid"];
      Item messageItem = Factory.GetDatabase("master").GetItem(ShortID.Parse(itemId).ToID()).Parent;
      Guid messageIdGuid = messageItem.ID.Guid;
      Guid contactId;
      using (GuidCryptoServiceProvider provider = new GuidCryptoServiceProvider(Encoding.UTF8.GetBytes(GlobalSettings.PrivateKey), messageIdGuid.ToByteArray()))
      {
        contactId = provider.Decrypt(new Guid(contactIdValue));
      }
      string contactName = EcmFactory.GetDefaultFactory().Gateways.AnalyticsGateway.GetContactIdentifier(contactId);
      return contactName;
    }
  }
}

With the username in hand, you can either look up the user in the Contacts xDB database, or in the .NET membership database:

RecipientService receipientService = new RecipientService();
string userName = receipientService.GetRecipientName(Request); 
MembershipUser user = Membership.GetUser(userName);

MORE TO READ:



Viewing all articles
Browse latest Browse all 285

Trending Articles