Microsoft & .NET.NETSending E-Mail with System.Web.Mail

Sending E-Mail with System.Web.Mail

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Welcome to the next installment of the .NET Nuts & Bolts column. In this column, we’ll explore sending e-mail from within applications. This will involve utilizing classes contained in the System.Web.Mail namespace.

Collaboration Data Objects

Collaboration Data Objects for Windows 2000 (CDOSYS) is a Microsoft messaging component that allows for standards-based e-mail messages to be constructed and sent. It is a replacement of the Collaboration Data Objects for NTS (CDONTS), which, as you can probably guess by the name, was for Windows NT. CDONTS is included with Windows 2000 for backwards compatibility, but Windows XP, Windows Server 2003, and beyond do not include or support the use of CDONTS. Thus, any applications that send messages using CDONTS must be migrated to use CDOSYS. It provides the same functionality and is just as easy to use.

In addition to serving as a replacement, CDOSYS introduces some new functionality that was not previously available in CDONTS. Some of the functionality includes:

  • Ability to post messages to newsgroups
  • Control of MIME body structure for messages
  • Reply and forward functionality
  • Transport event sink to allow responding to events

The System.Web.Mail namespace contains classes that interact with CDOSYS to construct and send the message(s).

Using IIS and SMTP Service

In order for CDOSYS to send e-mail or other messages from your application, you need to enlist the services of IIS with the SMTP Service installed. Both are available in Windows 2000/XP through the Control Panel -> Add/Remove Programs -> Add/Remove Windows Components option. The job of the STMP Service is to accept and deliver the messages, based on the configuration. The service can attempt to deliver the messages directly, or it can utilize a smart host to deliver the message instead. When a smart host is enlisted, all messages are forwarded to it for delivery. You need to have IIS and the SMTP service installed and configured.

The SMTP Service uses a directory structure to contain messages prior to delivery. The default directory is C:Inetpubmailroot. This folder contains a number of subdirectories such as Queue, Drop, and Badmail. If you are unable to configure your instance of the SMTP Service for delivery, you can find the message in a *.EML file in the C:InetpubmailrootQueue directory. This technique can be useful when creating messages offline.

Sending a Message

As previously mentioned, sending an e-mail is a relatively simple thing to do. The System.Web.Mail.MailMessage class represents the message to be sent. E-mail messages are constructed by using instances of this class. This class contains properties such as To, From, and Subject that allow you to control the message being sent. Attachments can be created through instances of the System.Web.Mail.MailAttachment and then added to the MailMessage through the Attachments collection of the MailMessage. The message is then delivered through the System.Web.Mail.SmtpMail class.

Sending a Message Sample Code

The following sample code contains a C#-based Windows Console application that shows how to send an e-mail message. By not specifying that the SmtpMail.SmtpServer property is not set, the localhost is used by default. You need to make sure to add a reference to the System.Web.dll because this is a console application and not an ASP.NET application.

