Howto send E-mail from an ASP page

This article will show you how simple it can be to send an e-mail from an ASP page. With just a few lines of code, you can add mail sending capabilities to your ASP page in your Web site. Notice that I put the focus on can be; depending on your network setup, this approach may be very easy, or it may require you to setup or configure your network for this code to work. See the reference section at the end of this document for more information.

There are basically two ways to send an e-mail from your Web page: either from the client, or from the server. The client side method (using mailto: in either a <a href> tag or in a <form> tag) has quite a lot of disadvantages: first of all, it requires a working e-mail application at the client. Second, and more importantly, it requires your user to actually confirm and send the message themselves.

So, in most real-world applications, sending an e-mail from server side code is the way to go. Fortunately, sending e-mail from an ASP page is not that difficult. This article discusses two ways to send the e-mail: using the CDONTS.NewMail object and using the CDO.Message object. The first solution will work on most modern Windows installations (2000 and up), but it requires a local SMTP Server (running on the same machine that server the ASP pages) to relay the message. The second solution uses a remote SMTP server so there is no need for a local SMTP Server. However, you'll need to have the Collaboration Data Objects for Microsoft Windows 2000 or for Microsoft Exchange installed. These objects come with recent Microsoft Office installations (2000 and up, as far as I know. You usually find this option under Microsoft Outlook) and other Microsoft products. This solution can therefore also run on platforms that don't support a local SMTP Server, like Windows XP Home Edition.

Using CDONTS.NewMail to Send, uh, New Mail

As I said before, using the CDONTS.NewMail object requires you to have a local SMTP Server installed. This server comes with IIS so there is a good chance you have it already up and running. (As of Windows Server 2003, the SMTP Server is no longer installed by default). The reference section at the end of this article contains a link to a Microsoft article detailing the setup procedure for the SMTP Server.

Once you have the SMTP Server up and running, it's time to code. With the next 4 steps, I'll show you how to create an HTML form that allows a user to enter their name and a personal message. On the click of a button, the form will be submitted to the server and the form's contents are e-mailed to an e-mail address you specify.

  1. Create a new ASP page and call it SendMail.asp. If you're not using an advanced IDE, like Dreamweaver MX, but Notepad for example, add the default tags that are required for an HTML page, like the <html>, <head> and <body> tags.
  2. Between the <body> tags, add the following code:

    <body>
      <form id="frmSendEmail" method="post" action="SendMail.asp">
           Your name: <input type="text" name="txtName" id="txtName" /><br />
            Your message: <textarea name="txtMessage" id="txtMessage" cols="40" 
                rows="10"></textarea><br />
        <input type="submit" name="btnSubmit" id="btnSubmit" 
              value="Send Message" />
      </form>
    
    </body>

  3. At the top of your page, right before the opening <html> tag, add this ASP code:

    <%
      If Request.Form("btnSubmit") <> "" Then
        Dim UserName
        Dim UserMessage
        UserName = Request.Form("txtName")
        UserMessage = Request.Form("txtMessage")
             
        Dim Message
        Message = "Mail from the Web site" & vbCrlf & vbCrLf
        Message = Message & "User " & UserName & _
                  " left the following message: " & vbCrLf
        Message = Message & UserMessage & vbCrLf & vbCrLf
         
        Dim oMessage
        Set oMessage = Server.CreateObject("CDONTS.NewMail")
          
        Const CdoBodyFormatHTML = 0 ' Send HTML Mail 
        Const CdoBodyFormatText = 1 ' Send Text Mail
          
        Const CdoMailFormatMime = 0 ' Send mail in MIME format.
        Const CdoMailFormatText = 1 ' Send mail in uninterrupted
                                    ' plain text (default value).      
            
        With oMessage
          .To = "You@YourProvider.Com"
          .Bcc = "SomeoneElse@YourProvider.Com"
          .From = "YourWebsite@YourProvider.Com"
          .Subject = "User " & UserName & " left a message"
          .BodyFormat = CdoBodyFormatText ' CdoBodyFormatHTML
          .MailFormat = CdoMailFormatMime ' CdoMailFormatText
          .Body = Message
          .Send
        End with
        Set oMessage = Nothing
          
        Response.Redirect("ThankYou.asp")
      End If     
    %>
    <html>

  4. That's all there is to it. Save the page, and request it in your browser. Type your name and a message and then hit the Send Message button. If everything worked as planned, you'll receive an e-mail with your name and the message you typed in.

How It Works

Once the form has been submitted to the server, the values for the user's name and message are stored in two variables. Then a new object of type CDONTS.NewMail is created. For this object to work properly, you need to se t a few properties, like the To field, the Subject and the Body. In this example, I also set a BCC field. Note that you should change the e-mail addresses in the code to valid addresses. I highlighted the areas you need to change. When the message object is created, it can be send with (take a wild guess....) the Send method.

For this example, I have set the BodyFormat to CdoBodyFormatText. This will send the e-mail as plain text. With plain text, you need the ASP (VBScript) constant vbCrLf to add a line break to your message. If you have set the BodyFormat to CdoBodyFormatHTML you can use HTML to format your message. You can use the <br / > tag for a line break, but you can also add headings, links and even form elements.

The Send method tries to send the message to a local SMTP server. If it can't find one, the code will fail. Once the message has been sent successfully, the user is redirected to a ThankYou page where you can express your eternal thanks (and display a few of your revenue-generating banner ads along the way).

Using the Collaboration Data Objects to Send E-mail

