[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 413
  • 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">
<head>
<link type="text/css" rel="StyleSheet" href="../css/statustable.css" />
<title>INat::LoadStatus</title>
</head>
<body>
<h2 align=center> INAT :: Data Load Status </h2>
<form>
<%@ include file="../calendar.jsp" %>
<%
    Enumeration entries = Status.getStatus(selDate);
%>
</form>
<p><b>Status for : <%= displayDate %> <b></p>
<br>
<table class="status-table" border=0 cellspacing=1 cellpadding=2>
<thead>
<tr>
<td> BSC </td>
<%
for (int i = 0; i < 24; i++) {
    String ts = i + ":00";
%>
<td> <%= ts %> </td>
<%
}
%>
</tr>
</thead>
<%
while(entries.hasMoreElements()) {
    StatusEntry entry = (StatusEntry)entries.nextElement();
    int numDataArrays = entry.getNumDataArrays();    
%>
    <tr>
        <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>        
         </td>
        <%
         }
        %>
    </tr>
<%
}
%>    
</table>
</body>
</html>

------------------------------------------------------->---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------->------------------------------------------------------------------------------------
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..
0
raghuudupa
Asked:
raghuudupa
  • 5
  • 4
1 Solution
 
Siva Prasanna KumarPrincipal Solutions ArchitectCommented:
http://www.java2s.com/Code/Java/Servlets/Servletandemail.htm

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.
0
 
IsisagateCommented:
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);
            props.put("mail.smtp.auth","true");

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

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

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

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

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

                  msg.setSubject(this.subject);
                  msg.setText(this.msgText1);
                  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());
                  tr.close();



            } catch (MessagingException mex) {
                  mex.printStackTrace();
                  Exception ex = null;
                  if ((ex = mex.getNextException()) != null) {
                  ex.printStackTrace();
                  }
            }
      }
}
0
 
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....

Thanks
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
IsisagateCommented:
What server are you running?
0
 
raghuudupaAuthor Commented:
The webserver is Apache Tomcat/5.5.12............
0
 
IsisagateCommented:
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>);
mail.send();

0
 
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>);
mail.send();
}

I hope this is correct??
0
 
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..
0
 
IsisagateCommented:
Yes,

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");
                       mail.send();
}

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

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

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