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

Upload file using Servlets/JSP in Java

Hello friends!

In many web applications, the user needs to upload a file on the web so that it can be used later on. Java EE allows developers to create dynamic web applications using Servlets or JSP (Java Server Pages). A Servlet is like any other Java class. You insert your HTML code into print statements like you use System.out. On the other hand, a JSP gets converted to a Servlet and embeds the Java code into HTML. Servlets and JSP are functionally equivalent.

In this post I will demonstrate how to upload a file using the Servlets/JSP technology.

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

Open Eclipse. Create a new Dynamic web project. Name the project as FileUploadExample. Select Target Runtime environment as Apache Tomcat 7.0. If you are unable to get this option, you need to configure and install Apache Tomcat 7 by following this link.

file_upload_1

Create new dynamic web project

Create new dynamic web project

Step 1: Add .jar files

Before you start implementing your Servlet code, you need to add two .jar files namely commons-fileupload-1.3.jar and commons-io-2.4.jar to the lib folder present under WEB-INF.

Step 2: Create JSP page

Now create a new JSP page named index.jsp inside your WebContent folder.

index.jsp


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>File Upload</title>
</head>
 
<body>

    <hr/>
 
    <fieldset>
        <legend>Upload File</legend>
        <form action="fileuploadservlet" method="post" enctype="multipart/form-data">
            <label for="filename_1">File: </label>
            <input id="filename_1" type="file" name="filename_1" size="50"/><br/>
            <br/>
            <input type="submit" value="Upload File"/>
        </form>
    </fieldset>
   
</body>
</html>

Step 3: Create Servlet and modify web.xml

Right click the src folder, and select New –> Servlet. Name the Servlet FileUploadDemoServlet and give the package name as com.example

FileUploadDemoServlet.java

package com.example;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.File;
import java.util.List;
import java.util.Iterator;
 
public class FileUploadDemoServlet extends HttpServlet {
    private static final long serialVersionUID = -3208409086358916855L;
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException 
            {

    	boolean isMultipart = ServletFileUpload.isMultipartContent(request);
 
        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
 
            try {
                List items = upload.parseRequest(request);
                Iterator iterator = items.iterator();
                while (iterator.hasNext())
                 {
                    FileItem item = (FileItem) iterator.next();
 
                    if (!item.isFormField()) 
                     {
                       
                        String fileName = item.getName();
                        String root = getServletContext().getRealPath("/");
                        
                        //path where the file will be stored
                        File path = new File("C:\\programs\\java_documents" + "/uploads");
                        if (!path.exists())
                        {
                            boolean status = path.mkdirs();
                        }
 
                        File uploadedFile = new File(path + "/" + fileName);
                        System.out.println(uploadedFile.getAbsolutePath());
                        item.write(uploadedFile);
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

Modify your web.xml file as follows!

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>FileUploadExample2</display-name>
  
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
        <servlet-name>FileUploadDemoServlet</servlet-name>
        <servlet-class>com.example.FileUploadDemoServlet</servlet-class>
  </servlet>
    
  <servlet-mapping>
        <servlet-name>FileUploadDemoServlet</servlet-name>
        <url-pattern>/fileuploadservlet</url-pattern>
  </servlet-mapping>
   
</web-app>

Finally, run the project on the Apache Tomcat server. Make sure no errors are present. You should see the following output on your console and browser respectively!

Output on browser and console

file_upload_output_1