Click here to Skip to main content
15,867,308 members
Articles / Web Development / IIS
Article

Easy SMTP Mail Using ASP.NET 2.0

Rate me:
Please Sign up or sign in to vote.
4.74/5 (38 votes)
4 Oct 200611 min read 509.9K   9.4K   188   80
The article addresses two topics: sending an email message to a standard email account, and sending an SMS message to a cell phone or pager.

Introduction

The article addresses two topics: sending an email message to a standard email account, and sending an SMS message to a cell phone or pager. The approach uses the SMTP client contained in System.Net to accomplish both types of message submittal, and all messages are sent from ASP.NET 2.0 ASPX pages.

The SMTP email portion application will demonstrate the following:

  • Using SMTP to configure and send email messages
  • Adding ‘CC’ addresses as message recipients
  • Adding attachments to a message

The SMS portion of the email application will demonstrate the following:

  • Passing standard email messages through the carrier to deliver SMS messages to the target.

In addition to discussing the small bit of code necessary to send these messages, the document will address the primary configuration requirements needed to successfully send messages through an ASP.NET 2.0 based website on an IIS server.

In order to use this demonstration, you should have an instance of IIS installed on your development machine, you should have Visual Studio 2005 installed, and you should have the optional SMTP mail server installed in your local IIS instance.

Image 1

Figure 1: The main page of the demonstration application

Getting Started

Unzip the attached file; in it, you will find a solution containing a web site project entitled, “RealMail”. Store the unzipped file onto your system, and create a virtual directory pointing to the web application from IIS. Then, open the solution in Visual Studio 2005. Looking at the Solution Explorer, you will see the files indicated in figure 2.

Image 2

Figure 2: RealMail web application in the Solution Explorer

There are two ASPX pages in the solution, the first (default.aspx) is used to send a standard message to a recipient using the .NET 2.0 SMTP class library; the second page is used to send an SMS message to a cellular telephone or messaging pager through SMTP.

IIS Configuration

Your local IIS instance has to be properly configured in order to successfully send an email message through its SMTP mail server. Even if you install IIS, the SMTP mail server installation is optional, and must be explicitly added to the installation. If you are not sure whether or not the SMTP mail server is installed, open up the IIS control panel and check for the installation; if it is installed, you will see a reference to the Default SMTP Virtual Server in the tree view (Figure 3):

Image 3

Figure 3: Default SMTP Virtual Server installed

If the server is not installed, you will need to use the “Add and Remove Windows Components” function in the “Add and Remove Programs” control panel to add the SMTP server to your IIS installation. If you need to do this additional installation, once you’ve opened “Add and Remove Windows Components”, click on “Internet Information Services (IIS)” to highlight it, and then click on the “Details” button (Figure 4). This will open an IIS dialog; examine this dialog to locate “SMTP Service”, and click on it to place a check mark on the box (Figure 5). Once this item has been checked, click on the “OK” button to install the SMTP server.

Image 4

Figure 4: Windows Components Wizard

Image 5

Figure 5: Adding the SMTP Service to IIS

Once the default SMTP server has been installed or verified, you can now configure it to send email. In order to configure the SMTP server, open the IIS control panel, locate the default SMTP server icon in the tree view, and select and right click the icon. Once the context menu has been displayed, locate “Properties”, and click on it to open the Properties menu. Once the Default SMTP Virtual Server Properties dialog is displayed, click on the “Access” tab (Figure 6):

Image 6

Figure 6: SMTP Properties dialog

Select the “Authentication” button to display the authentication options (Figure 7):

Image 7

Figure 7: Authentication options

Make sure that the Anonymous access option is checked, and that all other options are unchecked; in some instances, you may wish to use the other options, but in most cases involving a public website, this is the option you’d want. Once you have verified this setting, click “OK” to close this dialog.

Back to the “Access” tab, locate and click on the “Relay” button to display the relay options. Note that the radio button for “Only the list below” is selected, and that the local host IP address has been added to the list of computers permitted to relay through the SMTP server. Naturally, this is OK for a development machine, but in deployment, you would use the actual IP address of the web server. If no IP addresses are shown in the list, click on the “Add” button and add the IP address. Once finished, click on the “OK” button to accept the changes and to dismiss the dialog (Figure 8).

Image 8

Figure 8: Relay Restrictions dialog