using System;using System.Web.Mail;namespace CodeGuru.SendMail{  /// <summary>  /// Test console application to demonstrate sending e-mail.  /// </summary>  class TestMail  {    /// <summary>    /// The main entry point for the application.    /// </summary>    [STAThread]    static void Main(string[] args)    {      TestMail.Send("testuser@codeguru.com",                    "mstrawmyer@crowechizek.com",                    "Test Message Using CDOSYS",                    "Hello World!  This is a simple message sent                     using CDOSYS.");    }    /// <summary>    /// Send a message using the .NET wrapper for Collaborative Data    /// Objects (CDO).  This method should be used when sending to a    /// single recipient only; otherwise, the list of recipients    /// will be known.    /// </summary>    /// <param name="MessageFrom">Message originator</param>    /// <param name="MessageTo">Message receipent</param>    /// <param name="MessageSubject">Message subject</param>    /// <param name="MessageBody">Message body</param>    public static void Send(string MessageFrom,                            string MessageTo,                            string MessageSubject,                            string MessageBody)    {      MailMessage message = new MailMessage();      message.From        = MessageFrom;      message.To          = MessageTo;      message.Subject     = MessageSubject;      message.BodyFormat  = MailFormat.Text;      message.Body        = MessageBody;      try      {        System.Console.WriteLine("Sending outgoing message");        SmtpMail.Send(message);      }      catch( System.Web.HttpException exHttp )      {        System.Console.WriteLine("Exception occurred:" +                                 exHttp.Message);      }    }  }}

Sending a Message with an Attachment Sample Code

The following sample code contains a C#-based Windows Console application that shows how to send an e-mail message that includes an attachment. This is done by creating instances of the MessageAttachment class and then adding them to the message through the Attachments collection.

using System;using System.Web.Mail;namespace CodeGuru.SendMail{  /// <summary>  /// console application to demonstrate sending e-mail with an  /// attachment.  /// </summary>  class TestMail  {    /// <summary>    /// The main entry point for the application.    /// </summary>    [STAThread]    static void Main(string[] args)    {      TestMail.SendAttachment("testuser@codeguru.com",                              "mstrawmyer@crowechizek.com",                              "Test Message Using CDOSYS",                              "Hello World!  This is a simple                               message sent using CDOSYS.",                              "c:myattachment.txt");    }    /// <summary>    /// Send a message using the .NET wrapper for Collaborative Data    /// Objects (CDO).  This method should be used when sending to    /// a single recipient only; otherwise, the list of recipients    /// will be known.    /// </summary>    /// <param name="MessageFrom">Message originator</param>    /// <param name="MessageTo">Message receipent</param>    /// <param name="MessageSubject">Message subject</param>    /// <param name="MessageBody">Message body</param>    /// <param name="MessageAttachmentPath">Path to attachment    /// </param>    public static void SendAttachment(string MessageFrom,                                      string MessageTo,                                      string MessageSubject,                                      string MessageBody,                                      string MessageAttachmentPath)    {      // Create and setup the message      MailMessage message = new MailMessage();      message.From        = MessageFrom;      message.To          = MessageTo;      message.Subject     = MessageSubject;      message.BodyFormat  = MailFormat.Text;      message.Body        = MessageBody;      // Create and add the attachment      MailAttachment attachment = new          MailAttachment(MessageAttachmentPath);      message.Attachments.Add(attachment);      try      {        // Deliver the message        System.Console.WriteLine("Sending outgoing message");        SmtpMail.Send(message);      }      catch( System.Web.HttpException exHttp )      {        System.Console.WriteLine("Exception occurred:" +                                 exHttp.Message);      }    }  }}

Possible Enhancements

We have demonstrated how to send e-mail messages in a couple of ways. It is now up to you to think about ways in which you can utilize this functionality within your applications. Here are some ideas to consider on your own:

  • E-mail alerts—when a fatal or unrecoverable application error occurs, your application could e-mail information to a designated location so that it is immediately known.
  • Build a Web-based contact form—you can allow users to send customer feedback by filling out a Web form and then programmatically e-mailing it to the appropriate contact(s).
  • Subscription service—when sending mail by using CDOSYS for a subscription-type service, you may want to send multiple messages instead of a single message with all of the recipients. When a message has too many recipients, it can drastically slow processing as all of the recipients are processed. It is often better to break the list of recipients into multiple lists and send multiple messages.
  • Send messages using Bcc—when sending mail using by CDOSYS for a subscription-type service, you may want to address messages using the Bcc instead of To. This will keep the list of recipients unknown to all of those that receive it.
  • Send HTML-formatted mail—the message body format can be set to HTML. This will allow the body of the message to be sent in HTML format rather than plain text.

Future Columns

The next column has yet to be determined. If you have something in particular that you would like to see explained, please e-mail me at mstrawmyer@crowechizek.com.

About the Author

Mark Strawmyer, MCSD, MCSE, MCDBA is a Senior Architect of .NET applications for large and mid-size organizations. Mark is a technology leader with Crowe Chizek in Indianapolis, Indiana. He specializes in the architecture, design, and development of Microsoft-based solutions. You can reach Mark at mstrawmyer@crowechizek.com.

# # #

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories