ASP Hosting Top Header
Easy ASP Hosting Logo ASP.NET Hosting   Toll Free: (800) 579-1657
ASP Hosting Contact Information
Windows Hosting
         Home         Hosting         Domains         Support          Order Windows 2003 Hosting
Helm Hosting
 

Generic ASP Form Mailer Post Sample

This is a generic ASP Form Mail sample that can be used to email ALL posted form data to one or more email addresses.

The following is a working sample of how this component works on EasyASP hosting accounts. There are literally thousands of other combinations, colors, methods, etc that could be used to accomplish the same function. Please note that we do not provide support for this sample. It is only provided as a guide to help you get started.

All the ASP code is documented. What is not documented is the plain HTML tables which were added for aesthetic purposes.

Please note: When using any ASP Mail COM Objects, you must use the specific internal email IP address assigned to that server and "2525" as the port number. We configure SMTP on a non-routable, internal IP with an odd port number so that people can send email through ASP scripts, without having to deal with SMTP authentication issues. You can find out what IP address you should be using by clicking here.


Keep in mind that this script will require some customization in order to work on any particular site. You may also wish to alter it to suit your needs better, such as by reformatting the output or adding new options.

Setting Up the Form

Just about any new or existing form can use the script by setting its ACTION attribute to the URL where the script resides and making sure its METHOD is set to "POST".

<form action="/scripts/formmail.asp" method="post">
<p>
<input name="_recipients" type="hidden" value="support@example.net" />
<input name="_requiredFields" type="hidden"
  value="Name,Customer ID,Email,Comments" />
Name: <input name="Name" type="text" /><br />
Customer ID: <input name="Customer ID" type="text" /><br />
Email Address: <input name="Email" type="text" /><br />
Comments:<br />
<textarea name="Comments" rows=5 cols=50></textarea>
<input type="submit" value="Submit" />
<input type="reset" value="Clear" />
</p>
</form>

Like other versions, this one uses specially named form fields as parameters for controlling the processing. These can be added to the form as hidden fields.

Control Fields

Below is a listing of these fields. Note that all begin with an underscore ('_') character to distinguish them from any other form fields. Any field name that begins with an underscore is not displayed in the resulting email.

FormMail Control Fields
Field Name Description
_recipients Required The email address to send the form to. Multiple recipients can be specified by separating addresses with commas (',').
<input name="_recipients" type="hidden"
value="admin@example.net" />
or
<input name="_recipients" type="hidden"
value="sales@invalid.com,orders@invalid.com" />
_replyTo An email address that will be used in the Reply-To header of the email.
<input name="_replyTo" type="hidden"
value="guest@example.org" />
_replyToField Like _replyTo except that you specify the name of another field on the form. Generally, you'd use the name of a field that asks for the user's email address. Then, the email would have a Reply-To header set to that address making replies easy.
<input name="_replyToField" type="hidden"
value="Email Address" />
...
Your email address: <input name="Email Address"
type="text" size="40" />
_subject Specifies the text to use in the email subject line.
<input name="_subject" type="hidden"
value="Site Feedback" />
_requiredFields A comma-deliminated list of field names that should be checked for a value. Any missing values causes an error message to be displayed and the form will not be submitted.
<input name="_requiredFields" type="hidden"
value="Name,Address,City,State,Zip,Email" />
_fieldOrder A comma-deliminated list of field names. When building the email, the fields and values will be displayed in the order specified here. Note that if you use this option, you must specify the names for all form fields you want sent.
<input name="_fieldOrder" type="hidden"
value="Name,Email,Phone,Address,City,State,Zip" />
_envars A comma-deliminated list of environment variable names. These can be any of the fields available in the Request.ServerVariables collection.
<input name="_envars" type="hidden"
value="HTTP_REFERER,HTTP_USER_AGENT,REMOTE_ADDR" />
_redirect Normally when the form has been submitted and the email sent without any errors the script will display a thank you message along with the form data. You can change this by specifying the URL of another page in this field and the user will be sent there instead.
<input name="_redirect" type="hidden"
value="termsofservice.html" />

You should note that FILE input types are not supported by the script as ASP has no built-in methods for easily dealing with files uploaded from forms.

Before the script can be used, some customization is needed. Much of this depends on the script's location and host environment.


Setting Up the Script

In order for the ASP script to work, some configuration variables need to be set. These are defined at the beginning of the code and determine what sites can use the script and how it will set up and send the email.

Script Parameters

Here is a view of the code with some typical values. The parameters are described in detail below.

referers   = Array("www.example.net","example.net")
mailComp   = "ASPMail"
smtpServer = "mail.example.net"
fromAddr   = "guest@example.net"
FormMail Configuration Variables
Variable Name Description
referers An array of web host addresses. This is used to prevent other sites from posting forms to your host. Basically, it should match what's in your website address between the "http://" and the next "/" character.

An array value is used so that you can include variations, such as "www.example.net" and "example.net" if your site can be accessed that way. You can even include IP addresses.

Note: A browser or firewall may be configured to block the referer header on HTTP requests. This means that some users will not be able to use the form. You can leave the array empty:

referers = Array()

to make the script skip this check.
mailComp Must be set to one of "ASPMail", "CDONTS", "CDOSYS" or "JMail". These are the four email components that the script recognizes and can use for sending email.

If your web host does not support any of these, you will need to add your own coding to use whatever is available to you.
smtpServer The hostname of your SMTP server. This is required for all the supported email components except CDONTS.
fromAddr This email address will be used as the sender address for the email created by the script.

Most web hosts do not allow email to be sent from their systems without a valid From address in order to discourage spamming. In any case, you should always use a valid email address for your own site.

The referers list is meant simply for your protection. The script checks the URL of the incoming form against the values you've set in this variable and rejects any that don't match.

Otherwise, anyone from anywhere could set up a form on their own site, point it to your script and start sending email from your host without your consent.

Email Components

The remaining configuration variables relate to the component used to send email. The script has been designed to work with four of the most common ASP email components available and to provide an easy way to set the parameters they generally require.

If your host does not use one of these, you'll need to modify the script to add support for your particular situation. You should check with your host administrator or technical support personnel to find out what is supported on your site and the correct parameters needed to use it.

For more information on the supported email components, visit the vendor sites: ServerObjects (ASPMail), Microsoft (CDONTS and CDOSYS), and Dimac (JMail).

Coding Details

The script is fairly simple with four basic steps.

  1. Check the request to ensure a valid form submission.
  2. Process any control form fields passed.
  3. If no errors occured in the previous steps, create and send the email.
  4. Produce an output page displaying either errors or the data that was emailed.

Note that the script does not necessarily stop processing when an error occurs. Instead, error messages are stored in a global array and processing continues where possible. Then all the error messages can be displayed on the final step.

The details for each step are discussed below.

Checking for a Valid Form Submission

The script first checks for form data in the request, no data means that there is nothing to process. Then it checks the referering URL, parsing out the host name and looking for a match in the referers array.

<% 'Check for form data.

   if Request.ServerVariables("Content_Length") = 0 then
     call AddErrorMsg("No form data submitted.")
   end if

   'Check if referer is allowed.

   validReferer = false
   referer = GetHost(Request.ServerVariables("HTTP_REFERER"))
   for each host in referers
     if host = referer then
       validReferer = true
     end if
   next
   if not validReferer then
     if referer = "" then
       call AddErrorMsg("No referer.")
     else
       call AddErrorMsg("Invalid referer: '" & referer & "'.")
     end if
   end if

   'Check for the recipients field.

   if Request.Form("_recipients") = "" then
     call AddErrorMsg("Missing email recipient.")
   end if %>

The HTTP_REFERER environment variable contains the URL of the form that submitted the request. This is passed to the GetHost() function which parses out the host name, i.e. the characters between the the beginning "http://" (or "https://") and the next "/" character.

The script then looks in the referers list for a match. Any requests from an unauthorized host name generates an error message. If a match is found, the validReferer flag is set to True.

The final check is for the _recipients field, which is the only required control field. If no recipient was supplied, an error message will be given.


Parsing Multiple Values

All the email addresses in the _recipients field are validated using a function called IsValidEmailAddress() which checks that an address follows proper format. Any invalid address results in an error.

It's useful to note how the script separates individual email addresses of this field, as the same technique is used in other control fields that allow multiple values.

<% 'Check all recipient email addresses.

   recipients = Split(Request.Form("_recipients"), ",")
   for each name in recipients
     name = Trim(name)
     if not IsValidEmailAddress(name) then
       call AddErrorMsg("Invalid email address in " _
         & "recipient list: " name & ".")
     end if
   next
   recipients = Join(recipients, ",") %>

The built-in VBScript function Split() is used to break the input string up using the comma (',') character as the delimiter. It returns the individual email addresses as an array, even if only one was given.

Looping through these, it first trims any leading or trailing whitespace from the individual string and then makes the validation check.

Finally, the complimentary Join() function is used to put the individual addresses back into a single string, again separated by commas. They are rejoined for this particular field because almost all email components accept multiple addresses in this format. It allows the same email to be sent to multiple recipients with a single send call.

Processing the Optional Control Fields

The script then checks for the optional control fields. For _replyTo and _subject it merely saves the value for use when sending the email.

The _replyToField works a little differently. Its value is taken to be the name of another field present in the form data. The script takes the value of this other field to be used as the Reply-To address.

<% 'Get replyTo email address from specified field, if given, and
   'check it.

   name = Trim(Request.Form("_replyToField"))
   if name <> "" then
     replyTo = Request.Form(name)
   else
     replyTo = Request.Form("_replyTo")
   end if
   if replyTo <> "" then
     if not IsValidEmailAddress(replyTo) then
       call AddErrorMsg("Invalid email address in " _
         & "reply-to field: " & replyTo & ".")
     end if
   end if %gt;

Again, since this is an email address, the IsValidEmailAddress() function is used to ensure the address format is correct.

Like the _recipients control field, _requiredFields may have contain multiple values separated by commas. It too is first broken up into individual values. Each value is used like the _replyToField value, its value is taken as the name of another field which the script looks for in the form data.

<% 'If required fields are specified, check for them.

   if Request.Form("_requiredFields") <> "" then
     required = Split(Request.Form("_requiredFields"), ",")
     for each name in required
       name = Trim(name)
       if Left(name, 1) <> "_" and Request.Form(name) = "" then
       call AddErrorMsg("Missing value for " & name)
       end if
     next
   end if %gt;

If any of these specified fields has a null string value, an error message is generated.

The _fieldOrder control field is also parsed in this manner, except that the resulting array of field names is not checked, merely saved for use later.

Building the Email Message

Once these control fields have been processed, and no errors have occured, the script then contructs body of the email note, using HTML formatting.

<% 'Build table of form fields and values.

   body = "<table border=""0"" cellpadding=""2""" _
        & cellspacing=""0"">" & vbCrLf
   for each name in fieldOrder
     body = body _
          & "<tr valign=""top"">" _
          & "<td><b>" & name & ":</b></td>" _
          & "<td>" & Request.Form(name) & "</td>" _
          & "</tr>" & vbCrLf
   next
   body = body & "</table>" & vbCrLf %>

The fieldOrder array is simply an array of field names. It is built using the _fieldOrder control, when supplied, or using a function called FormFieldList().

This function corrects a small problem with VBScript. While it's possible to simply loop through all the form fields using a statement like...

<% for each name in Request.Form
     ...
   next %>

VBScript doesn't guarantee that the field names will be given in the same order as they appear in the form request sent by the browser.

To ensure that the fields are listed in the order received, the FormFieldList() function is used to generate the names in an array in the proper order. Here's the code.

<% function FormFieldList()

     dim str, i, name

     'Build an array of form field names ordered as they
     'were received.

     str = ""
     for i = 1 to Request.Form.Count
       for each name in Request.Form
         if Left(name, 1) <> "_" and _
            Request.Form(name) is Request.Form(i) then
           if str <> "" then
             str = str & ","
           end if
           str = str & name
           exit for
         end if
       next
     next
     FormFieldList = Split(str, ",")

   end function %>

Note that it also ignores any fields whose name begins with an underscore character, so control fields are not included.


If any environment variables were requests via the _envars control field, the script appends another listing to the email message body for them.

The code is similar to that used to list form fields from the Request.Form collection. An array of names is derived from the list of environment variables given and used against the Request.ServerVariables collection.

<% 'Add a table for any requested environmental variables.

   if Request.Form("_envars") <> "" then
     body = body _
          & "<p>&nbsp;</p>" & vbCrLf _
          & "<table border=""0"" cellpadding=""2""" _
          & "cellspacing=""0"">" & vbCrLf
     envars = Split(Request.Form("_envars"), ",")
     for each name in envars
       name = Trim(name)
       body = body _
            & "<tr valign=""top"">" _
            & "<td><b>" & name & ":</b></td>" _
            & "<td>" & Request.ServerVariables(name) & "</td>" _
            & "</tr>" & vbCrLf
     next
     body = body & "</table>" & vbCrLf
   end if %>

Sending the Email

The SendMail() function handles the task of creating the proper email object, setting the proper parameters and sending it.

As noted before, the script supports four different email components, and more can be added. The mailComp setting is used in a series of if statements to decide which code to use. Here's the code for the CDONTS component that's supplied with Microsoft's IIS web server.

<% if mailComp = "CDONTS" then
     set mailObj = Server.CreateObject("CDONTS.NewMail")
     mailObj.BodyFormat = 0
     mailObj.MailFormat = 0
     mailObj.From = fromAddr
     mailObj.Value("Reply-To") = replyTo
     mailObj.To = recipients
     mailObj.Subject = subject
     mailObj.Body = body
     mailObj.Send
     set mailObj = Nothing
     exit function
   end if %>

The values for the variables recipients, subject, fromAddr, etc. have all been set at this point from processing the control fields set in the configuration variables.

CDONTS doesn't provide any return values or error checking on the send call but other components do. For these the function returns any error message or code provided. For example, this code is used when ASPMail is specified.

<% if mailComp = "ASPMail" then
     ...
     if not mailObj.SendMail then
       SendMail = "Email send failed: " & mailObj.Response & "."
     end if
     exit function
   end if %>

Displaying an Output Page

The last step is to create some form of output page. If any errors occured, the script prints out all the error messages collected. If a _redirect field was given, the script will redirect to the supplied URL.

Otherwise, it displays a simple "Thank you" message along with body of the email sent. Since the email message was formatted in HTML, the same string value can be used in the page display.

Conclusion

Although the script allows for some input validation, many online forms will require much more stringent checks. But it does serve well for generic purposes and the basic processing flow can easily be expanded to accomodate more complex data validation and processing requirements.

 

Home |  Hosting |  Resellers |  About Us |  Testimonials |  Site Map |  Contact Us |  Data Center |  Helm |  Support |  Announcements |  Order