Next, select the “Delivery” tab from the SMTP Server Properties dialog (Figure 9):

Image 9

Figure 9: Delivery Options dialog

From this dialog, select the “Advanced” button to reveal the advanced options dialog (Figure 10):

Image 10

Figure 10: Advanced Delivery dialog

From this dialog, there are two points to make: first, the “Fully qualified domain name” property should be pre-populated, you may click on the “Check DNS” button to validate the setting. The next option is probably the most critical item for the whole shooting match; the Smart Host property has to be set to point to a valid SMTP mail server that will permit you to relay mail. For most cases, you will key in the name of your internet provider’s default SMTP mail server; the address is likely to be in the format of “mail.something.com” where “something” is the internet provider’s domain name. There are two easy ways to get this: one is, if you are using Outlook, open up Outlook and pull up the information on your email account; the mail server will be listed there. The second option is to guess, and you can qualify your guess by pinging the server.

If your internet provider’s name is “foxtrox”, try pinging mail.foxtrot.com; if you get a response there, that is probably the one to use. If that does not work, contact your administrator and ask them for the information on the SMTP mail server; don’t try to plug in an Exchange server, there will likely be an SMTP mail server out there even if your company is using an Exchange server. The only other hurdle is to make sure that the SMTP mail server will allow you to relay, and again, you may need to talk to the administrator if the server bounces your mail. Once these settings are made, click on the “OK” button to save the settings and close the dialog.

The last thing to do is to check the security tab to make sure the accounts are properly configured; once done, your security settings should look something like this (Figure 11):

Image 11

Figure 11: Security settings for the SMTP server

Once everything is setup, click on the “OK” button to save the settings and to close the Default SMTP Virtual Server Properties dialog.

The Code: Sending an Email From an ASP.NET 2.0 Web Page

Open up the default.aspx code window from the included example project, and examine the code used to send an email.

Imports

Note that the project includes only three imports:

VB
Imports System
Imports System.Net
Imports System.Net.Mail

The application uses the System.NET.Mail libraries to format and send SMTP based email messages; these imports are required to run the project, and to send the email messages. This is also new to ASP.NET 2.0 and Visual Studio 2005.

Declarations

Within the declarations section at the beginning of the project, you will note a standard class declaration followed by a region called “Declarations”; within the Declarations region is a collection of variables used to contain information used in sending the mail:

VB
Partial Class _Default_
        Inherits System.Web.UI.Page

#Region "Declarations"
     ' message elements
    Private mMailServer As String
    Private mTo As String
    Private mFrom As String
    Private mMsg As String
    Private mSubject As String
    Private mCC As String
    Private mPort As Integer

#End Region

The Code

The first bit of code is a subroutine used to generate alerts; it has no bearing on the topic of sending messages, but I frequently use this code block whenever I want to generate an alert from a web page. The code is pretty simple. It merely places the JavaScript code necessary to define and display an alert box into the text field of a Label control, and then adds the control to the current page; since the Label will fire any JavaScript passed to it, as soon as the control is added to the page, the alert box will fire.

VB
Private Sub MessageBox(ByVal strMsg As String)

    ' generate a popup message using javascript alert function
    ' dumped into a label with the string argument passed in
    ' to supply the alert box text
    Dim lbl As New Label
    lbl.Text = "<script language="'javascript'">" & Environment.NewLine _
                & "window.alert(" & "'" & strMsg & "'" & ")</script>"

    ' add the label to the page to display the alert
    Page.Controls.Add(lbl)

End Sub

The only other bit of code in the application is the Send button’s Click event handler; this handler captures the user’s inputs from the page, uses those inputs to populate the message related variables, and then formats a message using the variable content. You may note that the server and port settings are extracted from the AppSettings contained in the web.config file.

When examining the code, note how the file attachment and the CC list is handled by the code contained in the Try-Catch block. If you wanted to add blind carbon copies (BCC recipients), you could add them in a manner similar to that applied to processing the standard CC list.

Here is the entire block of code:

VB
Protected Sub btnSend_Click(ByVal sender As Object, _
          ByVal e As System.EventArgs) Handles btnSend.Click

    'send message

    Dim strMsg As String
    strMsg = txtMessage.Text

    mTo = Trim(txtTo.Text)
    mFrom = Trim(txtFrom.Text)
    mSubject = Trim(txtSubject.Text)
    mMsg = Trim(txtMessage.Text)
    mMailServer = ConfigurationManager.AppSettings.Get("MyMailServer")
    mPort = ConfigurationManager.AppSettings.Get("MyMailServerPort")
    mCC = Trim(txtCC.Text)

    Try

        Dim message As New MailMessage(mFrom, mTo, mSubject, mMsg)

        If fileAttachments.HasFile Then
            Dim attached As New 
            Attachment(Trim(fileAttachments.PostedFile.FileName.ToString()))
            message.Attachments.Add(attached)
        End If

        If mCC <> "" Or mCC <> String.Empty Then
            Dim strCC() As String = Split(mCC, ";")
            Dim strThisCC As String
            For Each strThisCC In strCC
                message.CC.Add(Trim(strThisCC))
            Next
        End If


        Dim mySmtpClient As New SmtpClient(mMailServer, mPort)
        mySmtpClient.UseDefaultCredentials = True
        mySmtpClient.Send(message)

        MessageBox("The mail message has been sent to " & message.To.ToString())

    Catch ex As FormatException

        MessageBox("Format Exception: " & ex.Message)

    Catch ex As SmtpException

        MessageBox("SMTP Exception:  " & ex.Message)

    Catch ex As Exception

        MessageBox("General Exception:  " & ex.Message)

    End Try

End Sub

Within the Try-Catch block, note that format, SMTP, and general exceptions are trapped, and displayed to the user using the MessageBox subroutine at the beginning of the code block.

The Code: Sending an SMS Message Through ASP.NET 2.0

Open up the sendSmsMsg.aspx code window from the included example project, and examine the code used to send an SMS message as email.

Imports

Note that the project includes only three imports:

VB
Imports System
Imports System.Net
Imports System.Net.Mail

The application uses the System.NET.Mail libraries to format and send SMTP based email messages; these imports are required to run the project and to send the email based SMS messages.

Declarations

Within the declaration section at the beginning of the project, you will note a standard class declaration followed by a region called “Declarations”; within the Declarations region, is a collection of variables used to contain information used in sending the email based SMS messages:

VB
Partial Class sendSmsMsg _
        Inherits System.Web.UI.Page

#Region "Declarations"
     ' message elements
    Private mMailServer As String
    Private mTo As String
    Private mFrom As String
    Private mMsg As String
    Private mSubject As String
    Private mPort As Integer

#End Region

The Code

So far, you may have noticed that everything is the same up to this point; from this point on, things will continue to be similar, but there are a few interface and variable differences that make it possible to send SMS messages via the SMTP server.

The most interesting thing to note with regards to sending an SMS message is that you don’t have to do anything special. The carriers expose an interface through which you can send an email message (with some restrictions) to the cell phone subscriber, and the carrier will transmit that message as SMS to the subscriber.

In general, the important things to know are that the address of the subscriber is their ten digit cell number (area code and number) coupled with the carrier's specified address. This application includes a list of most of the US carriers and some off shore carriers as well. If you are located outside of the US, you may need to do a little research to find the proper address for your targeted carriers, and I should point out that some carriers do not support this interface.

In the page load event handler, I have populated a drop down list with the list of carriers:

