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

Posted on 2006-06-07
Last Modified: 2012-06-21
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" "">
<%@ page session="false" %>
<%@ page import="java.sql.*"%>
<%@ page import="com.inat.db.*"%>
<%@ page import="java.util.*"%>
<%@ page import="java.text.*"%>
<%@ page import=""%>
<%@ page import=""%>
<html xmlns="" 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("", 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..
Question by:raghuudupa
    LVL 23

    Expert Comment


    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

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

    or  else check out some shopping cart  applcation in

    atleast one of them will have a mailing option.

    Thank You.
    LVL 11

    Accepted Solution

    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 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)
       = to;
                this.from = from;
       = 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();

                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(};
                      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.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) {

    Author Comment

    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....

    LVL 11

    Expert Comment

    What server are you running?

    Author Comment

    The webserver is Apache Tomcat/5.5.12............
    LVL 11

    Expert Comment

    copy the code and save the file as needed).  compile the .java file with javac (syntax - javac  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>);


    Author Comment

    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??

    Author Comment

    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..
    LVL 11

    Expert Comment


    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("","","","","data[hour] <= 0","program error","raghuudupa","password");


    Author Comment

    Cool ....Thanks a lot ...
    Will get back to you and award you points once this works...
    Thanks and i appreciate your help..

    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    Join & Write a Comment

    Suggested Solutions

    When we have a dead host and we lose all connections to the ESXi, and we need to find a way to move all VMs from that dead ESXi host.
    David Varnum recently wrote up his impressions of PRTG, based on a presentation by my colleague Christian at Tech Field Day at VMworld in Barcelona. Thanks David, for your detailed and honest evaluation!
    Need more eyes on your posted question? Go ahead and follow the quick steps in this video to learn how to Request Attention to your question. *Log into your Experts Exchange account *Find the question you want to Request Attention for *Go to the e…
    Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

    754 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    23 Experts available now in Live!

    Get 1:1 Help Now