• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 430
  • Last Modified:

Sending mail from a JSP using Javamail........Very urgent!!!!!!! (250 points)

Hi Experts,

I have a jsp which gets loaded with data from the backend.Now this jsp has a table made of columns(time in hrs 00:00 to 23:00) which gets populated each time it is refreshed for every hr.If the data gets loaded correctly then the colour of the particular cell ie  column(time) and row(represented by some name) becomes green and when it fails it remains red.Now i need to send an email when ever the loading fails.How do i do that??
Do i have to write the javamail code within the jsp that iam having right now??If somebody can help me with the code it will be great!

The code for the jsp goes like this:

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<%@ page session="false" %>
<%@ page import="java.sql.*"%>
<%@ page import="com.inat.db.*"%>
<%@ page import="java.util.*"%>
<%@ page import="java.text.*"%>
<%@ page import="com.inat.bo.Status"%>
<%@ page import="com.inat.bo.StatusEntry"%>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<link type="text/css" rel="StyleSheet" href="../css/statustable.css" />
<h2 align=center> INAT :: Data Load Status </h2>
<%@ include file="../calendar.jsp" %>
    Enumeration entries = Status.getStatus(selDate);
<p><b>Status for : <%= displayDate %> <b></p>
<table class="status-table" border=0 cellspacing=1 cellpadding=2>
<td> BSC </td>
for (int i = 0; i < 24; i++) {
    String ts = i + ":00";
<td> <%= ts %> </td>
while(entries.hasMoreElements()) {
    StatusEntry entry = (StatusEntry)entries.nextElement();
    int numDataArrays = entry.getNumDataArrays();    
        <td class="label"> <%= entry.getName() %> </td>
        <% for (int hour = 0; hour < 24; hour++) {
               String code = "success";
               String msg = "";
               for (int i = 0; i < numDataArrays; i++) {
                   int[] data = entry.getDataArray(i);
                   if (data[hour] <= 0) {
                       code = "error";
                   msg += entry.getDataArrayName(i) + "=" + data[hour] + "<br>";
         <td class=<%=code %>>
         <%= msg %>
         <a href="ShowLogs.jsp?date=<%= selDate %>&bsc=<%= entry.getName() %>&hour=<%= hour %>&type=log">Info </a>,
         <a href="ShowLogs.jsp?date=<%= selDate %>&bsc=<%= entry.getName() %>&hour=<%= hour %>&type=err">Errors</a><br>        

I know i have to use the java mail api and write code something similar to this...

 Properties props = new Properties();
            props.put("mail.smtp.host", smtp);

            Session session = Session.getDefaultInstance(props, null);

            Message msg = new MimeMessage(session);
            msg.setFrom (new InternetAddress ("Accounts","accounts@widgetsandgadgets"));
            msg.addRecipient (Message.RecipientType.TO, new InternetAddress (toName,toAddr));
            msg.setSubject (subject);
            msg.setContent (content, "text/plain");
            Transport.send (msg);

But i do not know the process how i should be able to do it.If someone can give me the code i would appreciate it..I am new to this area....
Thanks once again..
  • 5
  • 4
1 Solution
Siva Prasanna KumarPrincipal Solutions ArchitectCommented:

there are lots of way one thing is you can have a srvlet like the above one and when the user says send you just nedd to forward the form action to this servlet and then send the main to the email id specified by the user and then use a request dispathcer to go to a new JSP.

here is another example http://www.java2s.com/Code/Java/JSP/EMail.htm

but i didn't had time to go through it.

or  else check out some shopping cart  applcation in http://www.java2s.com/Code/Java/JSP/Shopping-Cart.htm

atleast one of them will have a mailing option.

Thank You.
here is some code I created for my project.  don't for get to include the package statment.  just instantiate and call .send();

be sure to download the javamail package.

import javax.mail.*;
import javax.mail.Message.RecipientType;
import javax.mail.internet.*;
import java.util.*;
import java.io.*;
import javax.activation.*;

public class SendMail{

      public String to = "";
      public String from = "";
      public String Bcc = "";
      public String host = "";
      public String msgText1 = "";
      public String subject = "";
      public Vector fileNamesSentAs = null;
      public String filesLocation = "";
      public String loginName = "";
      public String password = "";

      public SendMail()


      public SendMail(String to, String from, String Bcc, String host, String message, String subject, String uname, String password)
            this.to = to;
            this.from = from;
            this.host = host;
            this.Bcc = Bcc;
            this.msgText1 = message;

            this.subject = subject;
            this.loginName = uname;
            this.password = password;

      public void send()
            // create some properties and get the default Session
            Properties props = System.getProperties();
            props.put("mail.smtp.host", this.host);

            Session session = Session.getInstance(props, null);

            try {
                  // create a message
                  MimeMessage msg = new MimeMessage(session);
                  msg.setFrom(new InternetAddress(this.from));

                  InternetAddress[] ReplyToInetAddresses = {new InternetAddress(this.from)};

                  InternetAddress[] address = {new InternetAddress(this.to)};
                  msg.setRecipients(MimeMessage.RecipientType.TO, address);

                        InternetAddress Bcc[] = {new InternetAddress(this.Bcc)};
                        msg.setRecipients(MimeMessage.RecipientType.BCC, Bcc);

                  msg.setSentDate(new Date());

                  Transport tr = session.getTransport("smtp");
                  tr.connect(this.host, this.loginName, this.password);
                  msg.saveChanges();      // don't forget this
                  tr.sendMessage(msg, msg.getAllRecipients());

            } catch (MessagingException mex) {
                  Exception ex = null;
                  if ((ex = mex.getNextException()) != null) {
raghuudupaAuthor Commented:
Thanks for the reply..
But what exactly should i do..??
Do i include the code that you sent inside my jsp ??Where do i instantiate? Please go through my requirement that i have written in my question and give me a good possible solution...
I appreciate your help....

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

What server are you running?
raghuudupaAuthor Commented:
The webserver is Apache Tomcat/5.5.12............
copy the code and save the file as SendMail.java(capitolization needed).  compile the .java file with javac (syntax - javac SendMail.java)  That will create a SendMail.class file.  copy that file into webapps/<app name>/WEB-INF/classes/ folder

download javaMail and copy the .jar file to webapps/<app name>/WEB-INF/lib folder

Insert the following code into your jsp page error block.

SendMail mail = new  SendMail(<to>,<from>,<bcc>,<host>,<message>,<subject>,<username>,<password>);

raghuudupaAuthor Commented:
In my jsp page i need to include this right??

if (data[hour] <= 0) {
                       code = "error";
SendMail mail = new  SendMail(<to>,<from>,<bcc>,<host>,<message>,<subject>,<username>,<password>);

I hope this is correct??
raghuudupaAuthor Commented:
Hi Isisagate,
What are the parameters that i require for this application...??
What do i need to find out like for example smtp hostname etc etc. for this application??
How do i get the from,uname,host ,pwd and to parameters??

Please explain the flow..I would really appreciate it..

replace <to> with recient e-mail address.
replace <from> with the responder e-mail address
replace <bcc> with a blind carbon copy(leave blank if not using)
replace <host> with smtp server address
replace <message> with the message body.
replace <subject> with the message subject
replace <username> with smtp servers authenication user name
replace <password> with smtp servers authentication password.

a sample line would be.

if (data[hour] <= 0) {
                       code = "error";
                       SendMail mail = new SendMail("raghuudupa@someDomain.com","raghuudupa@someDomain.com","","mail.someDomain.com","data[hour] <= 0","program error","raghuudupa","password");

raghuudupaAuthor Commented:
Cool ....Thanks a lot ...
Will get back to you and award you points once this works...
Thanks and i appreciate your help..
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

  • 5
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now