Karl Gjertsen

Architect, Developer, Speaker, Bad Golfer,
Raygun brand ambassador and creator of Infiniforms

Inversion of control in Mail4Net

Inversion of Control

All of the Mail4Net client classes implement a common interface, ISmtpClient. This allows you to use the inversion of control pattern with the Mail4Net clients.

To demonstrate using IoC with Mail4Net, I have created a sample class called MailCreator class, which has a SendEmail method that takes an email address and then sends an email to that address.

Here is the class:

public class MailCreator
{
 
  private readonly Mail4Net.Interface.ISmtpClient _client;
 
  public MailCreator(Mail4Net.Interface.ISmtpClient client)
  {
    _client = client;
  }
 
  public void SendEmail(string emailAddress)
  {
 
    // Create email.
    var message = new System.Net.Mail.MailMessage();
    message.To.Add(emailAddress);
    message.From = new MailAddress("sender@mydomain.com");
    message.Subject = "Hello";
    message.Body = "Here is an email from me.";
 
    // Send email here.
    _client.Send(message);
 
  }
 
}

To test this code works correctly, I add a test to my unit tests:

[TestMethod]
public void Mail_Creator_Populates_Email_Correctly()
{
 
  // Arrange.
  var client = new Mail4Net.Client.FakeClient();
  var creator = new MailCreator(client);
 
  // Act.
  creator.SendEmail("me@mydomain.com");
 
  // Assert.
  Assert.AreEqual(1, client.Messages.Count);
  Assert.AreEqual("me@mydomain.com", client.Messages[0].To);
  Assert.AreEqual("sender@mydomain.com", client.Messages[0].From);
  Assert.AreEqual("Hello", client.Messages[0].Subject);
  Assert.AreEqual("Here is an email from me.", client.Messages[0].Body);
 
}

To use this code in production code, I would substitute the FakeClient class with another client from the Mail4Net.Client namespace, using the appropriate client for my purpose.

To use this code in a production environment, you just replace the FakeClient with the client you want to use.

Send to an SMTP server:

public void SendEmailToSmtp()
{
 
  // Create classes.
  var client = new Mail4Net.Client.SmtpClient();
  var creator = new MailCreator(client);
 
  // Send an email.
  creator.SendEmail("me@mydomain.com");
  
}

Save to a SQL Server database:

public void SaveEmailToSql()
{
 
  // Create classes.
  var client = new Mail4Net.Client.SqlServerClient();
  var creator = new MailCreator(client);
 
  // Send an email.
  creator.SendEmail("me@mydomain.com");
  
}

You can find out more about Mail4Net at the Mail4Net website.

%d bloggers like this: