ASP FormMail
ASP FormMail
View the source code for this ASP script.This script takes generic form data and sends it as an email. It is modeled after the widely used FormMail script available at Matt's Script Archive but is written in ASP instead of Perl.
Note that it is not a direct port of Matt's script. While it has similar functionality it does not attempt to emulate every feature of that script.
It has support for four of the most widely used email components available and can be easily modified to support others. The email produced uses simple HTML formatting which most email clients can support.
Here's a sample, enter your own email address to receive the results.
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".
Like Matt's version, 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 (','). or |
_replyTo | An email address that will be used in the Reply-To header of the email. |
_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.
|
| Specifies the text to use in the email subject line. |
_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. |
_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. |
_envars | A comma-deliminated list of environment variable names. These can be any of the fields available in the Request.ServerVariables collection. |
_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. |
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
View the source code for this ASP 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.
Coding Details
The script is fairly simple with four basic steps.
- Check the request to ensure a valid form submission.
- Process any control form fields passed.
- If no errors occured in the previous steps, create and send the email.
- 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
View the source code for this ASP script.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 = "
| " & name & ": | " _" & Request.Form(name) & " | " _
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, ",")
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.
" & vbCrLf _ & "
| " & name & ": | " _ & "" & Request.ServerVariables(name) & " | " _ & "
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.
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.
end function %>
Note that it also ignores any fields whose name begins with an underscore character, so control fields are not included.
No comments:
Post a Comment