Beware of the Byte Order MarkEncourage Creativity

System.Net.Mail How To

May 27th, 2007

You've Got System.Net.Mail!VS 2005 / Framework 2.0 adds a new way to email, the System.Net.Mail Namespace that uses SMTP (Simple Mail Transfer Protocol) to deliver messages. In this article, I’ll provide a simple example of how to use it and go over a couple of quirks that people get hung up on.

The MailMessage and SmtpClient classes are the heart of this new Namespace and sending an email is really just a matter of a couple of lines.
.
.
.
.
.

Dim EmailServer As New System.Net.Mail.SmtpClient(EmailServerName)
EmailServer.SendAsync(TestEmail, Me)

The code above makes a couple of assumptions. First, that the variables for the call have been filled with correct information and, second, that the target SMTP server uses Windows authentication. Also note that the MailMessage class implements the IDisposible interface so you might think it’s a candidate for the Using block as I mentioned in a previous article. However, since it is called async, the Using block would dispose of it prematurely so this is an exception to the rule where you should not use Using.

In addition to the basics of From, To, Subject, Body, you can use properties of the MailMessage to add attachments, set the CC and BCC, select the encoding method for the body, and do a few other things. For example, if you wanted to add a CC to the message above the code would look like this:

Dim TestEmail As New System.Net.Mail.MailMessage(EmailFrom, EmailTo, EmailSubject, EmailBody)
TestEmail.CC = EmailCC
Dim EmailServer As New System.Net.Mail.SmtpClient(EmailServerName)
EmailServer.SendAsync(TestEmail, Me)

If you wanted to add an attachment to the email, the code would look like this:

Dim TestEmail As New System.Net.Mail.MailMessage(EmailFrom, EmailTo, EmailSubject, EmailBody)
TestEmail.CC = EmailCC
TestEmail.Attachments.Add(New System.Net.Mail.Attachment(EmailAttachmentFileName))
Dim EmailServer As New System.Net.Mail.SmtpClient(EmailServerName)
EmailServer.SendAsync(TestEmail, Me)

There are several overloads available for creating attachments so you may want to consult MSDN help if you need more advanced options.

In the demo program, I keep it simple without CC’s or attachments although I do add in a callback for the async operation. Using the callback allows you to verify that the email was sent or not sent without tying up your program waiting for a response.

What if you need to authenticate onto a remote SMTP server where you don’t have Windows authentication available? In this case, you’ll need to create credentials, like so:

Dim TestEmail As New System.Net.Mail.MailMessage(EmailFrom, EmailTo, EmailSubject, EmailBody)
TestEmail.CC = EmailCC
TestEmail.Attachments.Add(New System.Net.Mail.Attachment(EmailAttachmentFileName))
Dim EmailServer As New System.Net.Mail.SmtpClient(EmailServerName)
EmailServer.Credentials = New System.Net.NetworkCredential(“emailaccount@remoteserver.com”, “mypassword”, “mail.remoteserver.com”)
EmailServer.SendAsync(TestEmail, Me)

In most cases you will need to provide the domain name on the email account ID and you’ll need to confirm that the mail subdomain is correct and allows this kind of login. Your password is sent as clear text basic authentication in this scenario so be careful! You can use other options to provide a more secure connection if your SMTP server supports them.

Now for a couple of quirks with System.Net.Mail.

First, if you’ve used other and earlier mail engines you may have gotten used to separating multiple TO email addresses with a semi-colon, like so:

EmailTo = “mrblah@mydomain.com; msblank@mydomain.com”

However, in this case a formatting exception will be thrown. Yes, it surprised me too the first time this happened. The correct delimiter to use with System.Net.Mail is a comma, like so:

EmailTo = “mrblah@mydomain.com, msblank@mydomain.com”

My other quirk that you might encounter is that the low level code that System.Net.Mail uses might get mistaken for a mass emailing virus by some versions of anti-virus software. While these anti-virus block System.Net.Mail email they will allow email by older CDO and System.Web.Mail methods to function normally. If you encounter this problem, the solution is the consult with the anti-virus company to see if they have an update available or you might want to risk disabling this part of the anti-virus protection, depending on your circumstances. As a last resort, you can fall back to the older methods that should work OK.

» Click here to download VB.NET source code for this article.

Share This Article: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Technorati
  • DotNetKicks
  • DZone

Entry Filed under: Code Examples


Rate This Article:

Not That GoodCould Be BetterOKGoodGreat (No Ratings Yet)
Loading ... Loading ...

6 Comments Add your own

  • 1. irene  |  October 17th, 2007 at 1:50 am

    Using Sendsync, can I know whether the email has been sent?

  • 2. jfrankcarr  |  October 17th, 2007 at 8:02 am

    Hi Irene

    Yes. The SmtpClient object has an event called SendCompleted. To use it you would have to declare this object at the module level and add a handler. Here’s an example. First the code to initialize the SmtpClient and add the handler:

    EmailServer = New System.Net.Mail.SmtpClient(EmailServerName)
    AddHandler EmailServer.SendCompleted, AddressOf EmailSendCompleted

    Now the routine that waits for the SendCompleted event.

    Private Sub EmailSendCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.AsyncCompletedEventArgs)
        If e.Error IsNot Nothing OrElse e.Cancelled Then
            ‘do error management 
        End If
    End Sub
  • 3. jay  |  October 25th, 2007 at 11:19 pm

    Thanks a lot It’s help a lot

  • 4. jfrankcarr  |  October 26th, 2007 at 9:20 am

    Thanks Jay. I’m always glad to help.

  • 5. Yadira  |  February 12th, 2008 at 11:06 am

    Hi !!

    Can you explain me the “UserToken” in the SendAsync method?

    Thanks !!

  • 6. Susan  |  June 29th, 2008 at 1:13 am

    > Can you explain me the “UserToken” in the SendAsync method?

    Ugh. What do we put in for a value in “UserToken”????

    Without that info… none of this works at all.

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Most Popular Articles

Highest Rated Articles

Categories

Most Recent Articles

Feeds

 Subscribe in a reader

To subscribe by e-mail
Enter your address here

Delivered by FeedBurner

VB Opportunities

Archives