Using Kentico's Email Templates in Custom Code

by November 16, 2015 2 comments
Kentico has an email template feature that is used in many areas of the CMS. When a user registers, posts to the forum, or places an order in the E-Commerce system, they are sent an email from a predefined template that has been filled with their information. I'll show you how easy it is to leverage this feature in your own code.

First, create the email template:

















Then, this is the code to send email:

public void DoSendFormDataToEmail(string emailTo, DataRow replacement)
{
    EmailMessage msg = new CMS.EmailEngine.EmailMessage();
    CMS.EmailEngine.EmailTemplateInfo eti = EmailTemplateProvider.GetEmailTemplate(EmailTemplateCodeForSendingFormDataToEmail, SiteContext.CurrentSiteID);
    if (eti != null)
    {
        var resolver = MacroResolver.GetInstance();
        resolver.SetAnonymousSourceData(replacement);

        msg.EmailFormat = EmailFormatEnum.Both;
        msg.From = eti.TemplateFrom;
        msg.Recipients = emailTo;
        msg.Subject = eti.TemplateSubject;
        msg.Body = eti.TemplateText;

        EmailSender.SendEmailWithTemplateText(SiteContext.CurrentSiteName, msg, eti, resolver, false); 
        EventLogProvider.LogEvent("I", "Sending Newsletter Signup form data", "CREATEOBJ");
    }

}
 How to call it:

DataTable dt = new DataTable();
dt.Columns.Add("InsertedDateTime");
dt.Columns.Add("FirstNameValue");
dt.Columns.Add("LastNameValue");
dt.Columns.Add("EmailValue");
DataRow drRow = dt.NewRow();
drRow["InsertedDateTime"] = DateTime.Now.ToString();
drRow["FirstNameValue"] = sb.SubscriberFirstName;
drRow["LastNameValue"] = sb.SubscriberLastName;
drRow["EmailValue"] = sb.SubscriberEmail;
DoSendFormDataToEmail(SendFormDataToEmail, drRow);

That's all. Hope it works for you.

Note: Kentico 8.2 


For more info about Kentico Macro here:
http://devnet.kentico.com/articles/kentico-8-technology-macro-improvements
Happy Coding :)

An Nguyen

Developer

Sharing daily exciting lesson learned and posts about .NET, SQL Server, HTML, Javascript - jQuery, CSS - Bootstrap, SalesForce CRM, Kentico CMS and so on.

2 comments :

  1. Kentico 13 xperience upgrade You made such an interesting piece to read, giving every subject enlightenment for us to gain knowledge. Thanks for sharing the such information with us to read this...

    ReplyDelete
  2. Kentico Developer Very interesting and worth fully information. Great!!!

    ReplyDelete