VB
Protected Sub Page_Load(ByVal sender As Object, _
          ByVal e As System.EventArgs) Handles Me.Load

    ' Load the names of the common carriers 
    cboCarrier.Items.Add("@itelemigcelular.com.br")
    cboCarrier.Items.Add("@message.alltel.com")
    cboCarrier.Items.Add("@message.pioneerenidcellular.com")
    cboCarrier.Items.Add("@messaging.cellone-sf.com")
    cboCarrier.Items.Add("@messaging.centurytel.net")
    cboCarrier.Items.Add("@messaging.sprintpcs.com")
    cboCarrier.Items.Add("@mobile.att.net")
    cboCarrier.Items.Add("@mobile.cell1se.com")
    cboCarrier.Items.Add("@mobile.celloneusa.com")
    cboCarrier.Items.Add("@mobile.dobson.net")
    cboCarrier.Items.Add("@mobile.mycingular.com")
    cboCarrier.Items.Add("@mobile.mycingular.net")
    cboCarrier.Items.Add("@mobile.surewest.com")
    cboCarrier.Items.Add("@msg.acsalaska.com")
    cboCarrier.Items.Add("@msg.clearnet.com")
    cboCarrier.Items.Add("@msg.mactel.com")
    cboCarrier.Items.Add("@msg.myvzw.com")
    cboCarrier.Items.Add("@msg.telus.com")
    cboCarrier.Items.Add("@mycellular.com")
    cboCarrier.Items.Add("@mycingular.com")
    cboCarrier.Items.Add("@mycingular.net")
    cboCarrier.Items.Add("@mycingular.textmsg.com")
    cboCarrier.Items.Add("@o2.net.br")
    cboCarrier.Items.Add("@ondefor.com")
    cboCarrier.Items.Add("@pcs.rogers.com")
    cboCarrier.Items.Add("@personal-net.com.ar")
    cboCarrier.Items.Add("@personal.net.py")
    cboCarrier.Items.Add("@portafree.com")
    cboCarrier.Items.Add("@qwest.com")
    cboCarrier.Items.Add("@qwestmp.com")
    cboCarrier.Items.Add("@sbcemail.com")
    cboCarrier.Items.Add("@sms.bluecell.com")
    cboCarrier.Items.Add("@sms.cwjamaica.com")
    cboCarrier.Items.Add("@sms.edgewireless.com")
    cboCarrier.Items.Add("@sms.hickorytech.com")
    cboCarrier.Items.Add("@sms.net.nz")
    cboCarrier.Items.Add("@sms.pscel.com")
    cboCarrier.Items.Add("@smsc.vzpacifica.net")
    cboCarrier.Items.Add("@speedmemo.com")
    cboCarrier.Items.Add("@suncom1.com")
    cboCarrier.Items.Add("@sungram.com")
    cboCarrier.Items.Add("@telesurf.com.py")
    cboCarrier.Items.Add("@teletexto.rcp.net.pe")
    cboCarrier.Items.Add("@text.houstoncellular.net")
    cboCarrier.Items.Add("@text.telus.com")
    cboCarrier.Items.Add("@timnet.com")
    cboCarrier.Items.Add("@timnet.com.br")
    cboCarrier.Items.Add("@tms.suncom.com")
    cboCarrier.Items.Add("@tmomail.net")
    cboCarrier.Items.Add("@tsttmobile.co.tt")
    cboCarrier.Items.Add("@txt.bellmobility.ca")
    cboCarrier.Items.Add("@typetalk.ruralcellular.com")
    cboCarrier.Items.Add("@unistar.unifon.com.ar")
    cboCarrier.Items.Add("@uscc.textmsg.com")
    cboCarrier.Items.Add("@voicestream.net")
    cboCarrier.Items.Add("@vtext.com")
    cboCarrier.Items.Add("@wireless.bellsouth.com")

End Sub

When using the application, you will see this list of carriers in the area used to define the recipient’s address (see Figure 12):

Image 12

Figure 12: List of carriers used to address SMS recipients

The message contains the ‘To’ address, a ‘From’ address, a subject line, and the message body itself (which is limited to 140 characters in length).

Clicking the Send button will start the ball rolling by executing the following Click event handler:

VB
Protected Sub Button2_Click(ByVal sender As Object, _
          ByVal e As System.EventArgs) Handles Button2.Click

    'send message

    Dim strMsg As String
    strMsg = txtMessage.Text

    If strMsg.Length >= 140 Then
        strMsg = strMsg.Substring(1, 140)
    End If

    mTo = Trim(txtToNumber.Text) & _
          Trim(cboCarrier.SelectedItem.ToString())
    mFrom = Trim(txtFrom.Text)
    mSubject = Trim(txtSubject.Text)
    mMsg = Trim(txtMessage.Text)
    mMailServer = ConfigurationManager.AppSettings.Get("MyMailServer")
    mPort = ConfigurationManager.AppSettings.Get("MyMailServerPort")

    Try

        Dim message As New MailMessage(mFrom, mTo, mSubject, mmsg)
        Dim mySmtpClient As New SmtpClient(mMailServer, mPort)
        mySmtpClient.UseDefaultCredentials = True
        mySmtpClient.Send(message)

        MessageBox("The mail message has been sent to " & _
                    message.To.ToString())

    Catch ex As FormatException

        MessageBox("Format Exception: " & ex.Message)

    Catch ex As SmtpException

        MessageBox("SMTP Exception:  " & ex.Message)

    Catch ex As Exception

        MessageBox("General Exception:  " & ex.Message)

    End Try


