Karl Gjertsen

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

Sending an email with Mail4Net

Mail4Net is a .NET library for creating, managing and sending emails.

Sending an email

Typically, you create a MailMessage class, populate it and then send it to a SMTP server, using Microsoft’s System.Net.Mail.SmtpClient class:

private void SendEmail()
{

  // Create mail message.
  var message = new System.Net.Mail.MailMessage();
  message.To.Add("someone@mydomain.com");
  message.From = new MailAddress("me@mydomain.com");
  message.Subject = "Hello World";
  message.Body = "Here is an email";

  // Send email.
  var client = new System.Net.Mail.SmtpClient();
  client.Send(message);

}

This code probably looks familiar to you, nothing out of the ordinary!

Mail4Net provides a direct replacement for the System.Net.Mail.SmtpClient class:

private void SendEmail_Clients()
{

  // Create mail message.
  var message = new System.Net.Mail.MailMessage();
  message.To.Add("someone@mydomain.com");
  message.From = new MailAddress("me@mydomain.com");
  message.Subject = "Hello World";
  message.Body = "Here is an email";

  // Send email - Microsoft.
  var client1 = new System.Net.Mail.SmtpClient();
  client1.Send(message);

  // Send email - Mail4Net.
  var client2 = new Mail4Net.Client.SmtpClient();
  client2.Send(message);

}

This shows you how easy it is to change from the System.Net.Mail namespace to the Mail4Net.Client namespace.

Mail4Net clients

The Mail4Net.Client namespace has a number of different clients. What happens to the MailMessage depends on which client you use:

Mail4Net.Client Action
SmtpClient() Sends the email to a SMTP server
EmlClient() Saves the email to a folder
SqlServerClient() Saves the email to a SQL Server database
FakeClient() Sends the email to the testing framework

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.

You can find out more at the Mail4Net website: www.mail4net.com.

%d bloggers like this: