Sending Form Results by Email

By Michael Moncur (October 13, 2003)

One question I am frequently asked is how to send form results by email using only HTML or JavaScript. This is not an easy question, since the standard methods of doing so are poorly supported by browsers. Read on for the best answers I've found.

The Code

The ACTION attribute of a <form> tag tells the browser where to send the data from the form. While the value of this attribute is usually the URL of a CGI script, you can also use a mailto: URL to send the results by email. The following <form> tag demonstrates this:

<form action=mailto:your@email.address method="POST" 
enctype="text/plain">

This <form> tag includes the following key attributes:

  • The action attribute specifies the mailto method. Make sure you include the correct email address.
  • The method attribute is set to POST. The default GET method can't pass enough data for some forms.
  • The enctype attribute ensures that the mail will be sent in plain-text format.

The Problem

The trouble with using this method to send form results is that it is highly dependent on the browser in use and the email client in use. In particular, some of the most popular versions of Internet Explorer will not work correctly. With all of the browser troubles, you're likely to lose about half of your readers' messages.

The Solution

It's simple: Don't use JavaScript and HTML to do a Web server's job. Use a server-side script in Perl, PHP, or another language to send the mail and it will work 100% of the time. You don't even have to write one - many are available for free.

One of the most popular scripts is formmail.pl, written in Perl. However, some versions of formmail have major security holes and have been exploited by spammers. Use only the following fixed versions from their official source:

For PHP, you can write your own form-to-email program easily or use one of the many available for free:

You can also use many remotely-hosted services to send your form results without any code on your own server. There is a list of these services here:

Conclusion

As one of the most commonly-needed features, it's a shame this particular aspect of HTML forms hasn't been standardized or well supported by browser makers. But even if current browsers improve, your best bet for a reliable email gateway is to use a server-side approach.

Good luck!

Note: This article first appeared at The JavaScript Workshop. This is a revised version.