End Sub

As you will quickly see, the code is the same with a couple of minor exceptions; one pertains to validating the size of the message to be less than 140 characters, and the other major exception is in how the address of the recipient is constructed.

Of course, it should go without saying that the recipient of the message is charged a fee for the transactions, and as tempting as it might be to set this up to loop a couple of thousand times and send “Happy Birthday” greetings to your ex-wife’s divorce attorney, don’t do it.

The rest of the code in this page is identical to the default page described earlier; that includes the code to generate the alerts; there is also a hyperlink on both pages that allows you to traverse back and forth between the pages.

Summary

The article and sample project were intended to demonstrate the approach used to send email messages using SMTP through .NET; the examples also attempted to describe the ease with which this approach could be used to send SMS messages to cell phone subscribers using the same techniques applied to sending standard email messages.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer (Senior)
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionHello- good app Pin
Maheah M13-Jul-23 6:31
Maheah M13-Jul-23 6:31 
QuestionGetting Error Pin
Member 1217161317-Mar-16 6:05
Member 1217161317-Mar-16 6:05 
Questionequal sign appear in my message Pin
The14thNoah10-Feb-14 16:26
The14thNoah10-Feb-14 16:26 
Questionhi to all Pin
shalinibharani9-Jul-12 0:57
shalinibharani9-Jul-12 0:57 
Questionhi to all Pin
shalinibharani9-Jul-12 0:56
shalinibharani9-Jul-12 0:56 
QuestionGood - How to send email in asp.net or C# Pin
madhan2u8-May-12 21:31
madhan2u8-May-12 21:31 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey24-Apr-12 23:42
professionalManoj Kumar Choubey24-Apr-12 23:42 
Questiongradient panel Pin
piya188-Apr-12 10:07
piya188-Apr-12 10:07 
QuestionMail From Asp.net Pin
hardik1421-Feb-12 6:57
hardik1421-Feb-12 6:57 
QuestionSending mail message via asp.net Pin
ashaq Majid12-Oct-11 0:51
ashaq Majid12-Oct-11 0:51 
GeneralMy vote of 5 Pin
sairfan17-Jul-11 22:32
sairfan17-Jul-11 22:32 
QuestionHow to find the subscribers carriers address Pin
Cai Ming En30-Mar-11 0:58
Cai Ming En30-Mar-11 0:58 
GeneralEmail Working, but sms not working Pin
vivek090822-Sep-10 20:12
vivek090822-Sep-10 20:12 
GeneralReading ther reply Pin
xcalculus4-Apr-10 5:44
xcalculus4-Apr-10 5:44 
GeneralRe: Reading ther reply Pin
vivek090822-Sep-10 20:14
vivek090822-Sep-10 20:14 
QuestionSMS sending not working for me Pin
vidhyacoder22-Feb-10 2:16
vidhyacoder22-Feb-10 2:16 
AnswerRe: SMS sending not working for me Pin
jsam7828-Feb-10 3:47
jsam7828-Feb-10 3:47 
GeneralFully-qualified domain name and Smart host Pin
powerscott31-Jan-10 4:05
powerscott31-Jan-10 4:05 
GeneralASP.NET 2.0 - Send SMS Message Demonstration Pin
Sonam S. Diwate15-Jan-10 0:43
Sonam S. Diwate15-Jan-10 0:43 
QuestionHow to send to a pager? Pin
s196675m12-Nov-09 6:53
s196675m12-Nov-09 6:53 
GeneralAbout send mail without mail server User and password Pin
sanjay3010-Aug-09 0:59
sanjay3010-Aug-09 0:59 
GeneralFailure sending mail -Unable to connect to remote server Pin
saifkhan58323-Jul-09 4:59
saifkhan58323-Jul-09 4:59 
GeneralEmail haven't sent at all Pin
saifkhan58323-Jul-09 3:24
saifkhan58323-Jul-09 3:24 
GeneralRe: Email haven't sent at all Pin
vivek090822-Sep-10 20:00
vivek090822-Sep-10 20:00 
Generalfriend Pin
sasikalasengottaiyan18-Jun-09 21:03
sasikalasengottaiyan18-Jun-09 21:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.