Back to all posts

Sending E-mail .NET 1.1 and 2.0 - Including Sending Login Information

Posted on Mar 01, 2007

Posted in category:
Development
.NET

Sending e-mails from a .NET application is a very easy process using built-in classes.  This article will discuss the methods needed to send e-mails, the differences between .NET 1.1 and .NET 2.0 implementations, as well as the benefits of new features in .NET 2.0.  This can be considered a comprehensive overview that can be used to reference the differences and methods for using e-mail in .NET 1.1 and 2.0.

This article will be broken into the following four sections.

  1. Class Information
  2. .NET 1.1 Examples
  3. .NET 2.0 Examples
  4. .NET 2.0 Tip

Class Information

Although the methods to send e-mail is similar between .NET 1.1 and .NET 2.0 there were many changes when Microsoft implemented .NET 2.0.  The most noticeable change is the moving of the classes from the System.Web.Mail namespace to the System.Net.Mail namespace.  Microsoft is cited as saying this was done to remove the appeared web dependency on the e-mail tools.  In addition to the namespace change they did rename and add multiple classes which result in a slightly different experience.  Below is a chart showing you the "important" classes relating to sending e-mmail messages.

.NET 1.1 Classes (System.Web.Mail Namespace)*
Class Description
MailAttachment Provides properties and methods for adding a mail attachment
MailMessage Provides properties and methods for creating an e-mail message
SmtpMail Provides properties and methods for sending MailMessage objects using SMTP
* Although obsolete in .NET 2.0 these objects are still available for use with .NET 2.0 but will generate a compile warning
.NET 2.0 Classes(System.Net.Mail Namespace)**
Class Description
Attachment Represents an e-mail attachment (Replaces MailAttachment)
AttachmentCollection Stores attachments to be sent as part of an e-mail
MailAddress Represents the address of an e-mail sender or recipient
MailAddressCollection Stores e-mail addresses for use with sending an e-mail (Sender, Recipient, CC, and BCC lists)
MailMessage Represents an e-mail message
SmtpClient Allows the sending of SMTP MailMessages. (Replaces SmtpMail)
SmtpPermission Controls access to SMTP servers
SmtpPermissionAttributes Used with SmtpPermission to store access information
** Some objects omitted, see MSDN for the full list

.NET 1.1 Examples

Sending e-mail in the .NET 1.1 framework takes a little less effort than using .NET 2.0, however it is slightly less robust.  A specific example is that you must configure your SMTP address for each instance of the SmtpMail class.  Additionally specifying user credentials is slightly more difficult.  Below you will see examples of how to send  three types of e-mail messages.
Plain-text Message (Not Sending Authentication)
Plain-text Message (Sending Authentication)
HTML Message with Attachment

Plain-text Message (Not Sending Authentication)

The most simple type of e-mail message to send is a plain-text e-mail that will be sent from a SMTP server that does not require authentication. Below you will see a code sample showing the required steps, after the code sample the details will be discussed.

Simple Email Send (VB.NET)

Sub PlainTextNoAuthentication(ByVal oServer As String, _
                                ByVal oSendTo As String, _
                                ByVal oFrom As String, _
                                ByVal oSubject As String, _
                                ByVal oBody As String)
    'Declare the MailMessage
    Dim oMessage As New MailMessage
     'Set the to and from addresses
    oMessage.From = oFrom
    oMessage.To = oSendTo
    'Set the subject
    oMessage.Subject = oSubject
    'Set the body and declare as NOT HTML
    oMessage.BodyFormat = MailFormat.Text
    oMessage.Body = oBody
    'Set the mail server
    SmtpMail.SmtpServer = oServer
    'Send the message
    SmtpMail.Send(oMessage)
    'Shortened form could be used inplace of MailMessage
    'SmtpMail.Send(oFrom, oSendTo, oSubject, oBody)
End Sub

As you can see from this example the use of the MailMessage object is not necessarily needed when sending an e-mail with simple plain text formatting, however, to use advanced features such as carbon copy (CC), blind carbon copy (BCC), and attachments you must use the MailMessage object.  The main parts to note in this example are the SmtpMail.SmtpServer = oServer and SmtpMail.Send(oMessage) lines.  The first instructs the .NET Framework to send e-mail using the specified server.  The server name should be the full name of your outgoing SMTP mail server.  The second instructs the .NET Framework to send the included message via the specified server. 

