Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to send email in JSP

In this article we will see how we can send an email through JSP and getting a response from the server.

There are certain steps to be followed to use Java Mailing System. To send an email using a JSP is simple enough but to start with you should have JavaMail API and Java Activation Framework (JAF) installed on your machine.

  • Firstly, download JavaMail (Version 1.2) from any Java's standard website.
  • Now we have to download latest version of JavaBeans Activation Framework JAF (Version 1.0.2) from Java's standard website.

Download and unzip these files, in the newly created top level directories you will find a number of jar files for both the applications. We need to include mail.jar and activation.jar files in our CLASSPATH.

Send a Simple Email:

Here is an example to send a simple email from our machine. Let us assume that our localhost is connected to the internet and capable enough to send an email. Simultaneously also check that all the jar files from Java Email API package and JAF package are available in CLASSPATH.

Listing 1: Sending a simple email

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

<%
   String result;
      String to = "abcd@gmail.com";
      String from = "mcm@gmail.com";
      String host = "localhost";


   Properties properties = System.getProperties();


properties.setProperty("mail.smtp.host", host);

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

   try{
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, InternetAddress(to));
message.setSubject("This is the Subject Line!");
message.setText("This is actual message");

Transport.send(message);
result = "Success....";
}
catch (MessagingExceptionmex) 
{
mex.printStackTrace();
result = "Error: unable to connect....";
}
%>
<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>

Now let us put above code in SendEmail.jsp file and call this JSP using URL http://localhost:9999/SendEmail.jsp which would send an email to given email ID abc@gmail.comand would display following response:

Send Email using JSP

Result: Sent message successfully....

If we want to send an email to multiple recipients then following methods would be used to specify multiple email IDs:

Listing 2: Sending email to multiple recipients

void addRecipients(Message.RecipientType type, Address[] addresses)
givesMessageException

Description of parameters:

  • Type: This would be set to TO, CC or BCC. Here CC represents Carbon Copy and BCC represents Black Carbon Copy.
  • Addresses: This is the array of email ID. We would need to use InternetAddress() method while denoting email IDs

Send an HTML Email:

Here is an example to send an HTML email from your machine. Here it is assumed that our localhost is connected to the internet and capable enough to deliver an email, also make sure all the jar files from Java Email API package and JAF package are available in CLASSPATH.

This example is same as previous one, except here we are using setContent() method to set content whose second argument is "text/html" to specify that the HTML content is included in the message.

Let us see an example, we can send as big as HTML content you like.

Listing 3: Example of sending email

<%@ pageimport="java.io.*,java.util.*,javax.mail.*"%>
<%@ pageimport="javax.mail.internet.*,javax.activation.*"%>
<%@ pageimport="javax.servlet.http.*,javax.servlet.*" %>
<%
   String result;
   String to = "abcd@gmail.com";
   String from = "mcmohd@gmail.com";
   String host = "localhost";
   Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
   Session mailSession = Session.getDefaultInstance(properties);
Try
{
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
                               new InternetAddress(toRecepient));
message.setSubject("This is the Subject Line!");
message.setContent("<h1>This messageis actual </h1>",
                            "text/html" );
Transport.send(message);
result = "Succesfully send the  message....";
   }catch (MessagingExceptionmex) {
mex.printStackTrace();
result = "Sending failed....";
   }
%>
<html>
<head>
<title>Send HTML 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>

Now we use above JSP to send HTML message on a given email ID.

Send Attachment in Email:

Let us see an example to send an email with attachment from our machine:

Listing 4: Example to send an email with attachment

<%@ pageimport="java.io.*,java.util.*,javax.mail.*"%>
<%@ pageimport="javax.mail.internet.*,javax.activation.*"%>
<%@ pageimport="javax.servlet.http.*,javax.servlet.*" %>
<%
   String result;
   String to = "abcd@gmail.com";
   String from = "mcmohd@gmail.com";
 String host = "localhost";
    Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
   Session mailSession = Session.getDefaultInstance(properties);
Try
{
MimeMessage message = new MimeMessage(mailSession);
      // Assign  From: header field of the header.
message.setFrom(new InternetAddress(from));

      // Assign To: header field in the header.
message.addRecipient(Message.RecipientType.TO,
                               new InternetAddress(to));
      // Set Subject: header field
message.setSubject("This is the Subject Line!");
      // Create the message part 
BodyPartmessageBodyPart = new MimeBodyPart();
      // Fill the message
messageBodyPart.setText("This is message body");
       // Create a multipar message
      Multipart multipart = new MimeMultipart();

      // Set text message part
multipart.addBodyPart(messageBodyPart);
      // Part two is attachment
messageBodyPart = new MimeBodyPart();
      String filename = "file.txt";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart );
Transport.send(message);
      String title = "Send Email";
result = " Successfully send....";
   }catch (MessagingExceptionmex) {
mex.printStackTrace();
result = "Failed to deliver....";
   }
%>
<html>
<head>
<title>Send Attachement Email using JSP</title>
</head>
<body>
<p align="center">
<% 
out.println("Result: " + result + "\n");
%>
</p>
</body>
</html>

User Authentication Part:

If it is necessary to provide user ID and Password to the email server for authentication purpose then we can set these properties as follows:

Listing 5: User authentication

props.setProperty("mail.user", "myuser");
props.setProperty("mail.password", "mypwd");

Using Forms to send email:

We can use HTML form to catch email parameters and then we can use request object to get all the information as follows:

Listing 6: Using HTML forms

String to = request.getParameter("to");
String from = request.getParameter("from");
String subject = request.getParameter("subject");
String messageText = request.getParameter("body");

Once we have all the data, we can use above mentioned programs to send email.

Conclusion

In this article we studied how we can send an email via JSP.Sending an email is a very important functionality of any application like Bookstores App, registering a new user. All such type where customer communication is necessary.

Thus JSP solve our problem and sends email with efficiency.

Hope you liked the article, see you next time.



I am well versed with Computer Programming languages and possess good working knowledge on software languages such as C, Java, PHP, HTML and CSS

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login