Contact Form Using JavaMail JSP

In this article let us see about how to develop a contact form using Java, JavaMail API and JSP. The example we are going to develop will be a responsive form and can be tested using Google GMail SMTP.

We have earlier learnt about how to send email using Java with Gmail SMTP and JavaMail API. We will use the email sending part from that article. If you are interested in learning about how to receive email using Java refer the linked tutorial.

This example program has a JSP and a Java class. The JSP is the front-end as well it has scriplet which processes the post data and invokes the mail sending class. This scriplet can be move moved to a servlet class and done in doPost.

Java-contact-form

Contact Form JSP

Following is the JSP code for the contact form. It has a stylesheet included and the form is designed to be responsive.

<%@ page import="com.javapapers.java.mail.JavaEmail"%>
<%@ page import="javax.mail.MessagingException;"%>
<%
	String message = null;
	String status = null;
	if (request.getParameter("submit") != null) {
		JavaEmail javaEmail = new JavaEmail();
		javaEmail.setMailServerProperties();
		String emailSubject = "Contact Form using Java JSP GMail";
		String emailBody = "";
		if (request.getParameter("name") != null) {
			emailBody = "Sender Name: " + request.getParameter("name")
					+ "<br>";
		}
		if (request.getParameter("email") != null) {
			emailBody = emailBody + "Sender Email: "
					+ request.getParameter("email") + "<br>";
		}
		if (request.getParameter("phone") != null) {
			emailBody = emailBody + "Sender Phone: "
					+ request.getParameter("phone") + "<br>";
		}
		if (request.getParameter("message") != null) {
			emailBody = emailBody + "Message: " + request.getParameter("message")
					+ "<br>";
		}
		javaEmail.createEmailMessage(emailSubject, emailBody);
		try {
			javaEmail.sendEmail();
			status = "success";
			message = "Email sent Successfully!";
		} catch (MessagingException me) {
			status = "error";
			message = "Error in Sending Email!";
		}
	}
%>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Contact Us</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel='stylesheet' href='style.css' type='text/css' media='all' />
</head>
<body>
	<div id="central">
		<div class="content">
			<h1>Contact Form</h1>
			<p>Send your comments through this form and we will get back to
				you.</p>
			<div id="message">
				<form id="frmContact" name="frmContact" action="" method="POST"
					novalidate="novalidate">
					<div class="label">Name:</div>
					<div class="field">
						<input type="text" id="pp-name" name="name"
							placeholder="enter your name here" title="Please enter your name"
							class="required" aria-required="true" required>
					</div>
					<div class="label">Email:</div>
					<div class="field">
						<input type="text" id="pp-email" name="email"
							placeholder="enter your email address here"
							title="Please enter your email address" class="required email"
							aria-required="true" required>
					</div>
					<div class="label">Phone Number:</div>
					<div class="field">
						<input type="text" id="pp-phone" name="phone"
							placeholder="enter your phone number here"
							title="Please enter your phone number" class="required phone"
							aria-required="true" required>
					</div>
					<div class="label">Message:</div>
					<div class="field">
						<textarea id="about-project" name="message"
							placeholder="enter your message here"></textarea>
					</div>
					<div id="mail-status"></div>
					<input type="submit" name="submit" value="Send Message"
						id="send-message" style="clear: both;">
					<%
						if (null != message) {
							out.println("<div class='" + status + "'>"
									+ message + "</div>");
						}
					%>
				</form>
			</div>
		</div>
		<!-- content -->
	</div>
	<!-- central -->
</body>
</html>

Email Sender Class

Following class is used to send the email. You need to supply the required parameters in it. I have configured it in such a way that we can use Google’s GMail SMTP server to send emails. You can also use any other SMTP server by suppling the respective parameters.

package com.javapapers.java.mail;

import java.util.Properties;

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

public class JavaEmail {

	Properties emailProperties;
	Session mailSession;
	MimeMessage emailMessage;

	String emailHost = "smtp.gmail.com";
	String emailPort = "587";// gmail's smtp port
	String fromUser = "gmail email here";// your gmail id
	String fromUserEmailPassword = "password here";
	String[] toEmails = { "joe@javapapers.com" };

	public void setMailServerProperties() {
		emailProperties = System.getProperties();
		emailProperties.put("mail.smtp.port", emailPort);
		emailProperties.put("mail.smtp.auth", "true");
		emailProperties.put("mail.smtp.starttls.enable", "true");
	}

	public void createEmailMessage(String emailSubject, String emailBody)
			throws AddressException, MessagingException {
		mailSession = Session.getDefaultInstance(emailProperties, null);
		emailMessage = new MimeMessage(mailSession);
		for (int i = 0; i < toEmails.length; i++) {
			emailMessage.addRecipient(Message.RecipientType.TO,
					new InternetAddress(toEmails[i]));
		}
		emailMessage.setSubject(emailSubject);
		emailMessage.setContent(emailBody, "text/html");// for a html email
		// emailMessage.setText(emailBody);// for a text email

	}

	public void sendEmail() throws AddressException, MessagingException {
		Transport transport = mailSession.getTransport("smtp");
		transport.connect(emailHost, fromUser, fromUserEmailPassword);
		transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
		transport.close();
	}
}

This example application is an Eclipse Dynamic Web Project. You can download it from below and import in your Eclipse. Java Mail API is added as dependency. The project show look as below.

Java-Contact-Form-Project

Download Contact Form Project

References

  1. JavaMail API

This Java tutorial was added on 17/03/2016.

Comments on "Contact Form Using JavaMail JSP" Tutorial:

  1. Sin Nombre says:

    Perfect !!
    Ty !!

  2. Sekhar says:

    Clearly explained. Really very good work.

  3. Bhimaraya says:

    Hi Sir,
    Please post some articles related to data tables using jquery and implementation of data structures(Internal architecture of all the data structures in java) in java.

    Thanks,
    Bhimaraya Nad

  4. Ahmed says:

    Hi sir,
    I’m trying to get spring mvc hello world application. But it shows “selection does not contain main method”. How can I resolve it tell me please.

Comments are closed for this "Contact Form Using JavaMail JSP" tutorial.