This method will work for any SMTP server that does not require authentication to send the message.  For those requiring authentication when sending mail messages please see the below message

Plain-text Message (Sending Authentication)

In .NET 1.1 it is possible to send an e-mail via authenticated SMTP using the MailMessage Fields collection.  This was added to .NET 1.1 and provided the first chance to send e-mails via an authenticated connection with .NET  Below is the code needed to send a plain text message via the SmtpMail object.  NOTE: the use of the MailMessage object is REQUIRED when sending via an authenticated SMTP channel

Authenticated Example

Sub PlainTextAuthentication(ByVal oServer As String, _
                            ByVal oUser As String, _
                            ByVal oPassword As String, _
                            ByVal oSendTo As String, _
                            ByVal oFrom As String, _
                            ByVal oSubject As String, _
                            ByVal oBody As String)
    'Declare and build the standard MailMessage 
    '(See previous example for detail)
    Dim oMessage As New MailMessage
    oMessage.From = oFrom
    oMessage.To = oSendTo
    oMessage.Subject = oSubject
    oMessage.BodyFormat = MailFormat.Text
    oMessage.Body = oBody
    'Storing keys to a varible to provide readable code
    Dim oAuthenticationKey As String = _
            "http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"
    Dim oSendUsernameKey As String = _
            "http://schemas.microsoft.com/cdo/configuration/sendusername"
    Dim oSendPasswordKey As String = _
            "http://schemas.microsoft.com/cdo/configuration/sendpassword"
    'Add field information for the authentication, username, and password
    oMessage.Fields.Add(oAuthenticationKey, "1")    'Enables basic authentication
    oMessage.Fields.Add(oSendUsernameKey, oUser)    'Sends the username with the msg
    oMessage.Fields.Add(oSendPasswordKey, oPassword) 'Sends the password with the msg
    'Set the mail server
    SmtpMail.SmtpServer = oServer
    'Send the message
    SmtpMail.Send(oMessage)
End Sub

As you can see the big addition in this example is the three oMessage.Fields.Add(.. method calls.  This associates your authentication information with the MailMessage.  Due to the code requirements for this functionality this is something that will be very helpful to move into a helper class if your SMTP server requires authentication for sending e-mails to avoid duplication of code.

HTML Message with Attachment

This final example for the .NET 1.1 framework will show you how to include an attachment with an HTML formatted email.  For the sake of brevity this example will utiize the non-authenticated SMTP sending method.  If you need to send an attachment via SMTP with authentication, simply add the needed arguments listed in the above example.

Sending with Attachment (VB)

Sub HtmlWithAttachment(ByVal oServer As String, _
                            ByVal oSendTo As String, _
                            ByVal oFrom As String, _
                            ByVal oSubject As String, _
                            ByVal oBody As String, _
                            ByVal oAttachmentPath As String)
    'Setup the basics of the mail message
    Dim oMessage As New MailMessage
    oMessage.From = oFrom
    oMessage.To = oSendTo
    oMessage.Subject = oSubject
    'Set the body, NOTE: we expect that the oBody passed is HTML
    oMessage.BodyFormat = MailFormat.Html
    oMessage.Body = oBody
    'Declare the Attachment object, passign the path
    Dim oAttachment As New MailAttachment(oAttachmentPath)
    'Add the attachment to the message
    oMessage.Attachments.Add(oAttachment)
    'Set the server and send
    SmtpMail.SmtpServer = oServer
    SmtpMail.Send(oMessage)
End Sub

The process for adding an attachment is very simple, however, there are a few points to remember when including attachments. 

  1. Ensure that the file to be attached exists on the system
  2. Do not delete the attachment file right after calling "SmtpMail.Send()" as it can take a little while for the message to fully send after the SmtpMail.Send() method completes. This is related to the use of CDONTS to send the message
  3. Be aware of the number of recipients and the number of attachments being sent to avoid overloading e-mail servers

.NET 2.0 Examples

.NET 2.0 greatly changed the methods to send e-mail messages. The most noticable difference is the addition of the MailAddress class.  The MailAddress class holds the information for a given e-mail recipient or sender.  You can specify the delivery address, display name, and encoding for each recipient.  The addition of this class does slightly complicate the assignment of your e-mail address because you are no longer allowed to directly assign a string e-mail address to a MailMessage object after it has been created.  Below examples will be provided that show you the various in's and outs of sending messages using .NET 2.0's new System.Net.Mail namespace classes.  Please note examples regarding mail attachments have been omitted as the process is similar to the old method.

Plain-text E-mail Using String E-mail Addresses
Plain-text E-mail Using MailAddress for E-mail Address
Plain-text E-mail With Authentication

Plain-text E-mail Using String E-mail Addresses

To send an E-mail address using string values for both the to and from addresses without using the MailAddress wrapper class you must use a method similar to the following.

.NET Core 2.0 - Simple Email (VB)

Sub PlainTextNoAuthentication(ByVal oServer As String, _
                                ByVal oFrom As String, _
                                ByVal oTo As String, _
                                ByVal oSubject As String, _
                                ByVal oBody As String)
    'Declare the message
    Dim oMessage As New MailMessage(oFrom, oTo)
    'Set the subject
    oMessage.Subject = oSubject
    'Set the body
    oMessage.IsBodyHtml = False
    oMessage.Body = oBody
    'Set the mail server
    Dim oClient = New SmtpClient(oServer)
    'Send the message
    oClient.Send(oMessage)
End Sub

Plain-text E-mail Using MailAddress for E-mail Address

This example shows you how you can set the E-mail address after you have created the mail message but how you are forced to use the mail message class.

.NET 2.0 With Authentication (VB)

Sub PlainTextNoAuthentication(ByVal oServer As String, _
                                ByVal oFrom As String, _
                                ByVal oTo As String, _
                                ByVal oSubject As String, _
                                ByVal oBody As String)
    'Declare the message
    Dim oMessage As New MailMessage()
    'Set the to and from addresses
    oMessage.From = New MailAddress(oFrom)
    oMessage.To.Add(oTo)
    'Set the subject
    oMessage.Subject = oSubject
    'Set the body
    oMessage.IsBodyHtml = False
    oMessage.Body = oBody
    'Set the mail server
    Dim oClient = New SmtpClient(oServer)
    'Send the message
    oClient.Send(oMessage)
End Sub

Plain-text E-mail With Authentication

In .NET 2.0 Microsoft introduced a new method for providing user credentials while sneding SMTP messages, below is an example of how this works and how much easier your code is to read using this new method.

.NET 2.0 With Authentication (VB)

Sub PlainTextWithAuthentication(ByVal oServer As String, _
                                ByVal oUsername As String, _
                                ByVal oPassword As String, _
                                ByVal oFrom As String, _
                                ByVal oTo As String, _
                                ByVal oSubject As String, _
                                ByVal oBody As String)
    'Declare the message
    Dim oMessage As New MailMessage(oFrom, oTo)
    'Set the subject
    oMessage.Subject = oSubject
    'Set the body
    oMessage.IsBodyHtml = False
    oMessage.Body = oBody
    'Build the Credential object
    Dim oAuthInfo = New System.Net.NetworkCredential(oUsername, oPassword)
    'Set the mail server, and auth items
    Dim oClient = New SmtpClient(oServer)
    oClient.Host = oServer
    oClient.UseDefaultCredentials = False
    oClient.Credentials = oAuthInfo
    'Send the message
    oClient.Send(oMessage)
End Sub

.NET 2.0 Tip

The .NET Framework 2.0 provides an added feature to allow you to easily configure the SmtpClient from your app.config or web.config file. This centralizes the storage of your login information, these settings are automatically read by the SmtpClient when you create a new instance of it, therefore you do not have to set any properties to send messages.  This will reduce the amount of code needed to send an e-mail. Below is the configuration elements that are required to setup the SmtpClient settings

Sample Config Snippet
 <system.net>
   <mailSettings> 
     <smtp> 
       <network  host ="<Your Server>" userName ="<Your Username>"  password ="<Your Password>"   />
    </smtp> 
   </mailSettings> 
</system.net>

This configuration section is placed inside the root <configuration> element and can be used in both app.config and web.config files.  Simply replace the listed values with the appropriate ones for your server.  If your server does not require authentication remove the "userName" and "password" declarations. An additional option is available called "port" which will allow you to specify a different communication port if you are using a non standard SMTP setting.

Once you have this configuration setup you may use the following code to send your e-mails.

Simple Send Example
Dim oClient as New SmtpClient
oClient.Send(oMessage)    'oMessage is your message object

Conclusion

This should provide a great starting point or reference for the methods around sending SMTP e-mails. Please leave your feedback below on this article. Code samples are available in both VB.NET and C#.NET, please e-mail me indicating the article and the sample desired. I will work to upload these samples soon!