SMTP in .NET 2.0

New Features and Functionality

Josef Finsel

October 30, 2009

9 Min Read
ITPro Today logo

asp:Feature

LANGUAGES: VB.NET

ASP.NETVERSIONS: 2.0

 

SMTP in .NET 2.0

New Features and Functionality

 

By Josef Finsel

 

The next version of Visual Studio has some interestingchanges in how and what you can do in sending e-mail. (Note: This column waswritten using the November Technology Preview of VS2005 and some things may notbe available until Beta 2.)

What Is SMTP?

SMTP stands for Simple Mail Transport Protocol and is the Internetprotocol used to deliver e-mail. Without going into all the technical details,the SMTP server sits and monitors a specific TCP/IP port, much like the HTTPserver does. And it responds to those requests. These requests could be from ane-mail client, such as the one that we are going to build, or they could comefrom other SMTP servers that are delivering mail.

 

The first difference between .NET 2.0 and earlier versionsis the introduction of the System.Net.Mailspace namespace, but this is not asimple move of methods and properties from one namespace to another. Rather, itis a rebuilding of how SMTP is implemented. One good example of this isdemonstrated by looking at an e-mail address. In its simplest form an e-mailaddress is:

 

[email protected]

 

But there is more to it than that, isn t there. After all,most e-mail shows a real name, not an e-mail address. But what s the correctformat? Is it:

 

Josef Finsel

 

or

 

Josef Finsel

 

Neither. It s simply:

 

[email protected]

 

The name is applied to the e-mail address within the textof the raw e-mail. Fortunately, this no longer matters because there is now aMailAddress object that takes care of that. The table in Figure 1 shows a listof all the classes in the System.Net.Mail namespace.

 

Class

Description

AttachmentBase

The base class used for the AlternateView, Attachment, and LinkedResource classes.

AlternateView

Used to provide a different format of the e-mail. If you send the e-mail as HTML, you can include a plain-text version using the AlternateView.

Attachment

A class for adding attachments to the e-mail.

LinkedResource

Used to embed external resources such as an image in an e-mail.

MailAddress

Used to define mail addresses and display names.

MailMessage

Used to create the actual e-mail.

SMTP

Several classes that enable great control over interacting with an SMTP server.

Figure 1: Classesin System.Net.Mail.

 

Creating an E-mail

For this example we are going to build a simple Web pagethat will allow the user to enter their name and e-mail address, select asubject from a dropdown list, then enter the body of the message to send; thisrepresents a typical customer service-type Email Us page. The page will thencreate a formatted e-mail to send to customer service and a copy to the user.

 

At first glance, the code in ListingOne may seem like a more complicated way to create and send e-mails than itused to be, but it offers more control. We ll begin by creating threeMailAddress objects, one each for the from address, the to address, and the CCto send a copy to the person sending the e-mail. This is as simple as creatingnew instances of the objects and passing in the e-mail address and the displayname. Once these addresses are created, we can use the to and from addresseswhen we instantiate the MailMessage object. Although it may seem like overkill,creating objects for such a simple thing as e-mail addresses, the real power ofthese new objects comes out in the creation of collections of these objects.Sending an e-mail to multiple people is as easy as adding new items to thecollection. This is how CC addresses are added.

 

MIME

All e-mails use MIME, Multipurpose Internet MailExtensions (RFC 1341). This enables attachments to be rendered into astandardized format. If you use Notepad to open the .eml file included in thecode download, you ll find that it contains blocks of encrypted text withheaders defining what type of data those blocks contain. If you ve everreceived an Unsolicited Commercial Email where the text of the message displayedthe HTML elements instead of rendering the HTML, it s because the personsending the e-mail forgot to set the MIME content to say it was HTML and yourmail program assumed it was text and displayed it as such. To avoid having thishappen, we are going to define the MimeContentType for our e-mail.

 

Because not all e-mail programs can display HTML content,we ll add two versions of the e-mail, one in HTML and one in plain text. To dothis, we ll use the AlternateView class to add the two messages, one with HTMLand one without. While the AlternateView class is based on the AttachmentBaseclass, these two versions of the e-mail will not show up as attachments becausethe AlternateView defines the data as content-type: multipart/alternative. Thisinforms the e-mail client that there are multiple ways to view the message andit can decide which one to display. In addition, including the HTML as analternate view for the e-mail rather than as an attachment prevents the clientfrom blocking the e-mail attachment as a potentially dangerous element.

 

The last thing to look at before digging into the codeitself is attaching a graphic for use in the e-mail. Although it is possible toreference an image on the Web with the appropriate url, most e-mail clientswill show broken images and the user will need to right-click to download theactual image. Rather than that, we are going to attach an image to the e-mail.As long as the html doesn t reference a location for the image, it will displaythe attachment as appropriate. Based on the documentation, it seems as thoughthe LinkedResource would be the best method for adding such an image. However,being not quite Beta software, not everything is working and the LinkedResourceis not available, so I am using the Attachment class instead. This means thatthe image will show up with a paperclip in most e-mail clients but thatshouldn t be a problem.

 

Flexibility

The default.aspx page contains a couple of textboxes toallow for input of a name and e-mail address and the body of the e-mail. Inaddition, there is a dropdown box that contains a number of potential subjects aboutwhich someone might want to contact a company: Broken Link, Missing Image, etc.I m using these subjects for more than just offering the user a choice ofsubjects, I am using them to select what information goes into the e-mailmessage.

 

