Karl Gjertsen

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

Saving an email to SQL Server with Mail4Net

There are a number of reasons why you might want to save your email to a SQL Server database. Maybe you want to be able to resend the message if it doesn’t arrive. A common reason is to have the sending process performed by a dedicated service, such as MailSender, which will soon be available to download from the Mail4Net website.

Saving to SQL Server

To save an email to SQL Server, you first need to run the SQL scripts available to download from the Mail4Net website.

The SqlServerClient can be used to save an email to SQL Server:

private void SendEmail_SqlServer()
{
 
  // 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";
 
  // Save email.
  var fake = new Mail4Net.Client.SqlServerClient();
  fake.Send(message);
 
}

 

Setting the email id

The email is stored in SQL Server, with a randomly assigned Guid. You can add a header to your email, giving the value to be used. This can be used to retrieve specific emails:

// Set email id.
var id = Guid.NewGuid().ToString();
 
// Add id to header.
message.Headers.Add("X-Mail4Net-Id", id);

 

Setting the email sending options

You can also set options when you send the email. Currently this only allows you to set the sending priority of the email. A default value of 100 is used if this is not specified. To have emails pushed to the front of the sending queue, set a sending priority of lower than 100:

private void SendEmail_Sql_Priority()
    {
 
      // 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";
 
      // Set options.
      var options = new Mail4Net.Client.SendingOptions();
 
      // Set sending priority.
      options.SendingPriority = 1;
 
      // Send email.      
      var client = new Mail4Net.Client.SqlServerClient();
      client.Send(message, options);
 
    }

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

 

%d bloggers like this: