Click here to Skip to main content
Click here to Skip to main content

Easy SMTP Mail Using ASP.NET 2.0

, 4 Oct 2006
Rate this:
Please Sign up or sign in to vote.
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.

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.

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):

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.

Figure 4: Windows Components Wizard

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):

Figure 6: SMTP Properties dialog

Select the “Authentication” button to display the authentication options (Figure 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).

Figure 8: Relay Restrictions dialog

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

Figure 9: Delivery Options dialog

From this dialog, select the “Advanced” button to reveal the advanced options dialog (Figure 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):

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:

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:

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.

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:

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:

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:

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:

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):

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:

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

Share

About the Author

salysle
Software Developer (Senior)
United States United States
No Biography provided

Comments and Discussions

 
GeneralRe: Great Job PinmemberKing Coffee6-Jan-10 19:41 
GeneralHi mam..... Pinmemberswetha_asp.net5-Dec-07 21:02 
GeneralPlease help me its not working for yahoo , gmail etc., even sms Pinmemberswetha_asp.net5-Dec-07 20:55 
GeneralRe: Please help me its not working for yahoo , gmail etc., even sms Pinmemberpvamsik24-Apr-09 10:50 
Generalquestion about email server Pinmemberjr90347-Nov-07 7:18 
Questionmessage cannot be sent to internal mail PinmemberSugi Lee5-Nov-07 17:28 
Generalsmtp exception Pinmemberyu zy27-Aug-07 1:20 
GeneralHelp PinmemberNirav Pate !27-Jul-07 2:22 
GeneralSerious help needed PinmemberHPKS28-May-07 18:15 
GeneralRe: Serious help needed Pinmembersalysle30-May-07 18:14 
GeneralHi PinmemberMakesh2117-May-07 20:41 
GeneralRe: Hi Pinmembersalysle21-May-07 1:03 
QuestionMessage sent = Not sent PinmemberStephanDelphi13-May-07 6:00 
AnswerRe: Message sent = Not sent Pinmembersalysle13-May-07 19:06 
Yes sir, that is it. Neither gmail nor yahoo permit anyone to relay through their mail servers. I believe that, once upon a time, gmail did allow relays. If you want a test case, you might try your ISP's mail server. I use mine for that purpose and it has always allowed me to relay my messages; if you are working on a corporate site; check with whoever controls the servers there and find out if they have an open smtp mail server and, if they do, is it set up to permit relays; I generally ping mail.thedomain.com (e.g., mail.pfizer.com) to see if it is active and then just try it before I resort to anything else.
 
There are paid services that allow message relays but likely you can find one that will do the trick.
GeneralRe: Message sent = Not sent Pinmemberrameez Raja21-Dec-08 1:56 
GeneralSMPT Exception: Failure sending mail Pinmemberwayne fernandez11-May-07 22:38 
GeneralRe: SMPT Exception: Failure sending mail Pinmemberhepo_bg12-May-07 5:23 
GeneralRe: SMPT Exception: Failure sending mail PinmemberMember 455147113-Feb-08 2:36 
GeneralRe: SMPT Exception: Failure sending mail PinmemberMember 272616718-Mar-08 22:32 
GeneralRe: SMPT Exception: Failure sending mail Pinmembersalysle13-May-07 18:54 
GeneralSMTP Authentication Pinmemberhepo_bg10-May-07 12:14 
GeneralRe: SMTP Authentication Pinmembersalysle11-May-07 4:32 
GeneralRe: SMTP Authentication Pinmemberhepo_bg12-May-07 5:20 
QuestionSMTP server needed? PinmemberKees Alderliesten26-Mar-07 23:17 
AnswerRe: SMTP server needed? Pinmembersalysle13-May-07 19:11 
AnswerRe: SMTP server needed? PinmemberShah Noman2-Apr-08 20:42 
GeneralRe: SMTP server needed? PinmemberKees Alderliesten3-Apr-08 13:01 
GeneralNot worked Pinmembergr8aqeel21-Dec-06 22:27 
GeneralRe: Not worked Pinmemberxaml.net13-Jan-07 3:19 
GeneralAttachments don't work without some kind of Server.MapPath Pinmembersma7778-Dec-06 7:52 
GeneralSMTP help PinmemberYamiyahoo6-Dec-06 19:56 
QuestionIs it available to send SMS to China Mobile with your tool? Pinmembercmdsh5-Nov-06 18:38 
QuestionC# version Pinmemberm_cool30722-Oct-06 10:52 
AnswerRe: C# version Pinmemberdarkrd3-Nov-06 18:28 
GeneralRe: C# version Pinmemberrama charan15-Nov-06 22:04 
QuestionWhat's the point of posting a duplicate? PinmemberLuciano Bargmann18-Oct-06 4:19 
AnswerRe: What's the point of posting a duplicate? Pinmembersalysle18-Oct-06 4:23 
GeneralProject and/or Solution Files Pinmembertxdu10-Oct-06 8:17 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141216.1 | Last Updated 4 Oct 2006
Article Copyright 2006 by salysle
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid