标签 smtp 下的文章

Original Post: http://dotnetslackers.com/articles/aspnet/Sending-email-from-ASP-NET-MVC-through-MVC-and-MSMQ-Part2.aspx

By: Andrew Siemer

In this article you will learn how to send emails using ASP.NET MVC and MSMQ.

Contents

  1. Introduction
  2. Setting up a private queue
    1. MSMQ in Windows 7
    2. MSMQ in Windows 2008
  3. Creating an MSMQ Service
  4. Update your web application to use MSMQ instead of SMTP
  5. Draining the queue
    1. A quick refactor of the queue guard code
  6. Sending the emails
    1. Relocating the SerializeMessage method
  7. Creating an installable Windows Service to drain the queue
    1. A quick refactor of our console applciation
  8. Finishing up the Windows Service
    1. Adding a Timer
    2. Making the service installable
  9. Installing your website email queue processing service
  10. Summary

Sending email from ASP.NET MVC through MVC and MSMQ Part Series

Introduction

In the previous article we discussed some of the downfalls of sending email directly from a web page and worker process that served that request. The biggest issue that we discussed was the fact that the user that initiated an email to be sent would be stuck waiting for the code to connect to the mail server and deliver the message. But we also discussed that for important emails we would also need a logging component to keep track of all the customer communications that we send. We then built out an example ASP.NET MVC application that sends email in a direct from the page fashion. We also built out a logging component so that all the messages that we intended to send would be serialized and stored in a logging database using LINQ to SQL.

In this article we will now refactor the previously created code base (make sure you grab a copy of the first articles application if you want to work along with this article) to take advantage of MSMQ. We will modify our EmailService so that rather than speaking directly with System.Net.Mail and SMTP we will instead utilize System.Messaging and MSMQ. Once our web application is converted to send its email communications to MSMQ we will then need to create a queue processing application. We will start by creating this in the form of a console application that clears the queue and sends email via our existing EmailService. Once the console application is working we will convert it into a more reliable Windows Service.

Setting up a private queue

To get started we will first create a new queue. There are many options when creating a queue. Take a look at "Reliable Messaging with MSMQ and .NET" for a good in depth discussion of MSMQ concepts. We are going to create a simple non-transactional private queue for this example. You need to first make sure that you have MSMQ installed on your machine.

I will quickly describe how to install MSMQ in Windows 7 and Windows 2008. You can use MSMQ on any of today's current versions of Windows (just google for some MSMQ installation help if you don't know what to do).

MSMQ in Windows 7

Go to Control Panel\Programs and select "Turn Windows features on or off". In the Windows Features window that pops up, scroll down to Microsoft Message Queue (MSMQ) Server and select that box. Just leave the default selection as that will get us through this demonstration. Then click OK.

Then navigate to the Computer Management console. You should be able to expand Services and Applications and see a Message Queuing entry. Expand that entry and right click on Private Queues. Select new private queue. In the New Private Queue window that opens enter WebsiteEmails. This will make the path to your private queue "{ComputerName}\private$\WebsiteEmails".

MSMQ in Windows 2008

In the Server Manager window, navigate to the Features node. Then click on Add Features. In the Add Features Wizard scroll down to Message Queuing. Then click through the wizard buttons to complete the installation.

Back in the Features node of Server Manger you should now have a Message Queue node. Inside of there you will see a Private Queues node. Right click on Private Queues and select new private queue. Give your queue the same name as above WebsiteEmails. This will make the path to your private queue "{ComputerName}\private$\WebsiteEmails".

Creating an MSMQ Service

Now that we have a queue to dump our EmailMessages into, let's write some code that will allow us to do just that. Start by creating a QueueService class in your Services folder. Then we will create a method named QueueMessage that will take in an EmailMessage object.

Listing 1: QueueService.cs

public class QueueService { public void QueueMessage(EmailMessage message) { } }

Now let's add a reference to System.Messaging to our BusinessLayer project. Then we will add the code that we need to connect to our private queue and insert a new message.

Listing 2: QueueService.cs

