Sending mail from a contact form

How to send mail from a contact form without using PHP or CGI scripts nor putting your email address in plain text in the form? Whereas I am a Java carpenter everything looks like a Java nail to me, and I opted for a little Java service to handle the mail sending. My plan was having a plain HTML email form which posts to a URL on my server where my little Java REST service is waiting to forward any incoming mail messages. This way the form can stay simple and the service is the only one who knows about my email address.

the spark service

I have used Spark before, and it seemed fit for the job. Spark is a very easy-to-use framework where a REST or web server is up and running in no time. Once the REST service is running, it waits on its port (default is 4567) for incoming requests, which it will forward to my email address and afterwards redirect the user either to a thank you page or an error page in case things go wrong. The default Java mailing framework is rather over-engineered and scary, so I chose to use Apache Commons Mail instead. The little service was quite easy to put together, you can get it on GitHub if you want.

configuring mail on the server

As it turned out, this was the first time my server was handling email. Setting up mail on a linux machine is pretty easy. Just installing GNU Mailutils, the self-proclaimed swiss army knife of electronic mail handling, does the job:
$ sudo apt-get install mailutils 
In the configuration tool you want to choose "Internet Site" as the setup type. For most other options the defaults are okay and your mail should be ready to go.

setting up lighttpd as a reverse proxy

To hide the forwarding to a different port I set up a reverse proxy to let the Spark service listen to the regular /mail instead of :4567/mail. To let this work in lighttpd the mod_proxy module has to be enabled and a snippet like this added to the config:
$HTTP["url"] =~ "^/mail" { 
        proxy.server = ( 
                "" => ( 
                        "sparkjava" => ( 
                                "host" => "127.0.0.1", 
                                "port" => 4567, 
                                "fix-redirects" => 1 
                        ) 
                ) 
        ) 
} 
Now all the pieces are in place and with an HTML form posting to /mail the picture is complete! On my site the end product looks a bit like this:

contact form


related blogs: