Table of contents
1.
Introduction
2.
Send emails using JSP
3.
Send emails using JSP to multiple recipients
4.
Send an Attachment in Email
5.
User Authentication Part
6.
FAQs
7.
Key Takeaways
Last Updated: Mar 27, 2024

Send Emails using JSP

Author Tanay kumar Deo
2 upvotes
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

JSP stands for Java Server Pages. JSP is a server-side programming language that combines HTML, XML, Java Servlet, and JavaBeans technologies into one highly productive technology. It allows developers to develop reliable, high-performance, platform-independent web applications, and dynamic websites.

This article will learn how to send emails using JSP (Java Server Pages ). To send emails using JSP, we should have the Java Activation Framework (JAF) and the JavaMail API installed on our machine.

Refer to the following link:

 

We have the Java Activation Framework (JAF) and the JavaMail API installed on our computer. Let's get started with the article on how to send emails using JSP.

Send emails using JSP

In this section we will consider an example to send a simple email using JSP. For this, we need to add the activation.jar and the mail.jar files in our CLASSPATH. After adding all the required packages in the CLASSPATH let's make our SendMail.jsp file.

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


<%
   String result;
  
   // Recipient's email ID
   String to = "abcd@codingninjas.com";


   // Sender's email ID
   String from = "mcmohd@codingninjas.com";


   String host = "localhost";


   // Get the system properties object
   Properties properties = System.getProperties();


   // Setup mail SMTP
   properties.setProperty("mail.smtp.host", host);


   // Get default Session object.
   Session mailSession = Session.getDefaultInstance(properties);


   try {
      // Create a MimeMessage object.
      MimeMessage message = new MimeMessage(mailSession);
      
      // Set From: header field of the header.
      message.setFrom(new InternetAddress(from));
      
      // Set To: header field of the header.
      message.addRecipient(Message.RecipientType.TO,
                               new InternetAddress(to));
      // Set Subject: header field
      message.setSubject("This is the Subject !");
      
      // Now set the actual message
      message.setText("This is the actual message");
      
      // Send message
      Transport.send(message);
      result = "Sent email successfully....";
   } catch (MessagingException mex) {
      mex.printStackTrace();
      result = "Error: failed to send message....";
   }
%>


<html>
   <head>
      <title>Send Emails using JSP</title>
   </head>
   
   <body>
         <h1>Send Emails using JSP</h1>
      <p > <% out.println("Result: " + result + "\n");%></p>
   </body>
</html>
You can also try this code with Online Java Compiler
Run Code

 

We implemented the logic for sending simple emails using JSP in the above code. Now, let's visit https://localhost:8080/sendmail.jsp to send a simple email to the given email id abcd@codingninjas.com. We will get a response like:

Output

Send emails using JSP to multiple recipients

If we want to send an email to one or more recipients, then we can use the following methods to specify all the email IDs :

void addRecipients(Message.RecipientType type, Address[] addresses)
throws MessagingException
You can also try this code with Online Java Compiler
Run Code

 

The parameters used in the above code is as follows:

1. type: With this parameter, we can add recipients by using TO( for one mail id), CC(Carbon Copy), or BCC(Blind Carbon Copy). For example, Message.RecipientType.CC

2. addresses: The address parameter is used to take the array of email IDs. We should make sure to use the method InternetAddress() while specifying email IDs.

Send an Attachment in Email

Sending an email with an attachment is very common. This section will learn how to send an attachment in email using JSP. Let's consider an example written below:

<%
   String result;
   
   // Recipient's email ID
   String to = "abcd@codingninjas.com";


   // Sender's email ID
   String from = "mcmohd@codingninjas.com";


   String host = "localhost";


   // Get the system properties object
   Properties properties = System.getProperties();


   // Setup mail SMTP
   properties.setProperty("mail.smtp.host", host);


   // Get default Session object.
   Session mailSession = Session.getDefaultInstance(properties);


   try {
      // Create a MimeMessage object.
      MimeMessage message = new MimeMessage(mailSession);
      
      // Set From: header field of the header.
      message.setFrom(new InternetAddress(from));
      
      // Set To: header field of the header.
      message.addRecipient(Message.RecipientType.TO,
                               new InternetAddress(to));
      // Set Subject: header field
      message.setSubject("This is the Subject !");
      
      // Now set the actual message
      message.setText("This is the actual message");
            // Creating a multipart message
            Multipart multipart = new MimeMultipart();


          // Set message part
          multipart.addBodyPart(messageBodyPart);


          // Setting Part two attachment
          messageBodyPart = new MimeBodyPart();
      
          String filename = "attachment.txt";
          DataSource source = new FileDataSource(filename);
          messageBodyPart.setDataHandler(new DataHandler(source));
          messageBodyPart.setFileName(“attachment”);
          multipart.addBodyPart(messageBodyPart);


          // Send the complete message parts
          message.setContent(multipart );      
      // Send message
      Transport.send(message);
      result = "Sent email successfully....";
   } catch (MessagingException mex) {
      mex.printStackTrace();
      result = "Error: failed to send message....";
   }
%>


<html>
   <head>
      <title>Send Emails using JSP</title>
   </head>
   
   <body>
         <h1>Send Emails using JSP</h1>
      <p > <% out.println("Result: " + result + "\n");%></p>
   </body>
</html>
You can also try this code with Online Java Compiler
Run Code

 

We implemented sending an email with an attachment from our computer using JSP in the above code. The response for the above code is same as the previous code.

Output


You can also read about the JSP Architecture and Lifecycle.

User Authentication Part

We have learned how to send emails using JSP, but how are these mails sent from the server? These emails are sent using some email service provider, and we can set them up using the properties.setProperty("mail.smtp.host", host). If required, we also need to provide UserID and Password to the email server for authentication. We can set these properties as mentioned below:

props.setProperty("mail.user", "myuserid");
props.setProperty("mail.password", "mypassword");
You can also try this code with Online Java Compiler
Run Code

FAQs

  1. What are different hosts we can use as email servers?
    There are a lot of SMTP(Simple Mail Transfer Protocol) servers. A few of them are listed below:
    Gmail - smtp.gmail.com
    Yahoo - smtp.mail.yahoo.com
    Hotmail - smtp-mail.outlook.com
     
  2. Can we use HTML forms to send emails using JSP?
    Yes, we can use HTML forms on the web page to send emails. We can get all the email parameters using the request object. For example,
String to = request.getParameter("to");
String from = request.getParameter("from");
String subjectText = request.getParameter("subject");
String messageBody = request.getParameter("body");
You can also try this code with Online Java Compiler
Run Code

Key Takeaways

This article implemented how to send emails using JSP with a detailed example. We learned how to send an email to multiple users using different methods like TO, CC, BCC. Finally, we discussed sending attachments in emails and the user authentication part.

Don't stop here. Check out the blogs Introduction to JSPJSP - Custom TagsJSP Architecture and Lifecycle, and JSP Syntax and First App.

Recommended Readings:

We hope you found this blog helpful. Liked the blog? Then feel free to upvote and share it.

Live masterclass