Kentico CMS 7.0 Developer's Guide

Custom E-mail provider

Custom E-mail provider

Previous topic Next topic Mail us feedback on this topic!  

Custom E-mail provider

Previous topic Next topic JavaScript is required for the print function Mail us feedback on this topic!  

Customizing the e-mail provider allows you to:

 

Execute custom actions when sending e-mails (for example logging the sent e‑mails for auditing purposes)

Use third‑party components for sending e‑mails

 

Once you create and register your custom e-mail provider, it is used to process all e-mails sent out by Kentico CMS and its modules.

 

Example

 

The following example demonstrates how to define a custom e‑mail provider. This sample provider supports all of the default e‑mail functionality, but additionally creates an entry in the Event log whenever the system sends an e‑mail.

 

Writing the custom e-mail provider

 

1. Open your web project in Visual Studio and create a new class in the App_Code folder (or Old_App_Code if the project is installed as a web application). For example, name the class CustomEmailProvider.cs.

 

2. Edit the class and add the following references:

 

[C#]

 

using System.ComponentModel;
using System.Net.Mail;
 
using CMS.EmailEngine;
using CMS.EventLog;
using CMS.SettingsProvider;

 

3. Modify the class's declaration to make it inherit from the CMS.EmailEngine.EmailProvider class:

 

[C#]

 

/// <summary>
/// Customized e-mail provider.
/// </summary>
public class CustomEmailProvider : EmailProvider
{
 
}

 

Custom e-mail providers must always inherit from the default EmailProvider class. This allows you to call the base methods before adding your own custom functionality.

 

4. Add the following method overrides into the class:

 

[C#]

 

/// <summary>
/// Customized e-mail provider.
/// </summary>
public class CustomEmailProvider : EmailProvider
{
  /// <summary>
  /// Synchronously sends an e-mail through the SMTP server.
  /// </summary>
  /// <param name="siteName">Site name</param>
  /// <param name="message">E-mail message</param>
  /// <param name="smtpServer">SMTP server</param>
  protected override void SendEmailInternal(string siteName, MailMessage message, SMTPServerInfo smtpServer)
   {
      base.SendEmailInternal(siteName, message, smtpServer);
 
      string detail = string.Format("E-mail from {0} was sent via {1} (synchronously)", message.From.Address, smtpServer.ServerName);
 
      EventLogProvider.LogInformation("CMSCustom", "EMAIL SENDOUT", detail);
   }
 
 
  /// <summary>
  /// Asynchronously sends an e-mail through the SMTP server.
  /// </summary>
  /// <param name="siteName">Site name</param>
  /// <param name="message">E-mail message</param>
  /// <param name="smtpServer">SMTP server</param>
  /// <param name="emailToken">E-mail token that represents the message being sent</param>
  protected override void SendEmailAsyncInternal(string siteName, MailMessage message, SMTPServerInfo smtpServer, EmailToken emailToken)
   {
      base.SendEmailAsyncInternal(siteName, message, smtpServer, emailToken);
 
      string detail = string.Format("E-mail from {0} was dispatched via {1} (asynchronously)", message.From.Address, smtpServer.ServerName);
 
      EventLogProvider.LogInformation("CMSCustom", "EMAIL SENDOUT", detail);
   }
 
 
  /// <summary>
  /// Raises the SendCompleted event after the send is completed.
  /// </summary>
  /// <param name="e">Provides data for the async SendCompleted event</param>
  protected override void OnSendCompleted(AsyncCompletedEventArgs e)
   {
      base.OnSendCompleted(e);
 
      string detail = "Received callback from asynchronous dispatch";
 
      EventLogProvider.LogInformation("CMSCustom", "SEND COMPLETE", detail);
   }
}

 

The provider uses these methods to send out e‑mails. Each method calls the base from the parent provider class and then logs an information event into the system's event log. You can use the same approach to add any type of custom functionality.

 

Registering the provider class (via the web.config)

 

This example uses the web.config approach for registering the custom e-mail provider:

 

1. Open your application's web.config file and add the following section into the configSections element (if it is not already present):

 

<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
 <configSections>

 
 ...
 

<!-- Extensibility BEGIN -->
 <section name="cms.extensibility" type="CMS.SettingsProvider.CMSExtensibilitySection" />
<!-- Extensibility END -->

 
 </configSections>
...

 

This defines the cms.extensibility web.config section where you can register custom providers, helpers and managers.

 

2. Create the actual cms.extensibility section directly under the root level of the web.config and add the e‑mail provider:

 

...

 

<!-- Extensibility BEGIN -->
<cms.extensibility>
 <providers>
   <add name="EmailProvider" assembly="App_Code" type="EmailProviderWithEventLog" />
 </providers>
</cms.extensibility>
<!-- Extensibility END -->

 

...

</configuration>

 

Because the custom provider is defined in App_Code, you also need to ensure that the system can load the class.

 

3. Extend the CMSModuleLoader partial class. You can either create a new class file for this purpose or add the partial class declaration directly into the file containing your custom provider (CustomEmailProvider.cs in this case).

 

[C#]

 

public partial class CMSModuleLoader
{
}

 

4. Create a new attribute class inside the CMSModuleLoader that inherits from CMSLoaderAttribute. Add the attribute to the CMSModuleLoader partial class:

 
[C#]

 

using CMS.SettingsProvider;
 
[ClassLoader]
public partial class CMSModuleLoader
{
  /// <summary>
  /// Attribute class that ensures the loading of custom classes.
  /// </summary>
  private class ClassLoader : CMSLoaderAttribute
   {
   }
}

 

5. Add the following code into the attribute class:

 

[C#]

 

/// <summary>
/// Called automatically when the application starts.
/// </summary>
public override void Init()
{
  // Assigns a handler for the OnGetCustomClass event  
  ClassHelper.OnGetCustomClass += GetCustomClassEventHandler;
}
 
/// <summary>
/// Gets the custom class object based on the specified class name.
/// </summary>
private static void GetCustomClassEventHandler(object sender, ClassEventArgs e)
{
  if (e.Object == null)
   {
      // Checks the name of the requested class
      switch (e.ClassName)
       {
          // Gets an instance of the 'CustomEmailProvider' class
          case "EmailProviderWithEventLog":
               e.Object = new CustomEmailProvider();
              break;
       }
   }
}

 

Note: The string used to identify the custom e-mail provider class must match the value of the type attribute set for the corresponding add element in the web.config extensibility section (EmailProviderWithEventLog in this example).

 

Result

 

The system now uses the custom e-mail provider (defined in the CustomEmailProvider class) when sending e-mails.

 

To try out the functionality:

 

1. Send some e‑mails using Kentico CMS.

oFor example, you can use the Site Manager -> Administration -> System -> E-mail interface to send a test e-mail (synchronously).

 

2. Check the log in Site Manager -> Administration -> Event log.

 

devguide_clip1495

 

Every successfully sent e-mail should have its own entry identified by the CMSCustom Source value (two entries for e-mails sent asynchronously).