Sending e-mail with the Collaboration Data Objects is pretty similar. Once you have installed the Collaboration Data Objects, you're ready to send e-mail from your ASP page. Note that the first two steps are exactly the same as in the previous solution. This is just an easy way to make this article look much more impressive than it really is. You can even print it out and drop it somewhere on your desk to impress your colleagues. Anyway, back to business. Follow the next 4 steps to add e-mailing capabilities to your ASP page:

  1. Create a new ASP page and call it SendMail.asp. If you're not using an advanced IDE, like Dreamweaver MX, but Notepad for example, add the default tags that are required for an HTML page, like the <html>, <head> and <body> tags.
  2. Between the <body> tags, add the following code:

    <body> 
      <form id="frmSendEmail" method="post" action="SendMail.asp">
        Your name: <input type="text" name="txtName" id="txtName" /><br/>
        Your message: <textarea name="txtMessage" id="txtMessage" 
                        cols="40" rows="10"></textarea><br/>
        <input type="submit" name="btnSubmit" id="btnSubmit"
                           value="Send Message" />
      </form>
    </body>
  3. At the top of your page, right before the opening <html> tag, add the following ASP code. The code comes pretty much directly from the Microsoft MSDN site. You'll find a link to the original article in the References section at the end of this article.

    <%
      If Request.Form("btnSubmit") <> "" Then
        Dim UserName 
        Dim UserMessage
        UserName = Request.Form("txtName")
        UserMessage = Request.Form("txtMessage")
        Dim Message
        Message = "Mail from the Web site" & vbCrlf & vbCrLf
        Message = Message & "User " & UserName & _
              " left the following message: " & vbCrLf
        Message = Message & UserMessage & vbCrLf & vbCrLf
       Const cdoSendUsingPort = 2
        
        Dim oConfiguration
        Dim oMessage
        Dim oFields
        Set oMessage = CreateObject("CDO.Message")
        Set oConfiguration = CreateObject("CDO.Configuration")
    
        Set oFields = oConfiguration.Fields
        ' Set the CDOSYS configuration fields to use port
        '   25 on the SMTP server.
        With oFields
          .Item("http://schemas.microsoft.com/cdo/configuration/sendusing") _
              = cdoSendUsingPort
          .Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") _
              = "smtp.YourProvider.Com" 
          .Item("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") _
              = 10 
          .Update
        End With
      
        ' Apply the settings to the message.
        With oMessage
          Set .Configuration = oConfiguration
          .To = "You@YourProvider.Com"
          .Bcc = "SomeoneElse@YourProvider.Com"
          .From = "YourWebsite@YourProvider.Com"
          .Subject = "User " & UserName & " left a message"
          .HTMLBody = Message
          .Send
        End With
      
        ' Clean up variables.
        Set oMessage = Nothing
        Set oConfiguration = Nothing
        Set oFields = Nothing
      
        Response.Redirect("ThankYou.asp")
      End If
    %>
    <html>

  4. Again, that's all there is to it. Save the page, and request it in your browser. Type your name and a message and then hit the Send Message button. If everything worked as planned, you'll receive an e-mail with your name and the message you typed in.

How It Works

Just as with the previous example, the form's contents are retrieved and stored in variables. Instead of the CDONTS.NewMail object, an object of type CDO.Message is constructed. This object has a Configuration property that allows you to change stuff like the SMTP Server that will send the e-mail message for you. In this example, I have set the SMTP Server to SMTP.YourProvider.Com. Obviously, you need to change it to the name of your SMTP Server.

The rest of the code is very similar to the example with the CDONTS.NewMail object: the To, BCC and From addresses are set (again, make sure you change them to more reasonable addresses). Also, the Subject and the Body are set. The Send method will deliver the message to the SMTP Server you specified in the configuration fields. This SMTP Server will then take care of sending the message to your recipient(s).

Summary

Sending e-mail from ASP pages is pretty easy. Once you have your network setup and configured correctly, you do not need much code to send an e-mail. This article has shown you two ways to send the e-mail; using CDONTS and using the Collaboration Data Objects. Which methods works best for you depends on your network setup. If you have an SMTP Server installed on the machine running your ASP pages, you can use the CDONTS method, otherwise you need to use the Collaboration Data Objects solution.

References

Download Files


Where to Next?

Wonder where to go next? You can post a comment on this article.

Doc ID 249
Full URL https://imar.spaanjaars.com/249/howto-send-e-mail-from-an-asp-page
Short cut https://imar.spaanjaars.com/249/
Written by Imar Spaanjaars
Date Posted 02/18/2004 21:50
Date Last Updated 11/04/2020 10:57
Date Last Reviewed 02/19/2005 14:58

Comments

Talk Back! Comment on Imar.Spaanjaars.Com

I am interested in what you have to say about this article. Feel free to post any comments, remarks or questions you may have about this article. The Talk Back feature is not meant for technical questions that are not directly related to this article. So, a post like "Hey, can you tell me how I can upload files to a MySQL database in PHP?" is likely to be removed. Also spam and unrealistic job offers will be deleted immediately.

When you post a comment, you have to provide your name and the comment. Your e-mail address is optional and you only need to provide it if you want me to contact you. It will not be displayed along with your comment. I got sick and tired of the comment spam I was receiving, so I have protected this page with a simple calculation exercise. This means that if you want to leave a comment, you'll need to complete the calculation before you hit the Post Comment button.

If you want to object to a comment made by another visitor, be sure to contact me and I'll look into it ASAP. Don't forget to mention the page link, or the Doc ID of the document.

(Plain text only; no HTML or code that looks like HTML or XML. In other words, don't use < and >. Also no links allowed.