Sending Emails with the Kentico API

By Dustin Christians on September 15, 2017

Sending Emails with the Kentico API
Have you ever needed to send a contact form submission automatically via email? Here’s how to create the email template and use it to send form fields. This method takes in any dynamic object and inserts its properties into the template. This way the method is reusable for any emails that need to be sent. 

The Method

I started with an email template. Here’s an example of an email template in Kentico:



I created an HTML email so I could embed inline styling if necessary. Notice that there are macro replacement fields in the email that look like this:
  { % FirstName % }
After a form is submitted the form object is passed into a method using the following logic:
            SendKenticoEmailTemplate( 
                "admin@bizstream.com",      // Email Recipient List
                "ContactUsFormSubmission",  // Email Template Code Name
                SiteContext.CurrentSiteID,  // Site ID
                new                         // The Dynamic Object
                {
                    FirstName = "Dustin",
                    LastName = "Christians",
                    Email = "myemail@bizstream.com",
                    Phone = "555-555-5555",
                    ReasonForContacting = "I'd like to learn more about Kentico.",
                    Message = "Hello. I'm leaving this message for you."
                });

I created an object on the fly so you could see the field names. However, any object will work as long as the object’s properties match the replacement macros in the email template. This is the method used to send the email: 
        /// <summary>
        /// Send an email using the Kentico email API
        /// </summary>
        /// <param name="emailRecipientList">A list of email addresses delimited by a semicolon</param>
        /// <param name="emailTemplateName">The email template code name</param>
        /// <param name="siteID">The Kentico Site ID that the email template belongs to</param>
        /// <param name="model">The model that contains the properties to be sent via macro replacements in the email template</param>
        /// <param name="emailFormat">HTML (default) or Text</param>
        public bool SendKenticoEmailTemplate( string emailRecipientList, string emailTemplateName, int siteID, dynamic model, EmailFormatEnum emailFormat = EmailFormatEnum.Html )
        {

            if (string.IsNullOrWhiteSpace( emailRecipientList ) || string.IsNullOrWhiteSpace( emailTemplateName ) )
            {
                return false;
            }

            var emailTemplate = CMS.EmailEngine.EmailTemplateProvider.GetEmailTemplate( emailTemplateName, siteID );
            var emailMacros = CMS.MacroEngine.MacroResolver.GetInstance( );
            var properties = model.GetType( ).GetProperties( );
            foreach ( var property in properties )
            {
                emailMacros.SetNamedSourceData( property.Name, property.GetValue( model, null ) );
            }
 
            var message = new CMS.EmailEngine.EmailMessage
            {
                EmailFormat = emailFormat,
                From = emailTemplate.TemplateFrom,
                Recipients = emailRecipientList,
                Subject = emailTemplate.TemplateSubject
            };
 
            try
            {
                CMS.EmailEngine.EmailSender.SendEmail( CMS.SiteProvider.SiteContext.CurrentSiteName, message, emailTemplateName, emailMacros, true );
            }
            catch( System.Exception exception )
            {
                CMS.EventLog.EventLogProvider.LogEvent( CMS.EventLog.EventType.ERROR,
                    "EmailService.SendKenticoEmailTemplate",
                    "SendEmailFailed",
                    $"{exception.Message}\n\nRecipient List: {emailRecipientList}\n\nEmail Template Codename: {emailTemplateName}" );

                return false;
            }

            return true;
        }

The Result

Testing the above method yielded the following result in the Kentico email queue:



I can now add the method call anywhere in a Kentico project, submit an object with fields that match the macros in the email template and send. Hopefully you will find this example useful on your next Kentico project!

Share This Post:

Twitter Pinterest Facebook Google+
Click here to read more Kentico posts
Start a Project with Us

About the author

Dustin has gone from satellite communications technician to computer engineer to web developer. He has always been excited about the prospects of technology; all that can be explored and discovered with it fascinates him. When Dustin is not developing software you can find him studying philosophy and preparing for another sailing or skiing adventure with his wife, Molly.

View other posts by Dustin

Subscribe to Email

Enter your email address to subscribe to the BizStream Newsletter and receive updates by email.