How to subscribe user to newsletter using API

This article describes how to subscribe user to newsletter using API. You can use it e.g. for subscribing user to newsletter automatically after her registration (in this case you should create copy of RegistrationForm web part and use the code in its btnOK_Click method after UserInfo object for user is created and set into DB).
Basically you need to get newsletter object, get the subscriber (or create new one) object for current user in according to his e-mail and then subscribe subscriber to newsletter. Please find sample code bellow (ui is object of UserInfo class):

            //get newsletter in according to its name for current site
            CMS.Newsletter.Newsletter myNewsletter = CMS.Newsletter.NewsletterProvider.GetNewsletter("nameOfNewsletter", CMS.CMSHelper.CMSContext.CurrentSite.SiteID);

            //get subscriber in according to e-mail of current user for current site
            CMS.Newsletter.Subscriber mySubscriber = CMS.Newsletter.SubscriberProvider.GetSubscriberByEmail(ui.Email, CMS.CMSHelper.CMSContext.CurrentSite.SiteID);
            if (mySubscriber == null) //if subscriber with given e-mail doesn't exist create the new one
                mySubscriber = new CMS.Newsletter.Subscriber();
                subscriberObj.SubscriberID = 0;
                subscriberObj.SubscriberSiteID = CMS.CMSHelper.CMSContext.CurrentSite.SiteID;
                mySubscriber.SubscriberGUID = new Guid();
                mySubscriber.SubscriberEmail = ui.Email;
                mySubscriber.SubscriberFirstName = ui.FirstName;
                mySubscriber.SubscriberLastName = ui.LastName;
                //.. you can fill other properties for subscriber from ui (UserInfo) object

            //subscribe subscriber to newsletter. Last parameter says if you want to send subscription confirmation to user.
           CMS.Newsletter.SubscriberProvider.Subscribe(mySubscriber.SubscriberGUID, news.NewsletterID, true);

See also:

Applies to: Kentico CMS 4.0 or later. Should work in previous versions with newsletters module as well.
Share this article on   LinkedIn