sitecoresitecore-ecm

Add recipients to existing recipient list with C# code - Sitecore Email campaign manager


I want to add new recipients to existing recipientlist using code. I tried with below code but it didnt work.

TargetAudience recipientList = Factory.GetTargetAudience("RecipientListId");
if ((recipientList != null))
{
       Contact contact = //I dont know how to create object for this, because it is protected class
       contact.Profile.Email = "my Email";
       contact.Profile.Name = "My Name";
       contact.Profile.FullName = "Full Name";
       recipientList.Subscribers.Add(contact);
 }

Please help me to acheive this,

Thanks in advance


Solution

  • You can get a contact from the username of the user. This method gets the contact by email address and contains code to get the username from the email address.

     public Contact GetContact(string email)
     {
            // managerRoot is the top level ECM item
            ManagerRoot managerRootFromId = Factory.GetManagerRootFromID(managerRoot.ID.ToString());
            var username = Util.AddressToUserName(email);
            string commonDomain = managerRootFromId.Settings.CommonDomain;
            string fullName = commonDomain + "\\" + Util.AddressToUserName(username);
    
            if (User.Exists(fullName))
            {
                return Contact.FromName(fullName);
            }
            return null;
        }
    

    You should then be able to add the Contact to the subscription list.

    Or once you have the Contact you can set the profile values and use the subscribe method.

    contact.InnerUser.Profile["Fullname"] = string.Format("{0} {1}",person.Firstname,person.Surname);
    contact.Subscribe(subscriptionLists);
    

    You can also add ECM users by using the following code supplying the email address as the localname.

     protected static Contact CreateAnonymousECMUser(string localName, ManagerRoot root)
     {
            Contact contact = (Contact)null;
            if (root != null && !string.IsNullOrEmpty(localName))
            {
                string commonDomain = root.Settings.CommonDomain;
                Assert.IsNotNullOrEmpty(commonDomain, EcmTexts.Localize("The Common Domain setting is not set.", new object[0]));
                string str = commonDomain + "\\" + Util.AddressToUserName(localName);
                while (User.Exists(str))
                    str = str + "_";
                string password = new PasswordGenerator()
                {
                    MinimumCharacters = 14
                }.Generate();
                System.Web.Security.Membership.CreateUser(str, password, localName);
                contact = Contact.FromName(str);
                contact.Profile.ProfileItemId = root.Settings.SubscriberProfile;
                contact.Profile.Save();
            }
            return contact;
      }