Import subscribers with custom fields
With Sitefinity CMS, you can import and export subscribers to mailing lists. You may also have subscribers with custom fields, for example, Phone number or Company. By default, Sitefinity CMS does not take any custom fields during import or export of subscribers.
You can import subscribers with custom fields by creating a separate user widget or page for this specific purpose. The following code sample demonstrates how to import subscribers' list in Sitefinity CMS from the MySubscribers CSV file:
using System;
using System.IO;
using System.Linq;
using Telerik.Sitefinity.Model;
using Telerik.Sitefinity.Modules.Newsletters;
namespace SitefinityWebApp
{
public class CustomSubscribersImport : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var newsLetterManager = NewslettersManager.GetManager();
var filePath = Server.MapPath("~/App_Data/Sitefinity/MySubscribers.csv");
using (var file = File.OpenText(filePath))
{
var lineEntry = file.ReadLine();
var fieldNames = lineEntry.Split(new string[] { delimiter }, StringSplitOptions.None);
lineEntry = file.ReadLine();
while (lineEntry != null)
{
var fieldData = lineEntry.Split(new string[] { delimiter }, StringSplitOptions.None);
var subscriber = newsLetterManager.CreateSubscriber(true);
for (int i = 0; i < fieldNames.Count(); i++)
{
if (subscriber.DoesFieldExist(fieldNames[i]))
subscriber.SetValue(fieldNames[i], fieldData[i]);
}
newsLetterManager.SaveChanges();
lineEntry = file.ReadLine();
}
}
}
private readonly string delimiter = ", ";
}
}
In the code above, you get an instance of the NewslettersManager class, which you later use to create new subscribers. To open a CSV file, you use the File class and read the contents of the file line by line. In this example, the first line contains column headers that correspond to the field names of subscribers, for example First name and so on. The rest of the lines in the CSV file contain the field data for each subscriber, including the custom fields. Using the CreateSubscriber method of the the newsletters manager, you create a new subscriber and set the desired field values. Finally, you save the changes of a the newsLetterManager class.