Send email from code behind - Kentico Xperience CMS
Overview
Sometimes when developing websites you may need to send emails to recipients depends on the scenario. For example, your client wants to have integration with a 3rd party system. So you did an integration and the client want every time the integration failed, send an email to the web editor to check. So how you can achieve this in Kentico Xperience CMS.Create an Email Template.
First, you need to have an email template in Kentico Xperience CMS. You can do this by open the Email Template module and create a new template. The steps described in this link.
Create a custom static method
This method will be called when there is some error happen when integration with 3rd party system failed. (This is just a scenario mentioned in the above)
Kentico 11/10
public static bool sendEmail(string emailTemplate, string Recipients, Dictionary<string, object> dataToPass)
{
try
{
CMS.MacroEngine.MacroResolver mcr = CMS.MacroEngine.MacroResolver.GetInstance();
mcr.SetNamedSourceData(dataToPass);
CMS.EmailEngine.EmailMessage msgRecipient = new CMS.EmailEngine.EmailMessage();
CMS.EmailEngine.EmailTemplateInfo EmailTemplate = CMS.EmailEngine.EmailTemplateProvider.GetEmailTemplate(emailTemplate, CMS.SiteProvider.SiteContext.CurrentSiteID);
msgRecipient.From = EmailTemplate.TemplateFrom;
msgRecipient.Subject = EmailTemplate.TemplateSubject;
msgRecipient.EmailFormat = EmailEngine.EmailFormatEnum.Html;
msgRecipient.Recipients = Recipients;
CMS.EmailEngine.EmailSender.SendEmailWithTemplateText(SiteContext.CurrentSiteName, msgRecipient, EmailTemplate, mcr, true);
return true;
}
catch (Exception ex)
{
EventLogProvider.LogException(ex.Source, "sendEmail", ex);
}
return false;
}
Kentico 8.X/9
public static void SendEmail(string EmailTemplateCode, CMS.MacroEngine.MacroResolver mcr, string recipients)
{
CMS.EmailEngine.EmailMessage msg = new CMS.EmailEngine.EmailMessage();
CMS.EmailEngine.EmailTemplateInfo eti = CMS.EmailEngine.EmailTemplateProvider.GetEmailTemplate(EmailTemplateCode, CMS.SiteProvider.SiteContext.CurrentSiteID);
msg.EmailFormat = CMS.EmailEngine.EmailFormatEnum.Both;
msg.From = eti.TemplateFrom;
msg.Recipients = recipients;
msg.Subject = eti.TemplateSubject;
try
{
CMS.EmailEngine.EmailSender.SendEmailWithTemplateText(CMS.SiteProvider.SiteContext.CurrentSiteName, msg, eti, mcr, true);
}
catch (Exception ex)
{
CMS.EventLog.EventLogProvider.LogException(ex.Source, "SendEmail", ex);
}
}