I have built a very simple HTML file calledMailFormat.htm. This file uses two IMG tags to display the goldbar.gif image asa fancy separator. In addition, it has three text sections that serve asplaceholders. Once the html file has been loaded into a string, these placeholders can be replaced with the text of our response, the user s query, andthe subject line. In addition, there are several text files that contain theresponse to the various subject lines. Now, to the code!

 

Putting the Pieces Together

We ll start by assembling the text of the messages. Thefirst few lines show nothing out of the ordinary, defining a few stringvariables to hold the file path and names and two to hold the text we ll beusing. The first new element comes when we read the files into the stringvariables. Opening a file and reading the entire thing into a string variableis as easy as using My.Computer.Filesystem.ReadAllText. The My.Computer,available in VB.NET, is a handy shorthand to reference many of the itemsrelated to the computer, such as the Clipboard, audio, registry, files, etc.Not all of these are available to server applications, but Filesystem is, so we lltake advantage of it to read the files in.

 

With the files loaded and ready, it s time to make the e-mailaddresses: toAddress, ccAddress, and fromAddress. Creating the e-mail addressallows us to use the to and from addresses, but not the CC. For that, we ll addthe e-mail address to the CC collection. Next, define the MimeContentTypes andadd the alternate view messages, one html and one plain text. The last thing todo before sending the e-mail is to attach the goldbar.gif image. In mostinstances, the Attachment class will take care of determining the correctMimeContentType, as it does in this case. And now we can set up the SmtpClient.

 

The SmtpClient class handles the actual sending of the e-mail.If you don t want to get fancy and do HTML e-mail and use names to mask the e-mailaddresses, you can pass the to, from, subject, and text of the body directly tothe SmtpClient s overloaded send method. Because we ve gone through all of thiswork to define the e-mail message, we ll pass that to the send method and we redone at least we are as soon as the e-mail has been dropped off to theserver. If that s taking too long, due to a heavy volume of mail, you can useSendAsync to send the message asynchronously. An example of that can be foundin the MSDN documentation.

 

Conclusion

All in all I like the new features and functionality forSMTP in .NET 2.0. But there is a caveat to mention here. The inner workings ofconfiguring security for the SmtpClient are not quite finished, so it s notquite possible to define a user id and password for the SmtpClient to use whensending an e-mail. If you are connecting to an Exchange server, you can set itup to allow outbound e-mail from specific IP addresses or from computers withinyour domain without having to log in.

 

For more information on SMTP visit http://www.ietf.org/rfc/rfc0821.txt?number=821.

 

The sample code accompanyingthis article is available for download.

 

Josef Finsel is asoftware consultant with Strategic Data Solutions (http://www.sds-consulting.com). Hehas published a number of VB and SQL Server-related articles and is currentlyworking with VS 2005. He s also author of TheHandbook for Reluctant Database Administrators (Apress, 2001).

 

Begin Listing One Using the NewSystem.Net.Mail Class to Send Mail

Protected Sub sendEmail_Click(ByVal sender As Object, ByVal e _

   As System.EventArgs)Handles sendEmail.Click

 Dim sBody As String

 Dim fileReaderBody AsString

 Dim fileReaderFormat AsString

 Dim WebDirectory AsString = Server.MapPath(".") & ""

 Dim fileName As String =WebDirectory

 Dim htmlEmailFormat AsString = WebDirectory & "MailFormat.htm"

 Select Case Subject.Text

   Case "BrokenLink"

      fileName = fileName &"BrokenLink.txt"

   Case "MissingPicture"

     fileName = fileName& "MissingPicture.txt"

   Case"Typographical Error"

     fileName = fileName& "TypoError.txt"

   Case "Deal onRolexes"

     fileName = fileName& "Rolexes.txt"

   Case Else

     fileName = fileName& "other.txt"

 End Select

 fileReaderBody =My.Computer.FileSystem.ReadAllText(fileName)

 fileReaderFormat = _

   My.Computer.FileSystem.ReadAllText(htmlEmailFormat)

 sBody =fileReaderFormat.Replace("BODYGOESHERE", _

   messageBody.Text)

 sBody =sBody.Replace("CONTENTGOESHERE", fileReaderBody)

 sBody =sBody.Replace("SUBJECTGOESHERE", Subject.Text)

 Dim toAddress AsMailAddress = New _

   MailAddress("[email protected]", "Customer Support")

 Dim ccAddress AsMailAddress = New _

   MailAddress(emailAddress.Text, emailName.Text)

 Dim fromAddress AsMailAddress = New _

   MailAddress("[email protected]")

 Dim eMail As MailMessage= New _

   MailMessage(fromAddress, fromAddress)

 eMail.CC.Add(fromAddress)

 eMail.Subject =Subject.Text

 Dim htmlType AsSystem.Net.Mime.ContentType = _

   NewSystem.Net.Mime.ContentType("text/html")

 Dim txtType AsSystem.Net.Mime.ContentType = _

   NewSystem.Net.Mime.ContentType("text/plain")

 eMail.AlternateViews.Add(_

   AlternateView.CreateAlternateViewFromString(sBody, _

   htmlType))

 eMail.AlternateViews.Add(_

   AlternateView.CreateAlternateViewFromString(fileReaderBody _

   & vbCrLf &messageBody.Text, htmlType))

 Dim attchment AsAttachment = New _

   Attachment(WebDirectory& "goldbar.gif")

 eMail.Attachments.Add(attchment)

 Dim client As SmtpClient= New SmtpClient("smtp.finsel.com")

 client.Send(eMail)

End Sub

End Listing One

 

 

 

 

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like