Creating a JavaWeb Email Contact Form

In a previous tutorial I have explained how to create a new NetBeans project and add a library to it to make the classes that are available in a jar available to use in your own project. If you are unsure how to do this go ahead and check out this article.

In this tutorial I’m going to explain how to create a contact form with a jQuery validation template for you to play with that will send an email to whomever. The end result should look like this:

form

Source

Your going to need some form of access to an smtp mailbox with a username and password. You can use your gmail account info if you like, all your going to need is your gmail address and password.
gmail

Now for the fun part, First of all you need to set up a new web application project in netBeans I’ve called mine ContactForm. In the index.jsp file in the root of your directory you should past this html structure. It’s going to set up the form. Simple elegant yet expandable if you want. You’ll see how easy it is to build custom emails with this form by adding new fields and manipulating a variable or two near the end of this tutorial.

<%@page import="mail.SendEmail" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >
        <link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.7.0/build/reset/reset-min.css">
        <link href="assets/css/style.css" rel="stylesheet" type="text/css" media="screen" >
        <title>Multilingual Contact Form</title>
    </head>
    <body>
        <div id="container">
            <p class="heading">Contact Form</p>
            <form action="index.jsp" method="POST">
                <div class="input">
                    <label for="fullname">Name:</label>
                    <input type="text" id="fullname" name="fullname" value="" />
                    <div id="fullname_warn" ></div>
                </div>

                <div class="input">
                    <label for="email" >Email:</label>
                    <input type="text" id="email" name="email" value="" />
                    <span id="email_warn" ></span>
                </div>

                <div class="input">
                    <label for="message" >Message:</label>
                    <textarea cols="10" rows="5" id="message" name="message"></textarea>
                </div>

                <input type="submit" name="send" value="send" id="send" />
            </form>

            <%
        if (request.getParameter("fullname") != null) {
            String fullname = request.getParameter("fullname");
            String email = request.getParameter("email");
            String message = request.getParameter("message");

            if (mail.SendEmail.run(email, fullname, message)) {
            %>
            <p class="goodtogo end">Mail Sent Successfully</p>
            <%} else {%>
            <p class="warning end">Error Sending Mail</p>
            <%}
        }
            %>

        </div>
        <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
        <script type="text/javascript" src="assets/js/jscript.js"></script>
    </body>
</html>

Now that the html structure is in place it’s time to transform it into something a little easier on the eye. We’re going to add some styles. Before you go ahead and do this you should go ahead and set up your folder structures. It’s imperative that you have your files arranged in an organized way so that other developers can easily find what their looking. That, and if you need to take pictures to remember a holiday then you should defiantly be making your documents easier to find. Your folder structure should look like this:
folderstructure

Now that youve got somewhere to put your styles you should go ahead and stick them in this folder. Here they are:

div#container{
    max-width:578px;
    min-width:440px;
    border:1px solid #222;
    padding:20px;
    margin:100px auto;
    color:#222233;
    font-family:sans-serif;
    -moz-border-radius:20px;
}

p.heading{
    font-size:36px;
    font-weight:bold;
}

.input,#send{
    font-size:24px;
    margin-top:10px;
}

.input label{
    display:block;
    text-decoration:underline;
}

.input input, .input textarea{
    width:300px;
    padding:1px;
}

#send{
    font-size:16px;
    cursor:pointer;
    width:120px;
    height:50px;
}

.warning, .goodtogo{
    font-size:20px;
    padding-left:35px;
    width:225px;
    height:33px;
    float:right;
    clear:right;

}

.warning{
    background:transparent url(../img/warn.png) no-repeat -5px -33px scroll;
}

.goodtogo{
    background:transparent url(../img/warn.png) no-repeat 0px 0px scroll;
}

.end{
    position:relative;
    top:-40px;
}

Now you need a sprite for your error icons. I’ve made this one you should stick it in the ‘img’ folder your created under ‘assets’ like the structure shown above.
warn

The following demonstrates dynamic class application with JQuery. You should play around with this fill and add validation to the form fields while getting familiar with the JQuery framework:

$(document).ready(function() {

    var fullname = $('#fullname');
    var fullname_warn = $('#fullname_warn');

    var email = $('#email');
    var email_warn = $('#email_warn');

    fullname.focus(function(){
        fullname_warn.removeClass('goodtogo');
        fullname_warn.addClass('warning');
        fullname_warn.html("Cannot be blank");

        fullname.blur(function(){
            fullname_warn.removeClass('warning');
            fullname_warn.addClass('goodtogo');
            fullname_warn.html(" ");
        });
    });

    email.focus(function(){
        email_warn.removeClass('goodtogo');
        email_warn.addClass('warning');
        email_warn.html("Cannot be blank");

        email.blur(function(){
            email_warn.removeClass('warning');
            email_warn.addClass('goodtogo');
            email_warn.html(" ");
        });
    });

});

Now that we have a base structure in place it’s time to start bringing in the JavaMail API into your project. Ive made it available to download here so you can just download it. Ok? Create a JavaMail library and add it to your project as in the iText tutorial.

So the final step in this is easy… Create a new package called ‘mail’ in your Source Packages roll out in your project folder structure as seen here:
javaClassStructure

As you can see from above a new Java Class file called SendMail has been added to the ‘mail’ package, create that file now and add this code to it:

package mail;

/**
 *
 * @author Siriquelle
 */
import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 *
 * @author Siriquelle
 */
public class SendEmail {

    public static boolean run(String addressedTo, String subject, String content) {

        String fromAddress = "Your Name ";//Your Email Address//
        String recipients = addressedTo.trim();
        String contentType = "text/plain";

        String smtpHost = "smtp.gmail.com";//Your Outgoing Mailbox//
        int smtpPort = 587;
        String username = "you@gmail.com";//Your Mailbox Username//
        String password = "yourpassword";//Your Mailbox Password//

        try
        {
            Properties props = System.getProperties();
            props.put("mail.smtp.starttls.enable", "true");
            Session session = Session.getDefaultInstance(props);

            MimeMessage message = new MimeMessage(session);

            message.setFrom(new InternetAddress(fromAddress));
            message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse(recipients, false));

            message.setSubject(subject);
            message.setContent(content, contentType);
            message.setSentDate(new Date());

            Transport transport = session.getTransport("smtp");
            transport.connect(smtpHost, smtpPort, username, password);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();

            return true;
        } catch (MessagingException messagingException)
        {
            System.out.print(messagingException);
            return false;

        } catch (Exception e)
        {
            System.out.print(e);
            return false;
        }
    }
}

And that is it. You should now have a valid working form that will send emails. Nice. If you don’t check that your folder structure matches mine. Check that you’ve added your own GMail username and password in the SendEmail java class.

4 comments

  1. Hi there, relly liked your post, i think it will be a great help for me since i’m starting to learn JSP and HTML, i’m still a bit noob however. So what i would like to know is this: I created a web site in HTML and i would like to call your JSP form inside a DIV tag is it possible?

    Thanks!

Comments are closed.