I added a Contact Form using the Javax JavaMail API to the File Upload Download Demo App on GitHub. (Screenshots and a description of the Demo App are found in this NixMash post.) You'll find the Contact Form in the "Other Demos" menu, as this seemed like a good place to add demos with the option of more to come.
The technologies we'll be seeing are the Javax JavaMail API, Jersey, and some Mustache. Not covered here, our SMTP Transport Agent on the back end is Exim4. I blogged about configuring Exim in this NixMash post.
Before getting to the code, here are the dependencies we'll need for sending out an email with Javax Mail.
The Controller Method
Here is the Controller Method that receives the Contact Form Submit @POST action and lays out our 3 primary actions:
- Send the contents of our EmailForm DTO on its way with sendContactEmail()
- Based on the response of sending the email we prepare a response to our user
- Return to the Contact Form with the appropriate message
Here's the core of sending an email with the Java Mail API. We created an EmailMessage DTO to hold the various message parts which we use to populate our Javax MailMessage object.
If all goes well our user will see this.
And not this.
Source Code Notes for this Post
Source code discussed in this post is found in my File Upload Download in Bootique Jersey Demo app on GitHub.