Java mail process  hangs

Hi,
I am connecting to exchange server to read the mails. The program works fine but sometimes it just hangs.
The process hangs at "store = session.getStore("imap")".
Any help?
Thanks

Can you get a stack trace when the hang occurs?
The most common cause of hanging is trying to connect to a server that's not up.
You can set timeouts to control that.
But the getStore method is an entirely local method, it should not hang.

Similar Messages

  • C++ process hangs when started from Java

    I am trying to execute a c++ code from java on a remote Windows machine. In order to deal with the remote part, I have created a Web service from where the actual command is run using Runtime.exec(). The c++ exe is not being called directly from the java code. I have a batch file that eventually calls the exe.
    The problem is, both java and c++ processes hang. The java code on server side does handle the output stream and error stream. Also, the c++ code is logging everything in a file on Windows. The strange thing is that, when I remove the WS call and run the java code on server side as a standalone java program, it succeeds. Also, execution of the batch file alone does not hang. Here is the java code:
    public class RunCPlusPlusExecutable {
    public int runExecutable() {
        int exitValue = 0;
        try {
            Process p = null;
            Runtime rt = Runtime.getRuntime();
            System.out.println("About to execute" + this + rt);
            p = rt.exec("c:/temp/execcplusplus.bat");
            System.out.println("Process HashCode=" + p.hashCode());
            StreamProcessor errorHandler = new StreamProcessor(p.getErrorStream(), "Error");
            StreamProcessor outputHandler = new StreamProcessor(p.getInputStream(), "Output");
            errorHandler.start();
            outputHandler.start();
            exitValue = p.waitFor();
            System.out.println("Exit value : " + exitValue);
            if (exitValue == 0)
                System.out.println("SUCCESS");
            else
                System.out.println("FAILURE");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (Exception e) {
        return exitValue;
    class StreamProcessor extends Thread {
        private InputStream is = null;
        private String type = null;
        private InputStreamReader isr = null;
        private BufferedReader br = null;
        private FileWriter writer = null;
        private BufferedWriter out = null;
        StreamProcessor(InputStream is, String type) {
            this.is = is;
            this.type = type;
        public void run() {
            try {
                isr = new InputStreamReader(is);
                br = new BufferedReader(isr);
                writer = new FileWriter("*******path to log file********");
                out = new BufferedWriter(writer);
                String line = null;
                while ((line = br.readLine()) != null) {
                    Date date = new Date();
                    out.write("[" + type + "]: " + date + " : " + line);
                    out.newLine();
                writer.flush();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            } finally {
                try {
                    if (br != null)
                        br.close();
                    if (isr != null)
                        isr.close();
                    if (out != null)
                        out.close();
                    if (writer != null)
                        writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
    String line = null;
                while ((line = br.readLine()) != null) {
                    Date date = new Date();
                    out.write("[" + type + "]: " + date + " : " + line);
                    out.newLine();
                writer.flush();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            } finally {
                try {
                    if (br != null)
                        br.close();
                    if (isr != null)
                        isr.close();
                    if (out != null)
                        out.close();
                    if (writer != null)
                        writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
    The WS server is running from some admin user. And I have been running the standalone java program from some other user. It seems that the c++ executable is giving referenced memory error when being executed from WS call. There are pop-ups citing the error with OK and Cancel buttons(visible when logged in as admin). The error states
    The instruction at 0x05473030 referenced memory at 0x000001d4. The memory could not be read
    Any idea what is causing the problem and how to debug it? Why does this memory error comes only when the exe is run through WS call? Please note that I won't be able to debug the c++ code and the web service is an apache axis2 service.
    Thanks

    How can I know? Its your environment, not mine. The only thing we know is that when running the stuff through one path things blow up and when you run them through another path, things don't blow up. User rights is an obvious suspect, but not necessarily the actual problem. Generally when rights are the problem, you get some form of "access denied" exception, not a code hang.
    Another likely possibility is that of network settings; perhaps your server goes through a proxy and your local applications do not, or the other way around.
    Yet another likely possibility is that the version of Java used is different, or different versions of libraries are no the classpath causing differences in behavior. There is only one way to figure it out: get to know your environment very well and through solid reasoning and experimentation try to figure out where the breaking point is. It all starts with answering this question: what might be different in the environment of the web server, and outside of it? I can't know, only you can. Good luck.

  • Help me IN JAVA MAIL

    HI TO ALL......
    I AM NEW TO THIS FIELD....I AM TRYING TO SEND EMAIL THROUGH JAVA MAIL FUNCTION......,FIRST I AM FETCHING THE MAIL ADDRESS FROM DATA BASE.....I WANT TO SEND MAIL TO THOSE ADDRESS......HERE I M LITTLE BIT CONFUSED....PLZ HELP ME....BELOW IS THE CODE.........
    THIS FOR SEARCHING THE MAIL IDS......(SearchEmail .java)
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.util.*;
    import java.sql.*;
    public class SearchEmail extends HttpServlet {
    public String s1;
    public String username="root";
    public String passWord="";
    public String url="jdbc:mysql://192.168.0.7:3306/ias";
    private String SUB_NO="";
    private String ST_DT="";
    private String EMAIL="";
    public void init() {
    try {
    Class.forName("sun.mysql.Jdbc.Driver");
    System.out.println("JDBC driver loaded");
    catch (ClassNotFoundException e) {
    System.out.println(e.toString());
    /**Process the HTTP Get request*/
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    sendPageHeader(response);
    sendSearchForm(response);
    sendPageFooter(response);
    /**Process the HTTP Post request*/
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    ST_DT = request.getParameter("ST_DT");
    sendPageHeader(response);
    sendSearchForm(response);
    sendSearchResult(response);
    sendPageFooter(response);
    public void sendSearchResult(HttpServletResponse response)
    throws IOException {
    PrintWriter out = response.getWriter();
    try {
    Connection con = DriverManager.getConnection(url,username,passWord);
    System.out.println("got connection");
    Statement s = con.createStatement();
    String sql= "SELECT EMAIL " + "FROM temp "+
    "WHERE ST_DT='" + ST_DT + "' AND EMAIL!='" + null + "'";
    ResultSet rs = s.executeQuery(sql);
    StringBuffer sb = new StringBuffer(100);
    while (rs.next()) {
    String SUB_NO = rs.getString(1);
    s1 =sb.append( rs.getString(1)).append(",").toString();
    out.println("<TABLE border='1'>");
    out.println("<TR>");
    out.println("<TD>TO</TD><TD><INPUT TYPE=TEXT SIZE='50' VALUE='"+ s1 +"' ></TD>");
    out.println("</TR>");
    out.println("<TR>");
    out.println("<TD>FROM</TD><TD><INPUT TYPE=TEXT SIZE='50' [email protected] ></TD>");
    out.println("</TR>");
    out.println("</TR>");
    out.println("<TD>SUBJECT</TD><TD><INPUT TYPE=TEXT SIZE='50' NAME=SUBJECT></TD>");
    out.println("</TR>");
    out.println("<TR>");
    out.println("<TD>MESSAGE </TD><td><textarea cols='70' rows='20' name='MESSAGE'>");
    out.println("C.Vedamurthy senior");
    out.println("Administrative Assistant");
    out.println("Indian Academy of Sciences");
    out.println("C.V.Raman Avenue,Near Mekhri Circle");
    out.println("Post Box No 8005,sadashivanagar'");
    out.println("bangalore 560080");
    out.println("office no 23612546,23611034,23612943 extn 207 ");
    out.println("res 23431357;Fax 23616094;");
    out.println("</textarea></td>");
    out.println("</TR>");
    out.println("<table align='center'>");
    out.println("<TR>");
    out.println("<form action='mailservlet' method='post' name='myform'>");
    out.println("<CENTER> <TD><INPUT TYPE='SUBMIT' VALUE='send'></INPUT></TD></CENTER>");
    out.println("</form>");
    out.println("</TR>");
    out.println("</TABLE>");
    rs.close();
    s.close();
    con.close();
    catch (SQLException e) {
    catch (Exception e) {
    out.println("</TABLE>");
    * Send the HTML page header, including the title
    * and the <BODY> tag
    private void sendPageHeader(HttpServletResponse response)
    throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<HTML>");
    out.println("<HEAD>");
    out.println("<TITLE>Displaying Selected Record(s)</TITLE>");
    out.println("</HEAD>");
    out.println("<BODY BGCOLOR=#FFE4C4>");
    out.println("<CENTER>");
    * Send the HTML page footer, i.e. the </BODY>
    * and the </HTML>
    private void sendPageFooter(HttpServletResponse response)
    throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    out.println("</CENTER>");
    out.println("</BODY>");
    out.println("</HTML>");
    /**Send the form where the user can type in
    * the details for a new user
    private void sendSearchForm(HttpServletResponse response)
    throws IOException {
    PrintWriter out = response.getWriter();
    out.println("<BR><H2>Search</H2>");
    out.println("<BR>");
    out.println("<BR><FORM METHOD=POST>");
    out.print("START DATE: <INPUT TYPE=TEXT Name=ST_DT");
    out.print(" VALUE=\"" + ST_DT + "\"");
    out.println(">");
    out.println("<BOTTOM>");
    out.println("<TABLE ALIGN='CENTER'>");
    out.println("<INPUT TYPE=SUBMIT VALUE=submit>");
    out.println("</TABLE>");
    out.println("</FORM>");
    THIS IS JAVA MAIL FUNCTION.........(mailservlet .java)
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import javax.mail.*;
    import javax.mail.internet.*; // important
    import javax.mail.event.*; // important
    import java.net.*;
    import java.util.*;
    import javax.mail.MessagingException;
    public class mailservlet extends HttpServlet
    public void doPost(HttpServletRequest request,HttpServletResponse response)
    throws ServletException, IOException
    PrintWriter out=response.getWriter();
    response.setContentType("text/html");
    try
    Properties props=new Properties();
    props.put("mail.smtp.host","localhost"); // 'localhost' for testing
    Session session1 = Session.getDefaultInstance(props,null);
    String s1 = request.getParameter("FROM"); //sender (from)
    String s2 = request.getParameter("EMAIL");
    String s3 = request.getParameter("SUBJECT");
    String s4 = request.getParameter("MESSAGE");
    Message message =new MimeMessage(session1);
    message.setFrom(new InternetAddress(s1));
    message.setRecipients
    (Message.RecipientType.TO,InternetAddress.parse(s2,false));
    message.setSubject(s3);
    message.setText(s4);
    Transport.send(message);
    out.println("mail has been sent");
    catch(Exception ex)
    out.println("COULD NOT SEND EMAIL.....");
    plz help me its very urgent ........

    out.println("<TD>TO</TD><TD><INPUT TYPE=TEXT SIZE='50' VALUE='"+ s1 +"' ></TD>");
    out.println("</TR>");
    out.println("<TR>");
    out.println("<TD>FROM</TD><TD><INPUT TYPE=TEXT SIZE='50' VALUE=[email protected] ></TD>");
    You didn't put names to those fields above:
    out.println("<TD>TO</TD><TD><INPUT TYPE=TEXT SIZE='50' VALUE='"+ s1 +"' name ='EMAIL'></TD>");
    out.println("</TR>");
    out.println("<TR>");
    out.println("<TD>FROM</TD><TD><INPUT TYPE=TEXT SIZE='50' VALUE='[email protected]'  name='FROM'></TD>");also try:
    catch(Exception ex)
    out.println("COULD NOT SEND EMAIL.....");
    ex.printStackTrace();
    }to know what is exactly the error.

  • Using Java Mail API from Tomcat

    Hello,
    Purely as an academic exercise I have written a JSP page which, upon being requested from the client's browser, should send me a default email using Java Mail Api.
    here is the code :
    import java.util.*;
    import java.io.*;
    import javax.mail.*;
    import javax.mail.internet.*;
    import javax.activation.*;
    public class TestMail {
        static String msgText1 = "success this time 12";
        static String msgText2 = "This is the text in the message attachment.";
        public String sendIt() {
            String to = "<my email";
            String from = "<anything>";
            String host = "<my ip address of smtp server>";
            boolean debug = false;
            Properties props = new Properties();
            props.put("mail.smtp.host", host);
            Session session = Session.getInstance(props, null);
    .....The code works fine as a stand alone app but when called from JSP page it hangs on the Session.getInstance line. I can only guess that this might be a security issue with the container not allowing access to the smtp server ?
    Can anyone give me a clue ???

    Your Tomcat log files should spell out the problem for you.
    My Tomcat installation does not come with the Java Mail API. I had to add the mail and activation jar files to the server/common.lib directory (or the server's shared/lib or the WEB-INF/lib of your application.)
    HTH.

  • Sneak preview sp11 java edition install hangs

    I posted this in the NetWeaver forum originally but now realize this might be a more appropriate forum.
    I am trying to install the sneak preview sp11 java edition to a brand new box. The installation hangs on the "Load Java Database Content" step. The last thing in the jload.log is:
    08.11.05 00:24 com.sap.inst.jload.Jload dbImport
    INFO: table J2EE_CONFIGENTRY created
    It's been running for 24 hours now and has not moved off that step. The java.exe process is using 50% cpu so it apparently thinks it's doing something. I've seen the posts regarding errors with the install and the Timezone change fix, but I'm already in a timezone that has DST.
    Any ideas?

    I had the same problem. I tried reinstalling a couple of times, but the same thing happened - the installation was just hanging and using 100% cpu time.
    As the installation had not been tested with JDK 5.0 I had installed the newest version of 1.4.2, namely 1.4.2_10.
    Then, just for kicks, I uninstalled 1.4.2_10 and installed 1.4.2_08 - 40 minutes later I got the "Successful install" screen.
    I hope this helps.
    ps: it should be noted that I installed on a freshly installed Windows XP (and later on a freshly installed Windows 2003 Server - also without problems) with German regional settings, just to make sure - I have later reverted the regional settings to my locale.
    Message was edited by: Rune Jeppesen

  • Problem with starting a sqlplus-process via java.lang.Process

    Hi,
    I want to start a sqlplus-Process from a java-application via java.lang.Process. Works great with XP. On a W2K-Machine, the process is started (I can see it in the Taskmanager), but it doesn't connect to the db - the OS-process hangs, also the java-application which invoked the process.
    If I start a sqlplusw.exe-Process instead of sqlplus.exe, it works as well.
    Does anybody know what's going wrong ?
    I'm using java 1.5.0_11 and Oracle Database 10g Enterprise Edition Release 10.2.0.3.0
    Thanks in advance
    Jens

    java.lang.Process can be used to perform an OS Shell to launch specific tasks. But why are you interested in specifically launching sqlplus from here?
    ~ Madrid
    http://hrivera99.blogspot.com/

  • Workflow Java Mailer - Where is it?

    Hi,
    I have installed Oracle Workflow Server Release 10.1.0.3 for Linux x86 standalone on a on a 10.1.0.4 database run the configuration assistant. The DAD is configured in the 10G Standalone HTTPD which i installed from the 10.1.0.3 companion CD and after sorting out a number of installation issues the installation was successful.
    I have one missing component and that is the Java Mailer which is said to be 'included' with Workflow server 2.6.3 in the install notes:
    Oracle® Workflow Installation Notes for Oracle Database Release 2.6.3 February 2004 Part No. B12169-01
    Quote "Java-based Workflow Notification Mailer: The Notification System includes a Java-based program called a notification mailer, implemented as a service component within the Generic Service Component Framework, which communicates notifications to users via e-mail and interprets responses. Oracle Workflow provides one seeded notification mailer service component called the Workflow Notification Mailer. This program requires an outbound SMTP mail server and an inbound IMAP mail server"
    after chasing my tail for hours trying to find where and how this components needs to be installed I came across 266612.1 which has some references to a. Oracle® Content Management SDK 10g (9.0.4.2.0) and Oracle® Application Server Integration 10g (10.1.2.0.0).
    I have looked at the documentation for these two components and there is nothing specific mentioned about the Java Mailer, although workflow is mentioned amoung other things..
    If someone could point me in the right direction i would be exceedingly grateful. What I thought was a simple exercise in getting workflow installed and being able to send emails using the standard workflow API's and turned into a monumental journey of frustration and utter waste of time which a customer is paying for.
    Reading between the lines it looks like i need yet another installation of Oracle (the 10.1.2) application server along with the two components above.
    Also, Workflow 2.6.4 is included in the 10G Release 2 Database companion CD. Is the Java Mailer included with this version?
    My apologies if this post has come across somewhat indignant, I get annoyed when people flame in posts and then ask for help, but i am genuinely needing advice from someone who done the seemingly impossible.
    regards,
    Brenden

    Sorry, for database installation there is a seperate application to manage workflow (can't remember the name but you can find it in the apache server middle tier or you can view "install" folder a WF***MANAGER.ear file in there, start up your apache and run it in your browser ).
    The parameter you entered in config assistant for mailer isn't enough to get it working because you need some extra bits, for example the password and the path that points to processed folder and discard folder, etc. All of these bit can be set in workflow manager, remember don't keep looking for the JAR file for mailer, even if you found it you can do nothing about it unless you successfully run the workflow manager after installation.
    Once you have the workflow manager up and running you shall be able to config the mailer in there.
    List of steps: (if you go for silent installation you don 't need to do the post config in workflow manager anymore, and mailer shall be ready to run)
    for wf shipped with DB
    1. follow offical installation note
    2. it will ask for a apache home to be used as middle tier
    3. run through all steps
    4. find Wf manager and run the config through the interface.
    5. test the mailer in wf manager
    I would like someone correct if wrong because I have no experience to set up wf server shipped with DB, but for the one shipped with CMSDK I can answer you alot.
    Regards,
    Kun

  • Java mail Demo Web App

    I have tried to run and deploy demo web app that comes with java mail 1.3, but while logging i have got the following error:
    javax.mail.MessagingException: Connection timed out: connect; nested exception is: java.net.ConnectException: Connection timed out: connect
    And while sending message it generates the following error:
    A Servlet Exception Has Occurred
    org.apache.jasper.JasperException: This absolute uri (http://java.sun.com/products/javamail/demo/webapp) cannot be resolved in either web.xml or the jar files deployed with this application
         at org.apache.jasper.compiler.TagLibraryInfoImpl.(TagLibraryInfoImpl.java:194)
         at org.apache.jasper.compiler.TagLibraryInfoImpl.(TagLibraryInfoImpl.java:174)
         at org.apache.jasper.compiler.JspParseEventListener.processTaglibDirective(JspParseEventListener.java:1148)
         at org.apache.jasper.compiler.JspParseEventListener.handleDirective(JspParseEventListener.java:755)
         at org.apache.jasper.compiler.DelegatingListener.handleDirective(DelegatingListener.java:121)
         at org.apache.jasper.compiler.Parser$Directive.accept(Parser.java:243)
         at org.apache.jasper.compiler.Parser.parse(Parser.java:1132)
         at org.apache.jasper.compiler.Parser.parse(Parser.java:1091)
         at org.apache.jasper.compiler.Parser.parse(Parser.java:1087)
         at org.apache.jasper.compiler.ParserController.parse(ParserController.java:213)
         at org.apache.jasper.compiler.Compiler.compile(Compiler.java:210)
         at org.apache.jasper.servlet.JspServlet.loadJSP(JspServlet.java:543)
         at org.apache.jasper.servlet.JspServlet$JspServletWrapper.loadIfNecessary(JspServlet.java:176)
         at org.apache.jasper.servlet.JspServlet$JspServletWrapper.service(JspServlet.java:188)
         at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:381)
         at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:473)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:1264)
         at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:672)
         at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:430)
         at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:354)
         at FilterServlet.doPost(FilterServlet.java:61)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:1145)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:1264)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:243)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:566)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:472)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:215)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:566)
         at org.apache.catalina.valves.CertificatesValve.invoke(CertificatesValve.java:246)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:564)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:472)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943)
         at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2366)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:566)
         at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:462)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:564)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:472)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:163)
         at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline.java:566)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:472)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943)
         at org.apache.catalina.connector.http.HttpProcessor.process(HttpProcessor.java:1005)
         at org.apache.catalina.connector.http.HttpProcessor.run(HttpProcessor.java:1098)
         at java.lang.Thread.run(Thread.java:534)
    Please send me a fully working war file if any one have with the web server used ! Please I have to subit this as my assignment!

    You might want to try the latest version of that app included
    with JavaMail 1.4. It has a few fixes that might help you.
    Hopefully you're not going to take credit for this with your
    assignment. :-)

  • Java Mail Project HELP Required....URGENT PLZ HELP!!!

    hello there!!
    i took up a pjct for my engineering on java mail..got the code..and i thought that ill analyse it...the code is submitting the mail to the smtp server but after dat its failing to deliver to the client..as i can see this error in the logs on SMTP server...can anyone help me out in analysing this code!!!
    plz help, exams are near...(am new to java)
    //java FINAL!
    import javax.swing.*;
    import java.net.URL;
    import javax.mail.*;
    import javax.mail.internet.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    public class EmailProg extends JPanel implements ActionListener {
    protected JTextArea textArea;
    protected String newline = "\n";
    static final private String composemail = "compose";
    static final private String sendmail = "send";
    static final private String about = "about";
    static final private String submit = "submit";
    static final private String exit = "exit";
    JLabel lSubmit = new JLabel("Submit");
    JButton subbutton = new JButton();
    JTextArea emailfrom = new JTextArea(1,1);
    JTextArea emailto = new JTextArea(1, 1);
    JTextArea emailsubject = new JTextArea(1, 1);
    JTextArea emailmessage = new JTextArea(25, 1);
    //------BAG LAYOUT
    JLabel lFrom = new JLabel("From:");
    JTextField cFrom = new JTextField(32);
    JLabel lTo = new JLabel("To:");
    JTextField cTo = new JTextField(32);
    JFrame frame2 = new JFrame("Compose New");
    JLabel lSubject = new JLabel("Subject");
    JTextField cSubject = new JTextField(32);
    JLabel lMessage = new JLabel("Body");
    JTextArea cMessage = new JTextArea(5,32);
    //====================================
    public EmailProg() {
    super(new BorderLayout());
    //Create the toolbar.
    JToolBar toolBar = new JToolBar();
    addButtons(toolBar);
    //Create the text area used for output. Request
    //enough space for 5 rows and 30 columns.
    textArea = new JTextArea(5, 30);
    textArea.setEditable(false);
    textArea.setText("Welcome to Jeff's email program! With this program you can compose and send emails. I hope I get a good grade on thise, and marine world finds a good use for it :-D:-D (implements really just testing the scroller!!!)");
    JScrollPane scrollPane = new JScrollPane(textArea);
    //Lay out the main panel.
    setPreferredSize(new Dimension(450, 110));
    add(toolBar, BorderLayout.NORTH);
    add(scrollPane, BorderLayout.CENTER);
    //==================================
    protected void addButtons(JToolBar toolBar) {
    JButton button = null;
    //first button
    button = makeNavigationButton("/toolbarButtonGraphics/general/ComposeMail24.gif", composemail ,"Compose new Email", "compose new");
    toolBar.add(button);
    //second button
    button = makeNavigationButton("toolbarButtonGraphics/general/SendMail24.gif", sendmail,"Send The Mail","send");
    toolBar.add(button);
    //third button
    button = makeNavigationButton("toolbarButtonGraphics/general/About24.gif", about,"About","About");
    toolBar.add(button);
    //exit button
    button = makeNavigationButton("toolbarButtonGraphics/general/Stop24.gif", exit, "Exit", "Exit");
    toolBar.add(button);
    //===================================
    protected JButton makeNavigationButton(String imageName, String actionCommand, String toolTipText, String altText) {
    //Look for the image.
    String imgLocation = imageName;
    URL imageURL = EmailProg.class.getResource(imgLocation);
    //Create and initialize the button.
    JButton button = new JButton();
    button.setActionCommand(actionCommand);
    button.setToolTipText(toolTipText);
    button.addActionListener(this);
    if (imageURL != null) {                      //image found
    button.setIcon(new ImageIcon(imageURL));
    } else {                                     //no image found
    button.setText(altText);
    System.err.println("Resource not found: "+ imgLocation);
    return button;
    //=============================
    public void actionPerformed(ActionEvent e) {
    String cmd = e.getActionCommand();
    String description = null;
    // Handle each button.
    if (exit.equals(cmd)){
    textArea.setText("");
    description = "EXITING";
    System.exit(0);
    if (composemail.equals(cmd)) { //first button clicked
    textArea.setText("");
    description = "Write new mail.";
    composeWindow();
    } else if (sendmail.equals(cmd)) { // second button clicked
    textArea.setText("");
    description = "This button does'nt do anything yet :x";
    } else if (about.equals(cmd)) { // third button clicked
    textArea.setText("");
    description = "About this program. (See pop-up)";
    coolWindow();
    else if (submit.equals(cmd))
    if (cFrom.getText().equals("")||cTo.getText().equals("")||cSubject.getText().equals("")||cMessage.getText().equals(""))
    textArea.setText("One or more of the fields was not filled in.");
    else{
    try {
    String smtpServer="serverhere";
    String to=cTo.getText();
    String from=cFrom.getText();
    String subject=cSubject.getText();
    String body=cMessage.getText();
    send(smtpServer, to, from, subject, body);
    textArea.setText("");
    description = "Mail Sent.";
    JOptionPane.showMessageDialog(null, "Message Sent.");
    catch (Exception ex)
    System.out.println("Usage: java com.lotontech.mail.SimpleSender"
    +" smtpServer toAddress fromAddress subjectText bodyText");
    //CLOSE THE FRAME2 WINDOW IIIIIIIIFFFFFFF SENDING IS SUCCESSFUL!!
    }//end of else during send
    }//end of if of submit
    displayResult(description);
    //============================
    protected void displayResult(String actionDescription) {
    textArea.append(actionDescription + newline);
    //=============================
    public void coolWindow() {
    JFrame frame = new JFrame("About");
    JTextArea filecontents = new JTextArea();
    filecontents.setText("Use the tool bar to compose\n compose new emails, in which you can\n send to anyone on the\n srvhs email server. \n Fill in all the blanks before pressing send. If you dont\n you will receive an error! \n For more information about this program click on the\n information button.");
    frame.getContentPane().add(filecontents, BorderLayout.CENTER);
    frame.pack();
    frame.setResizable(false);
    frame.setSize(300,200);
    frame.setVisible(true);
    //===============================
    public void composeWindow() {
    frame2.getContentPane().setLayout(new GridBagLayout());
    frame2.setResizable(false);
    frame2.setSize(600,500);
    frame2.setVisible(true);
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.insets = new Insets(5, 10, 5, 10);
    cMessage.setLineWrap(true);
    subbutton = makeNavigationButton("toolbarButtonGraphics/general/SendMail24.gif", submit,"submit","submit");
    addRow(gbc, lFrom, cFrom);
    addRow(gbc, lTo, cTo);
    addRow(gbc, lSubject, cSubject);
    addRow(gbc, lMessage, cMessage);
    addRow(gbc, lSubmit, subbutton);
    //===============================
    private void addRow(GridBagConstraints gbc, Component left, Component right) {
    gbc.gridx = GridBagConstraints.RELATIVE;
    gbc.gridy = GridBagConstraints.RELATIVE;
    gbc.gridheight = 1;
    gbc.gridwidth = 1;
    gbc.anchor = GridBagConstraints.EAST;
    frame2.getContentPane().add(left, gbc);
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    gbc.anchor = GridBagConstraints.WEST;
    frame2.getContentPane().add(right, gbc);
    frame2.pack();
    //=======================
    public static void send(String smtpServer, String to, String from, String subject, String body) {
    try {
    Properties props = System.getProperties();
    props.put("localhost", smtpServer);
    Session session = Session.getDefaultInstance(props, null);
    System.out.println(smtpServer);
    // -- Create a new message --
    Message msg = new MimeMessage(session);
    // -- Set the FROM and TO fields --
    msg.setFrom(new InternetAddress(from));
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
    // -- We could include CC recipients too --
    // if (cc != null)
    // msg.setRecipients(Message.RecipientType.CC
    // ,InternetAddress.parse(cc, false));
    // -- Set the subject and body text --
    msg.setSubject(subject);
    msg.setText(body);
    // -- Set some other header information --
    msg.setHeader("X-Mailer", "LOTONtechEmail");
    msg.setSentDate(new Date());
    // -- Send the message --
    Transport.send(msg);
    System.out.println("Message sent OK.");
    catch (Exception ex)
    ex.printStackTrace();
    public static void main(String[] args) {
    JFrame frame = new JFrame("EmailProg");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    EmailProg newContentPane = new EmailProg();
    newContentPane.setOpaque(true);
    frame.setContentPane(newContentPane);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    }

    The code to retrieve the messages from SMTP
    finally all working fine...
    thanx guys!!!
    package EmailProg;
    import javax.mail.*;
    import javax.mail.internet.*;
    import java.util.*;
    import java.io.*;
      * A simple email receiver class.
    public class SimpleReceiver
        * Main method to receive messages from the mail server specified
        * as command line arguments.
      public static void main(String args[])
        try
          String popServer=args[0];
          String popUser=args[1];
          String popPassword=args[2];
          receive(popServer, popUser, popPassword);
        catch (Exception ex)
          System.out.println("Usage: java com.mail.SimpleReceiver" +" popServer popUser popPassword");
        System.exit(0);
         * "receive" method to fetch messages and process them.
       public static void receive(String popServer, String popUser, String popPassword)
         Store store=null;
         Folder folder=null;
         try
           // -- Get hold of the default session --
           Properties props = System.getProperties();
           Session session = Session.getDefaultInstance(props, null);
           // -- Get hold of a POP3 message store, and connect to it --
           store = session.getStore("pop3");
           store.connect(popServer, popUser, popPassword);
           // -- Try to get hold of the default folder --
           folder = store.getDefaultFolder();
           if (folder == null) throw new Exception("No default folder");
           // -- ...and its INBOX --
           folder = folder.getFolder("INBOX");
           if (folder == null) throw new Exception("No POP3 INBOX");
           // -- Open the folder for read only --
           folder.open(Folder.READ_ONLY);
           // -- Get the message wrappers and process them --
           Message[] msgs = folder.getMessages();
           for (int msgNum = 0; msgNum < msgs.length; msgNum++)
             System.out.println(msgs[msgNum]);
         catch (Exception ex)
           ex.printStackTrace();
         finally
           // -- Close down nicely --
           try
             if (folder!=null) folder.close(false);
             if (store!=null) store.close();
           catch (Exception ex2) {ex2.printStackTrace();
      }

  • Jsp java-mail problem.............

    how to send an email from jsp page using java mail?like for submitting a form an email will be sent to the user email-id(the email-id is stored/match-ed in/from the database)???i m using tomcat 5.5 and netbeans 6.5.1...........so what should i do if dont want to use google smtp/pop3 port???

    import java.io.*;
    import java.net.InetAddress;
    import java.util.Properties;
    import java.util.Date;
    import javax.mail.*;
    import javax.mail.internet.*;
    * Demo app that shows how to construct and send an RFC822
    * (singlepart) message.
    * XXX - allow more than one recipient on the command line
    * @author Max Spivak
    * @author Bill Shannon
    public class msgsend {
        public static void main(String[] argv) {
         String  to, subject = null, from = null,
              cc = null, bcc = null, url = null;
         String mailhost = null;
         String mailer = "msgsend";
         String file = null;
         String protocol = null, host = null, user = null, password = null;
         String record = null;     // name of folder in which to record mail
         boolean debug = false;
         BufferedReader in =
                   new BufferedReader(new InputStreamReader(System.in));
         int optind;
          * Process command line arguments.
         for (optind = 0; optind < argv.length; optind++) {
             if (argv[optind].equals("-T")) {
              protocol = argv[++optind];
             } else if (argv[optind].equals("-H")) {
              host = argv[++optind];
             } else if (argv[optind].equals("-U")) {
              user = argv[++optind];
             } else if (argv[optind].equals("-P")) {
              password = argv[++optind];
             } else if (argv[optind].equals("-M")) {
              mailhost = argv[++optind];
             } else if (argv[optind].equals("-f")) {
              record = argv[++optind];
             } else if (argv[optind].equals("-a")) {
              file = argv[++optind];
             } else if (argv[optind].equals("-s")) {
              subject = argv[++optind];
             } else if (argv[optind].equals("-o")) { // originator
              from = argv[++optind];
             } else if (argv[optind].equals("-c")) {
              cc = argv[++optind];
             } else if (argv[optind].equals("-b")) {
              bcc = argv[++optind];
             } else if (argv[optind].equals("-L")) {
              url = argv[++optind];
             } else if (argv[optind].equals("-d")) {
              debug = true;
             } else if (argv[optind].equals("--")) {
              optind++;
              break;
             } else if (argv[optind].startsWith("-")) {
              System.out.println(
    "Usage: msgsend [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]");
              System.out.println(
    "\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]");
              System.out.println(
    "\t[-f record-mailbox] [-M transport-host] [-a attach-file] [-d] [address]");
              System.exit(1);
             } else {
              break;
         try {
              * Prompt for To and Subject, if not specified.
             if (optind < argv.length) {
              // XXX - concatenate all remaining arguments
              to = argv[optind];
              System.out.println("To: " + to);
             } else {
              System.out.print("To: ");
              System.out.flush();
              to = in.readLine();
             if (subject == null) {
              System.out.print("Subject: ");
              System.out.flush();
              subject = in.readLine();
             } else {
              System.out.println("Subject: " + subject);
              * Initialize the JavaMail Session.
             Properties props = System.getProperties();
             // XXX - could use Session.getTransport() and Transport.connect()
             // XXX - assume we're using SMTP
             if (mailhost != null)
              props.put("mail.smtp.host", mailhost);
             // Get a Session object
             Session session = Session.getInstance(props, null);
             if (debug)
              session.setDebug(true);
              * Construct the message and send it.
             Message msg = new MimeMessage(session);
             if (from != null)
              msg.setFrom(new InternetAddress(from));
             else
              msg.setFrom();
             msg.setRecipients(Message.RecipientType.TO,
                             InternetAddress.parse(to, false));
             if (cc != null)
              msg.setRecipients(Message.RecipientType.CC,
                             InternetAddress.parse(cc, false));
             if (bcc != null)
              msg.setRecipients(Message.RecipientType.BCC,
                             InternetAddress.parse(bcc, false));
             msg.setSubject(subject);
             String text = collect(in);
             if (file != null) {
              // Attach the specified file.
              // We need a multipart message to hold the attachment.
              MimeBodyPart mbp1 = new MimeBodyPart();
              mbp1.setText(text);
              MimeBodyPart mbp2 = new MimeBodyPart();
              mbp2.attachFile(file);
              MimeMultipart mp = new MimeMultipart();
              mp.addBodyPart(mbp1);
              mp.addBodyPart(mbp2);
              msg.setContent(mp);
             } else {
              // If the desired charset is known, you can use
              // setText(text, charset)
              msg.setText(text);
             msg.setHeader("X-Mailer", mailer);
             msg.setSentDate(new Date());
             // send the thing off
             Transport.send(msg);
             System.out.println("\nMail was sent successfully.");
              * Save a copy of the message, if requested.
             if (record != null) {
              // Get a Store object
              Store store = null;
              if (url != null) {
                  URLName urln = new URLName(url);
                  store = session.getStore(urln);
                  store.connect();
              } else {
                  if (protocol != null)          
                   store = session.getStore(protocol);
                  else
                   store = session.getStore();
                  // Connect
                  if (host != null || user != null || password != null)
                   store.connect(host, user, password);
                  else
                   store.connect();
              // Get record Folder.  Create if it does not exist.
              Folder folder = store.getFolder(record);
              if (folder == null) {
                  System.err.println("Can't get record folder.");
                  System.exit(1);
              if (!folder.exists())
                  folder.create(Folder.HOLDS_MESSAGES);
              Message[] msgs = new Message[1];
              msgs[0] = msg;
              folder.appendMessages(msgs);
              System.out.println("Mail was recorded successfully.");
         } catch (Exception e) {
             e.printStackTrace();
         * Read the body of the message until EOF.
        public static String collect(BufferedReader in) throws IOException {
         String line;
         StringBuffer sb = new StringBuffer();
         while ((line = in.readLine()) != null) {
             sb.append(line);
             sb.append("\n");
         return sb.toString();
    }now what should i do???to call it from jsp???

  • Java.lang.Process output stream problem

    Hi, I have a program that starts a process (java.lang.Process) using the java.lang.Runtime.exec() and it attemtps to interface with it using the provieded io streams. I have both the output and error streams being handled on their own threads and I have a hashmap of output lines/command pairs that are checked so that when the process outputs certain lines to the console it feed the proper input into the process. My problem is that when I feed the input into the process it dosen't respond to it almost like the user hasn't pressed enter, The process hangs. I have tried using /n /r and permutations thereof but nothing works. The thread does read the lines from the process and does output to the process from what i can gather. Can you help me!
    here is some of the code..
    public void run() {
    try {
         //the process's output
         InputStreamReader isrOutput = new InputStreamReader(inOutput);
         //the process's input(our output)
         PrintWriter pw = new PrintWriter(outInput);
         String line = null;
         while(true){
              if(brOutput.ready()){
                   line = "";
                   while(brOutput.ready())
         line+=(char)brOutput.read();
                   System.out.print(line);
                   if(commands.containsKey(line)){
         pw.println((String)commands.get(line));
         System.out.println((String)commands.get(line));;
    } catch (IOException ioe) {
              ioe.printStackTrace();
    }Thanks

    Oops.. i forgot to flush my PrintWriter /blushing......... Thanks

  • Java mail api - sending mails to gmail account

    Hello
    I am using java mail api to send mails.when i send mails to gmail from ids which are not in gmail friends list, most of the mails are going to spam.Ofcourse, some of them go to inbox.I tried in lot of ways to analyse the problem.But nothing could help. Can anyone plzz tell me how to avoid mails going to spam in gmail, using java mail api?
    Thank you in advance,
    Regards,
    Aradhana
    Message was edited by:
    Aradhana

    am using the below code.
    Properties props = System.getProperties();
    //          Setup mail server
              props.put("mail.smtp.host", smtpHost);
              props.put("mail.smtp.port","25");
              props.put("mail.smtp.auth", isAuth);
         Authenticator auth = new UserAuthenticator();
    //          Get session
              Session s = Session.getDefaultInstance(props,auth);
    //          Define message
              Message m = new MimeMessage(s);
    //          setting message attributes
              try {
                   m.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
                   InternetAddress f_addr=new InternetAddress(from);
                   f_addr.setPersonal(personalName);
                   m.setFrom(f_addr);               
                   m.setSubject(subject);
                   m.setSentDate(new Date());
                   m.setContent(msg,"text/plain");
                   m.saveChanges();
    //               send message
                   Transport.send(m);
    Message was edited by:
    Aradhana

  • Can java mail be used for distributed exchange server?

    H,
    I am trying to connect to MS Exchange Server to read my mails using Java Mail API.
    I have a questions about using it with Exchange server.
    We have 6-7 exchange servers in our company and different users have mailboxes on different servers. My internet mail application will be used by everybody in the company.
    But while connecting to exchange server using java mail I can only cnnnect to one server and port. What happens when user mailbox is not on that server. How can I use javamail in this scenario where user mailboxes are on separate servers??
    Thanks
    [email protected]

    You said that you can connect to Exchange server my you help me with this because i cant connect to Exchange server, mayby you can post me a code example? Thanks

  • How can i access gmail's smtp server using java mail api

    i m using java mail api to access gmails pop and smtp service to receive and send mail from ur gmail account. I m able to access gmails pop server using the ssl and port 995 , but i can not use its smtp server to which i m connecting using ssl on 465 port. It requires authentication code.
    if anybody can help me in this regard i m thnkful to him/her.
    thnks in advance.
    jogin desai

    Here's an example of using SSL + Authentication
    http://onesearch.sun.com/search/onesearch/index.jsp?qt=ssl+authentication&subCat=siteforumid%3Ajava43&site=dev&dftab=siteforumid%3Ajava43&chooseCat=javaall&col=developer-forums

  • How to delete message from the fodler of  AOL account using Java mail

    Hello All,
    I am using Java MAil API in my application, i want to delete message from AOL account's folder,
    when i set the folder as "Recently Deleted" or "Trash" , i get an exception as "folder does not exist".
    when i tested , some times mail is moving into Recently Deleted folder, but not every time.
    this is happening in both the interface as AOl Interface or my application.
    when i use folder.close(true) after setting the flag of message as DELETED. it completely remove the message from the acount.
    but i want to let the message be remained in the Recently Deleted folder. what should i do.
    i dont want to remove the message completely from the account.I am using IMAP also.

    You'll need to figure out what the real name of the "Recently Deleted" folder is on the AOL IMAP server
    (assuming it's a real folder and not some sort of "virtual" folder), then copy the message into that folder.
    See the folderlist.java demo program as a way to explore the names of all the folders on the server.

Maybe you are looking for

  • Different row heights in one table - is this possible?

    I want the height of each row in a table to be set to fit the contents of that particular row. The column which drives the cell height uses the cell formatting options "Wrap Text" and "Row by Row Auto Fit". These options will set the row height of al

  • I don't know BIOS password for Satellite A100-528 PSAA2E

    hi..i have a problem... i have a laptop Toshiba SATELLITE A100-528 PSAA2E-01H00WGE.... the problem is that i downloaded toshiba HW setup and i accidentaly set a password.. .not a user password....it's propably supervisor password or bios password...

  • Windows 8 and iPhone stopped synching - why would that be?

    Windows 8 and iPhone stopped synching - why would that be? I never get the opportunity to specify a device. Used to work.

  • DVI-I Compatible?

    I understand that all of these monitors are DVI digital compatible which is known as DVI-D. Though I am curious if it also analog compatible (VGA). This is known as DVI-I digital and analog. Of course, there's only a DVI input on these monitors. If i

  • Do I have to use a login password?

    Do I have to use a login password?  If not, how can I change the setting so I'm not required to enter it each time I log on? Thanks!