-->
Bookmark and Share

ASP FormMail

View the source code for this ASP script.

Subroutines and Functions

The code shown so far includes call to some subroutines and functions which are defined at the end of the script. These are described next.

GetHost() takes a URL (from the HTTP_REFERER header) and parses out the host name. For example, GetHost("http://www.example.net/about/contact.html) would return "www.example.net".

AddErrorMsg() is used to store error messages generated within the main code in a simple array, so they can easily be listed on the output page.

InList() is used to check for a given string in the allowedHosts, allowedRecipients and allowedEnvars arrays.

IsValidEmailAddress() is used to validate email addresses. It basically checks for the proper format (username@domain) and checks that only valid characters are used.

FormFieldList() was discussed earlier. It simply creates an array of all the form field names found in the submission, ignoring the control fields (which all begin with an underscore).

SendMail() is the critical one. It contains code for sending an email using any of four common email components. Which one is used depends on the value set for mailComp.

Looking at the code, you'll see that all four share a similar pattern. Here's the code used for the ASPMail component:

  'Send email (ASPMail version).
  if mailComp = "ASPMail" then
    set mailObj = Server.CreateObject("SMTPsvg.Mailer")
    mailObj.RemoteHost  = smtpServer
    mailObj.FromAddress = fromAddr
    for each addr in Split(recipients, ",")
      mailObj.AddRecipient "", Trim(addr)
    next
    if ccToAddr <> "" then
      mailObj.ReplyTo = Trim(ccToAddr)
      mailObj.AddCC "", Trim(ccToAddr)
    elseif replyToAddr <> "" then
      mailObj.ReplyTo = Trim(replyToAddr)
    end if
    mailObj.Subject = subject
    mailObj.ContentType = "text/html"
    mailObj.BodyText = body
    if not mailObj.SendMail then
      SendMail = "Email send failed: " & mailObj.Response & "."
    end if
    exit function
  end if

First, a mail object is created. Then various fields are set, such as the name of the SMTP server, the to- and from- email addresses, the subject line, etc. Finally, the email is sent and any error message generated by the component is returned.

As stated before, you may need to modify this code based on what your own web host provides. Some hosts may require a user ID and password for access to the SMTP server, or may use an email component not supported by the script. Your hosting provider should be able to supply you with a sample of the necessary code which you can use in this function.

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.