public class QueueService { public void QueueMessage(EmailMessage message) { Message msg = new Message(); msg.Body = message; msg.Recoverable = true; msg.Formatter = new BinaryMessageFormatter(); string queuePath = @".\private$\WebsiteEmails"; MessageQueue msgQ; //if this queue doesn't exist we will create it if(!MessageQueue.Exists(queuePath)) MessageQueue.Create(queuePath); msgQ = new MessageQueue(queuePath); msgQ.Formatter = new BinaryMessageFormatter(); msgQ.Send(msg); } }

Update your web application to use MSMQ instead of SMTP

All that we need to do to get our web site to use MSMQ instead of SMTP is to comment out (or delete) the call to our EmailService and replace it with a call to our QueueService.

Listing 3: HomeController.cs

[HttpPost] public ActionResult Index(string id) { EmailMessage em = new EmailMessage(); em.Subject = "test message"; em.Message = "howdy from asp.net mvc"; em.From = "[email protected]"; em.To = "[email protected]"; //new EmailService().SendMessage(em, // "{email address}", // "{password}", // "smtp.gmail.com", // 587, // true, // new LoggingRepository()); new QueueService().QueueMessage(em); return View(); }

You should now be able to build and run your application. Clicking the Send Email button should now store messages in your new private queue. More importantly, the time it takes from when you click the button until the page returns should be considerably faster!

After clicking the button a few times you should be able to open up your MSMQ management window and see some messages in the queue.

Also, if you double click one of those messages to open it up, you should be able to see all sorts of data about the message. And you can see the original email that was sent!
Draining the queue

Now that we have our web site converted to send emails to a queue, we need to create an application that can read from the queue, deserialize our messages, and send out the emails as intended. We will start building this application as a console app. Once that is working as expected we can convert it to a Windows Service.

Add a new Console Application to your solution named WebsiteEmailProcessor. Then add two references to that project. The first reference is to the BusinessLayer project. The second reference is to the System.Messaging namespace.

Next we need to add a way for our application to read from the queue. This process is fairly straightforward. We will need the Main method in our console application to get us started. But we are also going to need an event handler to keep processing messages as they come into the queue.

Listing 4: Program.cs

class Program { private static MessageQueue msgQ = null; private static object lockObject = new object(); static void Main(string[] args) { string queuePath = @".\private$\WebsiteEmails"; msgQ = new MessageQueue(queuePath); msgQ.Formatter = new BinaryMessageFormatter(); msgQ.MessageReadPropertyFilter.SetAll(); msgQ.ReceiveCompleted += new ReceiveCompletedEventHandler(msgQ_ReceiveCompleted); msgQ.BeginReceive(); while (Console.ReadKey().Key != ConsoleKey.Q) { // Press q to exit. } } static void msgQ_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e) { lock (lockObject) { // The message is plain text. EmailMessage msg = (EmailMessage)e.Message.Body; Console.WriteLine("Message received: " + msg.Message); } // Listen for the next message. msgQ.BeginReceive(); } }

With what we have so far you can now run both the web application and the console application. When you click the Send Email button on the web application you should see a message go through your queue and through the processor. Give it a try!

A quick refactor of the queue guard code

You may have noticed that our console application is currently making an assumption that a queue exists. This is lazy! Let's refactor some code in our QueueService to check that the queue exists and make the queue in the case that it doesn't.

Listing 5: QueueService.cs

public static void InsureQueueExists(string queuePath) { //if this queue doesn't exist we will create it if (!MessageQueue.Exists(queuePath)) MessageQueue.Create(queuePath); }

And then we can replace this check in our QueueService.QueueMessage method.

Listing 6: QueueService.cs

MessageQueue msgQ; InsureQueueExists(queuePath); msgQ = new MessageQueue(queuePath);

Now we are ready to update our console app so that it makes this check as well.

Listing 7: Program.cs

class Program { private static MessageQueue msgQ = null; private static object lockObject = new object(); static void Main(string[] args) { string queuePath = @".\private$\WebsiteEmails"; QueueService.InsureQueueExists(queuePath); msgQ = new MessageQueue(queuePath); } }

Sending the emails

Now that the core guts of this thing are working we can now integrate our EmailService back into the picture. We will add this to our msgQ_RecieveCompleted event handler.

Listing 8: Program.cs

static void msgQ_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e) { lock (lockObject) { // The message is plain text. EmailMessage msg = (EmailMessage)e.Message.Body; new EmailService().SendMessage(msg, "{username}", "{password}", "{host}", 587, true, new LoggingRepository()); Console.WriteLine("Message received: " + msg.Message); } // Listen for the next message. msgQ.BeginReceive(); }

Now when we run the web application and the console application we can click the SendEmail button, see the messages get queued up in the MSMQ manager, see the console application process the queue, see in the database that our log is being added too, and see in our email client that the emails are getting sent too!
Relocating the SerializeMessage method

This looks pretty good so far. But it no longer makes sense to keep our SerializeMessage method in the EmailService. Let's move it to its own class now and then we can come back to update the QueueService. We need to create a new Serializer class. Then if you are using ReShaper you can simply put your mouse over the SerializeMessage method name and press [ctrl][shift][r] to refactor the method. Then you can choose Move to another Type from the list that pops up. If you don't have ReShaper then you can copy/paste! Don't forget to update your EmailService to use the relocated Serializer.SerializeMessage method (ReSharper does this for you!).

Listing 9: Serializer.cs

namespace AndrewSiemer.BusinessLayer.Services { public class Serializer { public static string SerializeMessage(EmailMessage message) { StringWriter outStream = new StringWriter(); XmlSerializer s = new XmlSerializer(typeof(EmailMessage)); s.Serialize(outStream, message); return outStream.ToString(); } } }

Creating an installable Windows Service to drain the queue

To complete our distributed application we need to take the console application and beef it up a bit. While we could technically leave our queue processor in the console application and just leave the console application running all day, this is not a very "enterprise" way of doing things! For that reason we will create one last project. This time we will create a Windows Service project that can be installed on a server and left to run forever after.

Let's start by adding a new Windows Service project called WebsiteEmailService to our solution. Then set the ServiceName (in the properties window) to something you will recognize in your Services MMC. I am calling my service WebsiteEmailQueueProcessor.
A quick refactor of our console applciation

Then we need to do a quick refactor of our console application. We need to pull the code that we wrote there up into our BusinessLayer project. We will do this by adding a QueueProcessor class to our Services folder. Inside that class we will add all the code from our Project.cs file so that it can be referenced by both the console application and the service.

Listing 10: QueueProcessor.cs

using System; using System.Collections.Generic; using System.Linq; using System.Messaging; using System.Text; using AndrewSiemer.BusinessLayer.DataAccess; using AndrewSiemer.BusinessLayer.Domain; namespace AndrewSiemer.BusinessLayer.Services { public class QueueProcessor { private static MessageQueue msgQ = null; private static object lockObject = new object(); public static void StartProcessing() { string queuePath = @".\private$\WebsiteEmails"; QueueService.InsureQueueExists(queuePath); msgQ = new MessageQueue(queuePath); msgQ.Formatter = new BinaryMessageFormatter(); msgQ.MessageReadPropertyFilter.SetAll(); msgQ.ReceiveCompleted += new ReceiveCompletedEventHandler(msgQ_ReceiveCompleted); msgQ.BeginReceive(); while (Console.ReadKey().Key != ConsoleKey.Q) { // Press q to exit. Thread.Sleep(0); } } static void msgQ_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e) { lock (lockObject) { // The message is plain text. EmailMessage msg = (EmailMessage)e.Message.Body; new EmailService().SendMessage(msg, "{username}", "{password}", "{host}", 587, true, new LoggingRepository()); Console.WriteLine("Message received: " + msg.Message); } // Listen for the next message. msgQ.BeginReceive(); } public static void StopProcessing() { msgQ.Close(); } } }

From there we can update our Program class in the console application to use this code which will make it much smaller and easier to read!

Listing 11: Program.cs

class Program { static void Main(string[] args) { QueueProcessor.StartProcessing(); } }

We also need to move the while loop out of the QueueProcessor as that implementation will only work when ran from the Console Application. It will give us errors if ran from the Windows Service. For that reason we will relocate that looping logic to our console app like this.

Listing 12: Program.cs

class Program { static void Main(string[] args) { QueueProcessor.StartProcessing(); while (Console.ReadKey().Key != ConsoleKey.Q) { // Press q to exit. Thread.Sleep(0); } } }

Finishing up the Windows Service

Now that our code is accessible for both the Windows Service and the Console Application we can complete the service. In the design surface for your service click the "click here to switch to code view" link.

Adding a Timer

One of the first things that we need to do when building up our service is to add a Timer to keep track of how often our service does its job. Every time the Timer's interval completes it will fire an event that we will capture to perform our queue processing. To do this we first need to declare a private Timer instance.

Listing 13: Service1.cs

public partial class WebsiteEmailQueueProcessor : ServiceBase { Timer timer = new Timer(); }

Then we need to initialize our timer in the OnStart method.

Listing 14: Service1.cs

protected override void OnStart(string[] args) { timer.Interval = 1000; timer.Elapsed += new ElapsedEventHandler(timer_Elapsed); timer.AutoReset = true; timer.Enabled = true; timer.Start(); }

Next, we need to create our even handler which will actually kick off the processor.

Listing 15: Service1.cs

void timer_Elapsed(object sender, ElapsedEventArgs e) { QueueProcessor.StartProcessing(); }

Lastly, we need to add some code to the OnStop method of our service that will stop the timer and free the resources in our QueueProcessor.

Listing 16: Service1.cs

protected override void OnStop() { QueueProcessor.StopProcessing(); timer.AutoReset = false; timer.Enabled = false; }

Logging makes building a service much easier!

I didn't want to bog down our code examples with logging code. But in the code download for this article you will find that I have added some error handling and logging code. This will allow you to look into what is going on with the service when you attempt to install it, run it, etc. which will ultimately help you track down problems in your service. My logging implementation just appends text to a text file in the root of your C drive. You may want to update this to run from somewhere else!

Making the service installable

Now that we have everything ready for testing we have a few more steps to perform to get our service installed and running. To make an installer for our service you need to go the design surface of your service. Then right click in the grey area and select add installer. This will add two components to your design surface, a service process installer, and a service installer. You might want to rename these to something more descriptive to your project. I prefixed both of them with WebsiteEmailQueueProcessor.

In the service installer you will want to give your service a description and name that means something to you when looking at the service in the Services MMC. I named my service "Website Email Queue Processor" and gave it a description of "Website email queue processing service".

Then in the process installer you will want to change the Account that your service will run under by default to "LocalSystem". This should give your service enough rights to run after the basic install process (described shortly).

The last and most important step of all this is to navigate to the properties window for your windows service project. In the application tab make sure that you set the Startup Object to the Program class in your service project.

Now you can build the entire solution (cross your fingers). Once everything builds ok we can get this puppy installed and running.

Installing your website email queue processing service

To get your service installed you need to open the Visual Studio command prompt in administrator mode. Then navigate to the directory that contains your service executable. This is most likely in the bin/debug folder of your service project. Then you can run installutil and the executable name to install your service.

Run these commands in the Visual Studio command prompt.

Listing 17: Visual Studio Command Prompt in Administrator Mode

cd /d {drive letter where your code is}: cd "{full path to project}\bin\debug\" installutil {name of executable}.exe Microsoft (R) .NET Framework Installation utility Version 4.0.30319.1 Copyright (c) Microsoft Corporation. All rights reserved. Running a transacted installation. ......... The Commit phase completed successfully. The transacted install has completed.

If you want to remove a service, you can type following command in the Visual Studio command prompt:

installutil /u {name of executable}.exe

If you find that you are having issues getting your service installed, you can always check the folder that contains your executable. After running the installutil you will have a couple of log files that will give you the details of your installation. Check there for more clues and google for the answer!

With any luck everything should be installed and at this point. You will then need to go to the Services MMC and start your service. You should now be able to run your web application and click the magical Send Email button. And after a few seconds that email should arrive in your inbox!

Summary

In our previous article we discussed why sending email directly from a website upon a user's request might be a bad idea. We then discussed some of the options for getting around these various forms of evil. We then created a demo application that sent email directly from the website. In this article we refactored our initial code base so that it would use a distributed method of sending email using an MSMQ private queue and a Windows Service to drain that queue and do the heavy lifting of sending email.

Original Post: http://dotnetslackers.com/articles/aspnet/Sending-email-from-ASP-NET-MVC-through-MVC-and-MSMQ-Part1.aspx

Published: 22 Mar 2010
By: Andrew Siemer

In this article you will learn how to send emails using ASP.NET MVC and MSMQ.

Contents

  1. Introduction
  2. An example of sending mail directly to SMTP
    1. Creating the ASP.NET MVC web application
    2. Creating the email logging database
    3. Creating a quick business layer
    4. Adding LINQ to SQL support for data access
    5. Creating an email wrapper
    6. Logging to the database
    7. Hooking up our web page
    8. Ready to send an email?
  3. Summary

Sending email from ASP.NET MVC through MVC and MSMQ Part Series

Introduction

I have worked in a lot of different web environments ranging from high traffic social networking sites to high transaction ecommerce sites. One thing every site has in common regardless of the industry that it serves is that at some point in time it will need to send an email communication to someone. In the case of a community site you might send an email to a user when they comment on a friend's profile. For ecommerce sites you might send a confirmation email when someone purchases a product from your site.

Regardless of the reason that the email is being sent, sending it directly from your web sites worker process is generally a bad idea. Connecting to an SMTP server, especially one on a separate server, can be a long blocking process. Adding insult to injury, the poor guy that performed the initial button click of some kind is now stuck waiting for the next web page to return. And if you work in an environment that needs to log every communication with its customers (a common requirements these days), the customer may have to endure the wait for the sending of the email as well as a dip to an email logging database. Luckily for your customer there is a better method!

In this article we will take a look at all the normal steps required to send an email directly from an ASP.NET MVC web page. We will also discuss how to log all of our communications by serializing our email communications to a logging database with LINQ to SQL. Once we complete this article we will have a working codebase that we can then refactor to send email in a more efficient and disconnected manner through MSMQ.
An example of sending mail directly to SMTP

In the majority of consulting gigs I have been a part of I almost always come across a web page that connects directly to an SMTP server. It creates an instance of MailMessage, populates various properties of that message, spins up an instance of SmtpClient, and attempts to send the message. If the message was sent successfully then we can log it to a database. If the message doesn't send then we can log the failed attempt too.
Creating the ASP.NET MVC web application

Let's create a quick web application

that works in this fashion. To start we will create an ASP.NET MVC 2 application (in Visual Studio 2010). I am going to place mine in a source folder and call the application "Web Application" (clever eh?).

Creating the email logging database

Then we need to create the database for the logging side of our application. Right click on the App_Data folder in your MVC application and choose to add a new item. Then select a SQL Server Database (you need SQL Express installed for this to work). Name the database EmailLogging.mdf and click Add. The new database should then show up in the App_Data folder as well as under your Data Connections section of the Server Explorer.

Expand the database in the Data Connections window. Right click on the Tables folder and select add new table. Add a column named EmailLogID with an int data type and don't allow nulls. Then mark that column as a primary key (click the key above). Then scroll down in the Column Properties and set the (Is Identity) filed under the Identity Specification to Yes.

Then add a SentSuccessfully field with a data type of bit and don't allow nulls.

Next we will add a SentDate field with a data type
of date (about time we got this data type!).

And lastly we will add a Message field with a data type of varchar(500).

Now you can save your table. Name the table EmailLogs in the window that pops up.

Creating a quick business layer

Now we can add a new class library to manage our data access and business logic. Do this by right clicking on your solution and selecting to add a new project. Choose to add a new Class Library project. Name this project BusinessLayer. Then add a reference from your WebApplication project to your BusinessLayer project. This can be done by right clicking on the WebApplication project and selecting add reference. In the project tab, select the BusinessLayer project.

Adding LINQ to SQL support for data access

The quickest way to achieve data access these days is through the uses of LINQ to SQL! Add a folder to the BusinessLayer project called Domain. Then right click on that folder and choose to add a new item. Then add a LINQ to SQL Classes item and call it Logging.dbml.

NOTE

The name you choose here will be used to generate a {nameYouPick}DataContext class. If you choose AndrewsEmailLoggingContext.dbml you will end up with an AndrewsEmailLoggingContextDataContext class that you have to do all your data access through. Buyer beware!

Now you can drag the EmailLogs table we create out of the Data Connections->EmailLogging.mdf->Tables section of the Server Explorer on to the design surface of your Logging.dbml. This will generate an EmailLogging class for you. Now save your Logging.dbml file. Then build your project so that your LoggingDataContext will be created for you as we will need it in upcoming steps.

Why did you put the LINQ to SQL classes in the Domain folder?

Good question. The LINQ to SQL classes item sort of leaks it's concerns throughout your application so you have to know how to pick the lesser of two evils when deciding where to put this thing. LINQ to SQL performs (at least) two functions for you. 1) It creates the classes that represent your database objects. 2) It provides you with the tools you need to query the database with.

What this means to you from a code organization perspective is that you either have Domain objects that live in a DataAccess folder (ugly) or code that you never directly reference in your application that lives in your Domain folder. What I mean to say is that you will use a Repository class that you create and that Repository class will have a reference to Domain.LoggingDataContext. Equally ugly but you only have to touch it when building the repositories.

If this discussion is boring you then it doesn't apply to you. If this discussion has you thinking then you should probably use the Entity Framework or NHibernate! :P

Creating an email wrapper

Next we need to create a quick wrapper class that will handle sending email for us. We will do this by creating a new folder in our BusinessLayer project called Services. Inside that we can create an EmailService class. We will use this class as the entry point into sending our email directly through SMTP. Make this class public and add a method called SendMessage.

Listing 1: EmailService.cs

public void SendMessage(EmailMessage message, string username, string password, string host, int port) { }

Use ReShaper to save you some time!

If you are a big ReSharper fan you might just implement the usage of the EmailMessage directly in the SendMessage method and then use ReSharper to create the EmailMessage class for you (must faster).

Now go to the Domain folder and create a new class called EmailMessage.
Listing 2: EmailMessage.cs

namespace AndrewSiemer.BusinessLayer.Domain { public class EmailMessage { public string To { get; set; } public string From { get; set; } public string Subject { get; set; } public string Message { get; set; } } }

Back in your EmailService we can now map our EmailMessage properties into the constructor of a MailMessage instance.

Listing 3: EmailService.cs

MailMessage mm = new MailMessage(message.From, message.To, message.Subject, message.Message);

After that we can create an instance of NetworkCredential with the passed in username and password. And then we can create an instance of SmtpClient with the host and port. And then we can bring those two together by passing in the credentials to the SmtpClient.

Listing 4: EmailService.cs

public void SendMessage(EmailMessage message, string username, string password, string host, int port, bool enableSsl) { MailMessage mm = new MailMessage(message.From, message.To, message.Subject, message.Message); NetworkCredential credentials = new NetworkCredential(username, password); SmtpClient sc = new SmtpClient(host, port); sc.EnableSsl = enableSsl; sc.Credentials = credentials; }

Once this is completed we are ready to try to send our message with a call to SmtpClient.Send().

Listing 5: EmailService.cs

try { sc.Send(mm); //add to logging db } catch (Exception) { //add to logging db throw; } SmtpClient.SendAsync()

If you really just want to send email from your page "because that is how you have always done it" you should at least upgrade to .NET 4 and use the SendAssync method (http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.aspx)

Now we can create one last method to serialize a mail message for us which we can then pass into our logging database.
Listing 6: EmailService.cs

public static string SerializeMessage(EmailMessage message) { string result = ""; StreamWriter tw = new StreamWriter(result); XmlSerializer x = new XmlSerializer(message.GetType()); x.Serialize(tw, message); return tw.ToString(); }

And now we can serialize our mail message to be logged by adding this line to our SendMessage method.

Listing 7: EmailService.cs

public void SendMessage(EmailMessage message, string username, string password, string host, int port) { string serializedMessage = SerializeMessage(message); MailMessage mm = new MailMessage(message.From, message.To, message.Subject, message.Message); }

Logging to the database

Now we are ready to build up a repository for our logging purposes. Add a new folder to the business layer called DataAccess. Then add a class called LoggingRepository. Then add a method called LogMessage. In this method we will connect to our database and insert our serialized message.

Listing 8: LoggingRepository.cs

public class LoggingRepository { public void LogMessage(string message, bool sentSuccessfully) { string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename={pathToDatabase}\EmailLogging.mdf;Integrated Security=True;User Instance=True"; using(LoggingDataContext dc = new LoggingDataContext(connectionString)) { EmailLog el = new EmailLog(); el.Message = message; el.SentDate = DateTime.Now; el.SentSuccessfully = sentSuccessfully; dc.EmailLogs.InsertOnSubmit(el); dc.SubmitChanges(); } } }

Now we can return to the EmailSerivce and wire up our LoggingRepository. Start by adding another parameter to our SendMessage method that takes in an instance of our new LoggingRepository. Then replace the "//add to logging db" comments with a call to the LoggingRepository.LogMessage method.

Listing 9: EmailService.cs

try { sc.Send(mm); repository.LogMessage(serializedMessage, true); } catch (Exception) { repository.LogMessage(serializedMessage, false); throw; }

Hooking up our web page

Now we can return to our web application. Open the Views/Home folder and then open the Index.aspx view page. We are going to add a form with a button that will allow us to catch a post to an action that will attempt to send an email for us.

Listing 10: Index.aspx

<% Html.BeginForm("Index", "Home"); %> <% Html.EndForm(); %>

With this in place we can then navigate to our HomeController. In the HomeController we need to add a new action to catch the form submission from the Index view. Make sure that you specify the HttpPost attribute! Without it our form post won't find this new action.

Listing 11: HomeController.cs

[HttpPost] public ActionResult Index(string id) { return View(); }

Once we have our new action in place we can then wire up our email sending code! We need to create a new instance of a MailMessage. Then we need to populate the various properties of our MailMessage. From there we can create an instance of EmailService and pass in all the various properties that your SMTP server requires.

Listing 12: HomeController.cs

[HttpPost] public ActionResult Index(string id) { EmailMessage em = new EmailMessage(); em.Subject = "test message"; em.Message = "howdy from asp.net mvc"; em.From = "[email protected]"; em.To = "[email protected]"; new EmailService().SendMessage(em, "{email account}", "{password}", "{smtp server address}", {smtp port}, {ssl or not}, new LoggingRepository()); return View(); }

Ready to send an email?

With all of these steps completed you should now be able to hit F5 and run your web application. When it pops open you will have a "SendEmail" button on your form just begging to be clicked. When you click it an email should be sent (or not depending on lots of things). And regardless of the status of your email being sent you should get a serialized EmailMessage logged into your database. If the email was sent you will probably notice that it took at least several seconds to perform its operation. If your email server was not available then you would have noticed that the server took around a minute (give or take) to tell you that it wasn't available for sending messages. Add to that the latency of logging the message into the database and you have a slow process no matter how successful it was!

Listing 13: Serialized EmailMessage from the EmailLogs table

[email protected] [email protected] test message howdy from asp.net mvc

Summary

In this article we discussed some of the issues with sending email directly out of a page in your web application. We then jumped into creating an example ASP.NET MVC application that would send email in this manner. Our example also serialized all of our communications and logged them into a logging database using LINQ to SQL.

In the next article we will take a look at the steps required to move away from this thread blocking way of sending email. We will then implement a disconnected method of sending email communications using MSMQ.