Tutorial #99: Send e-mail using JavaMail in JSP

Hi everyone!

JavaMail is a well known Java API used to send and receive email via SMTP, POP3 and IMAP. It mainly provides a platform-independent and protocol-independent framework to build mail and messaging applications. In addition, the JavaMail API package is also included in the Java EE platform.

JavaMail facilitates the sending of an e-mail via Gmail SMTP server, using both TLS and SSL connection. Through this tutorial, we will learn how to send an e-mail using JavaMail in a sample JSP page.

Pre-requisites: Eclipse IDE for Java EE developers, Apache Tomcat 7

Step 1: Create new Dynamic web project

Launch Eclipse IDE and create a new Dynamic web project called SendEmailUsingJSP with target runtime as Apache Tomcat 7.

Step 2: Add external jar files

In order to implement the sending of an e-mail, developers need to download and use the latest version of the JavaMail API in their web projects. For this tutorial, I will be using the mail-1.4.7.jar version of the JavaMail API. Make sure you add the .jar file in the WEB-INF/lib folder of your web project.

Step 3: Create JSP page

Create a new index.jsp page inside the WebContent folder of your web project and write the following code.

index.jsp

<%@ pageimport="javax.servlet.http.*,javax.servlet.*" %>
<%@ page import="javax.mail.internet.*,javax.activation.*"%>
<%@ page import="java.io.*,java.util.*,javax.mail.*"%>
<%

    //username for abc@gmail.com will be "abc"
	String username = "sender_username";
	String password = "sender_password";
	String result = null;

	try {
		
        Properties props = System.getProperties();
		props.setProperty("mail.transport.protocol", "smtp");
		props.setProperty("mail.host", "smtp.gmail.com");
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.port", "465");
		props.put("mail.debug", "true");
		props.put("mail.smtp.socketFactory.port", "465");
		props.put("mail.smtp.socketFactory.class",
				"javax.net.ssl.SSLSocketFactory");
		props.put("mail.smtp.socketFactory.fallback", "false");

		Session emailSession = Session.getInstance(props,
				new javax.mail.Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication("sender_username","sender_password");
				}
		});

		emailSession.setDebug(true);
		Message message = new MimeMessage(emailSession);
		message.setFrom(new InternetAddress(
				"sender_username@gmail.com"));
		message.setRecipients(Message.RecipientType.TO,
				InternetAddress.parse("xyz@hotmail.com"));
		message.setSubject("Test mail from Java");
		message.setText("Hello. this is a test");

		Transport transport = emailSession.getTransport("smtps");
		transport.connect("smtp.gmail.com", username, password);
		transport.sendMessage(message, message.getAllRecipients());

		result = "Successfully sent email";

	   } catch (MessagingException e) {
		result = "Unable to send email";
	}
%>
<html>
<head>
<title>Send Email using JSP</title>
</head>
<body>
	<center>
		<h1>Send Email using JSP</h1>
	</center>
	<p align="center">
		<%
			out.println("Result: " + result + "\n");
		%>
	</p>
</body>
</html>

Finally, save all changes and run the application on the Tomcat server. If no errors occur then you should see the following output!

output

Reference: JavaMail API

Karan Balkar About Karan Balkar
self proclaimed extraterrestrial fandroid, computer engineer, amateur gamer and die hard punk rock fan!

9 thoughts on “Tutorial #99: Send e-mail using JavaMail in JSP

  1. Not the best approach. There are existing Taglibs and Beans that support sending mail. A JSP should only display data (as a view). On the other side there are several security issues e. g. to store a password in a view component, missing exception handling (availabilty of mail server, connection timeouts), securing connections.

    • Hi Thomas,

      Yes I will agree with you on that. The code sample is definitely not a best practice and I would not recommend using it in a more practical situation. However, some might want an idea on how to send an e-mail if required through JSP. Although, this doesn’t happen most of the times as you rightly explained but then some might just want a quick and dirty code 🙂

  2. plz let me know i m doing travel Request project. when the user enter the details and when he submit the button . the whole details should go through e-mail only for 3 person eg any gmail id. but one person should approve i.e he should accept and after approving the mail should go to tat person who enter all details. i m dng all pages in jsp nd sql

  3. message.setRecipients(Message.RecipientType.TO,
    InternetAddress.parse(“database??”));

    i want to get the email adres from a database to sent. can someone help me please.

Leave a Reply

Your email address will not be published. Required fields are marked *