Java Mail Demo - msgsend.java

I have placed the 2 files into the following directories
and updated the classpath as follows
c:\j2sdk1.4.0_02\jre\lib\ext\mail.jar
c:\j2sdk1.4.0_02\jre\lib\ext\activation.jar
CLASSPATH = C:\j2sdk1.4.0_02\jre\lib\extmail.jar; C:\j2sdk1.4.0_02\jre\lib\ext\activation.jar
The program compiles fine but when I go to run it says:
Exception in thread "main" java.lang.NoClassDefFoundError: msgsend
I have made no changes to the code, and my claspath seems correct. Any ideas?

The class that could not be found was the msgsend.class not the ones in the jar files. The jar files were pathed fine since you were able to compile the class. The reason you were getting the error was because the local directory was not in the classpath.
I specify the local directory by adding a period (c:/some.jar;.) to the end of the classpath in the environment variables in Windows and set it in the shell script I use to execute with in Linux.
I believe that setting the classpath from the command line will automatically include the directory you are currently in which would explain how you got it to work.

Similar Messages

  • 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 program in java

    Hi,
    Can anybody suggest me the java code which sends mails using java mail api?
    Thanks & Regards,
    Karimulla

    Hi
    I have worked on it,so if you need code for the application,please write mail to me on my address [email protected]
    hopes u will get gud solution.
    cheers
    Sandy

  • JSP & Java Mail

    Hai Buddies,
    I don't know about JSP (only little bit), Iwant to create a page in jsp any one plzzz help me i will give the details about the the page ie given below..
    The page containning
    --number, name contacts, comments ,action plan,dre name,lead name
    --when i stores the above details to the database a mail is sent to the dre and the lead respectively
    --Using JSP & Java Mail                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    There is a forum on java database connectivity
    http://forum.java.sun.com/forum.jspa?forumID=48
    A forum on java mail
    http://forum.java.sun.com/forum.jspa?forumID=43
    There are loads of tutorials on the sun site and elsewhere, you need to read these and start coding. No-one is going to write this for you.
    Before posting questions use the search bar to the left, most of the questions you ask have been dealt with MANY times before, you will find code quickly using the search facility, saving you a lot of time.

  • Java Mail - Small problem

    I've just installed Javamail and I've gotten the demo servlet working. However I've compiled my own Javamail servlet, but it doesn't seem to be working. It compiles correctly, but it doesn't send the email. I have the correct settings for the SMTP and I was told, since I'm using my own computer, "localhost" would do for the name of the SMTP server. They both compile correctly and I've the mail server address I have is correct. Any ideas?
    package email12;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.mail.*;
    import business.User;
    import data.UserIO;
    import util.MailUtil;
    public class EmailServlet extends HttpServlet{
    public void doPost(HttpServletRequest request,
    HttpServletResponse response)
    throws IOException, ServletException{
    String emailAddress = "[email protected]";
    String firstName = "Noel";
    String to = "[email protected]";
    String from = "[email protected]";
    String subject = "Test Email";
    String message = "Dear " + firstName + ",\n" +
    "This is a test email";
    try{
    MailUtil.sendMail(to, from, subject, message);
    catch (MessagingException me){
    log("MessagingException: " + emailAddress);
    log(me.toString());
    RequestDispatcher dispatcher =
    getServletContext().getRequestDispatcher(
    "/email11/show_email_entry.jsp");
    dispatcher.forward(request, response);
    package util;
    import javax.mail.*;
    import javax.mail.internet.*;
    import java.util.*;
    public class MailUtil{
    public static void sendMail(String to, String from,
    String subject, String messageText)
    throws MessagingException{
    // 1 - get a mail session
    Properties props = new Properties();
    props.put("mail.whatever.ie", "localhost");
    Session session = Session.getDefaultInstance(props);
    // 2 - create a message
    MimeMessage message = new MimeMessage(session);
    message.setSubject(subject);
    message.setText(messageText);
    // 3 - address the message
    InternetAddress fromAddress = new InternetAddress(from);
    InternetAddress toAddress = new InternetAddress(to);
    message.setFrom(fromAddress);
    message.setRecipient(Message.RecipientType.TO, toAddress);
    // 4 - send the message
    Transport.send(message);
    }

    But how come when I use the demo program which comes in the Javamail-1.3 folder, it sends the email for me. So wouldn't that mean that there is a smtp server running? This is where the demo is and how it runs:
    http://java.sun.com/developer/onlineTraining/JavaMail/exercises/MailSetup/index.html
    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) {
         new msgsend(argv);
    public msgsend(String[] argv) {
         String to, subject = null, from = null,
              cc = null, bcc = null, url = null;
         String mailhost = null;
         String mailer = "msgsend";
         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;
         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("-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] [-d] [address]");
              System.exit(1);
         } else {
              break;
         try {
         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);
         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.getDefaultInstance(props, null);
         if (debug)
              session.setDebug(true);
         // construct the message
         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);
         collect(in, msg);
         msg.setHeader("X-Mailer", mailer);
         msg.setSentDate(new Date());
         // send the thing off
         Transport.send(msg);
         System.out.println("\nMail was sent successfully.");
         // Keep a copy, 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();
    public void collect(BufferedReader in, Message msg)
                             throws MessagingException, IOException {
         String line;
         StringBuffer sb = new StringBuffer();
         while ((line = in.readLine()) != null) {
         sb.append(line);
         sb.append("\n");
         // If the desired charset is known, you can use
         // setText(text, charset)
         msg.setText(sb.toString());
    }

  • First Java Mail Program...some problems

    Hi Friends,
    I am new to JavaMail and i am trying to follow the following exercise:
    http://java.sun.com/developer/onlineTraining/JavaMail/exercises/MailSetup/
    I am using rogers high speed internet connection,so i enter the following:
    D:\JAVAWORLD\javamail1.3.2-src\src\share\classes\demo>java msgsend -o [email protected] -M smtp.broadband.rogers.com [email protected]
    To: [email protected]
    Subject: hi
    Welcome
    ^ZI get the following error:
    com.sun.mail.smtp.SMTPSendFailedException: 530 authentication required - for hel
    p go to http://help.yahoo.com/help/us/mail/pop/pop-11.html
            at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:1
    275)
            at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:895)
            at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:524)
            at javax.mail.Transport.send0(Transport.java:151)
            at javax.mail.Transport.send(Transport.java:80)
            at msgsend.main(msgsend.java:165)When i went to that yahoo link for help,there are no settings for command line.Please tell me how to accomplish this..friends

    Thanks Ananda,
    But i guess,i should be able to access the rogers smtp server,because i have them as my isp.Moreover,it works fine with my outlook too.I even tried to use a free smtp server called "dumbster",i downladed it but i dont know how to use it.If anyone has some idea,please let me know.
    Thanks

  • Java Mail - newbie

    Hi All,
    I am a new bie to java mail, i am trying to run the msgsend.java in the demo. I am using eclipse and i have added the activation.jar and mail.jar in the classpath. still it says unable to resolve javax.mail.*
    can anyone help me
    Thanks in Advance
    Regards,
    Venki

    I know nothing about Eclipse...
    You probably need to add the jar files to your project or something
    like that, rather than just adding them to the classpath when you
    start Eclipse. You can also try putting them in the jre/lib/ext directory
    of the JDK that Eclipse is using.

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

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

  • How to use a progress bar with java mail?

    Hi, i'm new here.
    I want if someone can recommend me how to show a progress bar with java mail.
    Because, i send a message but the screen freeze, and the progress bar never appear, after the send progress finish.
    Thanks

    So why would the code we post be any different than the code in the tutorial? Why do you think our code would be easier to understand? The tutorial contains explanations about the code.
    Did you download the code and execute it? Did it work? Then customize the code to suit your situation. We can't give you the code because we don't know exactly what you are attempting to do. We don't know how you have changed to demo code so that it no longer works. Its up to you to compare your code with the demo code to see what the difference is.

  • Java mail api

    I currently downloaded the appropriate programs to use the Mail api however when i compile the messagesend in the demos folder i get an error saying javax.mail does not exist. I'm also having a problem setting up my class path in Systems/Evirnonment. My current path is ;d:\IBMVJava\eab\runtime30;d:\IBMVJava\eab\runtime20;d:\jsdk2.1;d:\jsdk2.1\servlet.jar;d:\jsdk2.1\server.jar;d:\oracle\ora81\jdbc\lib\classes12.zip;d:\ol304\learning;d:\ol316\Support\servlet.jar;%ol311_root%;%ol311_root%\ch06;%ol311_root%\ch07;%/TOMCAT_HOME%\lib\servlet.jar\ Where in this path do in insert ".;D:\Java\javamail-1.2\mail.jar;D:\Java\jaf-1.0.1\activation.jar".

    Thanks for the classpath information regarding the .jar files. Now when I start tomcat cat it runs appropriately. However I am still having a problem when i try to compile the message send demo. The message I get is javax.mail does not exist,(import javax.mail.) when I downloade the mail api I placed on the root of my D drive and i placed the mail and activation jar files in my lib folded of my Jakarta-3.2.1 lib folder. I graduated Chubb Institute back in october and am currently still looking for work so my memory but be a little fuzzy as to whether or not this is correct. Your help is greatly appreciated.

  • Complete working code for Gmail POP3 & SMTP with SSL - Java mail API

    Finally, your code-hunt has come to an end!!!!
    I am presenting you the complete solution (with code) to send and retrieve you mails to & from GMAIL using SMTP and POP3 with SSL & Authenticaion enabled. [Even starters & newbies like me, can easy try, test & understand - But first download & add JAR's of Java Mail API & Java Activation Framework to Netbeans Library Manager]
    Download Java Mail API here
    http://java.sun.com/products/javamail/
    Read Java Mail FAQ's here
    http://java.sun.com/products/javamail/FAQ.html
    Download Java Activation Framework [JAF]
    http://java.sun.com/products/javabeans/jaf/downloads/index.html
    Also, The POP program retrieves the mail sent with SMTP program :) [MOST IMPORTANT & LARGELY IN DEMAND]okey.. first things first... all of your thanks goes to the following and not a s@!te to me :)
    hail Java !!
    hail Java mail API !!
    hail Java forums !!
    hail Java-tips.org !!
    hail Netbeans !!
    Thanks to all coders who helped me by getting the code to work in one piece.
    special thanks to "bshannon" - The dude who runs this forum from 97!!I am just as happy as you will be when you execute the below code!! [my 13 hours of tweaking & code hunting has paid off!!]
    Now here it is...I only present you the complete solution!!
    START OF PROGRAM 1
    SENDING A MAIL FROM GMAIL ACCOUNT USING SMTP [STARTTLS (SSL)] PROTOCOL OF JAVA MAIL APINote on Program 1:
    1. In the code below replace USERNAME & PASSWORD with your respective GMAIL account username and its corresponding password!
    2. Use the code to make your Gmail client [jsp/servlets whatever]
    //Mail.java - smtp sending starttls (ssl) authentication enabled
    //1.Open a new Java class in netbeans (default package of the project) and name it as "Mail.java"
    //2.Copy paste the entire code below and save it.
    //3.Right click on the file name in the left side panel and click "compile" then click "Run"
    import javax.mail.*;
    import javax.mail.internet.*;
    import java.util.*;
    public class Main
        String  d_email = "[email protected]",
                d_password = "PASSWORD",
                d_host = "smtp.gmail.com",
                d_port  = "465",
                m_to = "[email protected]",
                m_subject = "Testing",
                m_text = "Hey, this is the testing email.";
        public Main()
            Properties props = new Properties();
            props.put("mail.smtp.user", d_email);
            props.put("mail.smtp.host", d_host);
            props.put("mail.smtp.port", d_port);
            props.put("mail.smtp.starttls.enable","true");
            props.put("mail.smtp.auth", "true");
            //props.put("mail.smtp.debug", "true");
            props.put("mail.smtp.socketFactory.port", d_port);
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.socketFactory.fallback", "false");
            SecurityManager security = System.getSecurityManager();
            try
                Authenticator auth = new SMTPAuthenticator();
                Session session = Session.getInstance(props, auth);
                //session.setDebug(true);
                MimeMessage msg = new MimeMessage(session);
                msg.setText(m_text);
                msg.setSubject(m_subject);
                msg.setFrom(new InternetAddress(d_email));
                msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));
                Transport.send(msg);
            catch (Exception mex)
                mex.printStackTrace();
        public static void main(String[] args)
            Main blah = new Main();
        private class SMTPAuthenticator extends javax.mail.Authenticator
            public PasswordAuthentication getPasswordAuthentication()
                return new PasswordAuthentication(d_email, d_password);
    END OF PROGRAM 1-----
    START OF PROGRAM 2
    RETRIVE ALL THE MAILS FROM GMAIL INBOX USING Post Office Protocol POP3 [SSL] PROTOCOL OF JAVA MAIL APINote:
    1.Log into your gmail account via webmail [http://mail.google.com/]
    2.Click on "settings" and select "Mail Forwarding & POP3/IMAP"
    3.Select "enable POP for all mail" and "save changes"
    4.In the code below replace USERNAME & PASSWORD with your respective GMAIL account username and its corresponding password!
    PROGRAM 2 - PART 1 - Main.java
    //1.Open a new Java class file in the default package
    //2.Copy paste the below code and rename it to Mail.java
    //3.Compile and execute this code.
    public class Main {
        /** Creates a new instance of Main */
        public Main() {
         * @param args the command line arguments
        public static void main(String[] args) {
            try {
                GmailUtilities gmail = new GmailUtilities();
                gmail.setUserPass("[email protected]", "PASSWORD");
                gmail.connect();
                gmail.openFolder("INBOX");
                int totalMessages = gmail.getMessageCount();
                int newMessages = gmail.getNewMessageCount();
                System.out.println("Total messages = " + totalMessages);
                System.out.println("New messages = " + newMessages);
                System.out.println("-------------------------------");
    //Uncomment the below line to print the body of the message. Remember it will eat-up your bandwidth if you have 100's of messages.            //gmail.printAllMessageEnvelopes();
                gmail.printAllMessages();
            } catch(Exception e) {
                e.printStackTrace();
                System.exit(-1);
    END OF PART 1
    PROGRAM 2 - PART 2 - GmailUtilities.java
    //1.Open a new Java class in the project (default package)
    //2.Copy paste the below code
    //3.Compile - Don't execute this[Run]
    import com.sun.mail.pop3.POP3SSLStore;
    import java.io.File;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Date;
    import java.util.Properties;
    import javax.mail.Address;
    import javax.mail.FetchProfile;
    import javax.mail.Flags;
    import javax.mail.Folder;
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.Multipart;
    import javax.mail.Part;
    import javax.mail.Session;
    import javax.mail.Store;
    import javax.mail.URLName;
    import javax.mail.internet.ContentType;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeBodyPart;
    import javax.mail.internet.ParseException;
    public class GmailUtilities {
        private Session session = null;
        private Store store = null;
        private String username, password;
        private Folder folder;
        public GmailUtilities() {
        public void setUserPass(String username, String password) {
            this.username = username;
            this.password = password;
        public void connect() throws Exception {
            String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
            Properties pop3Props = new Properties();
            pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
            pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false");
            pop3Props.setProperty("mail.pop3.port",  "995");
            pop3Props.setProperty("mail.pop3.socketFactory.port", "995");
            URLName url = new URLName("pop3", "pop.gmail.com", 995, "",
                    username, password);
            session = Session.getInstance(pop3Props, null);
            store = new POP3SSLStore(session, url);
            store.connect();
        public void openFolder(String folderName) throws Exception {
            // Open the Folder
            folder = store.getDefaultFolder();
            folder = folder.getFolder(folderName);
            if (folder == null) {
                throw new Exception("Invalid folder");
            // try to open read/write and if that fails try read-only
            try {
                folder.open(Folder.READ_WRITE);
            } catch (MessagingException ex) {
                folder.open(Folder.READ_ONLY);
        public void closeFolder() throws Exception {
            folder.close(false);
        public int getMessageCount() throws Exception {
            return folder.getMessageCount();
        public int getNewMessageCount() throws Exception {
            return folder.getNewMessageCount();
        public void disconnect() throws Exception {
            store.close();
        public void printMessage(int messageNo) throws Exception {
            System.out.println("Getting message number: " + messageNo);
            Message m = null;
            try {
                m = folder.getMessage(messageNo);
                dumpPart(m);
            } catch (IndexOutOfBoundsException iex) {
                System.out.println("Message number out of range");
        public void printAllMessageEnvelopes() throws Exception {
            // Attributes & Flags for all messages ..
            Message[] msgs = folder.getMessages();
            // Use a suitable FetchProfile
            FetchProfile fp = new FetchProfile();
            fp.add(FetchProfile.Item.ENVELOPE);       
            folder.fetch(msgs, fp);
            for (int i = 0; i < msgs.length; i++) {
                System.out.println("--------------------------");
                System.out.println("MESSAGE #" + (i + 1) + ":");
                dumpEnvelope(msgs);
    public void printAllMessages() throws Exception {
    // Attributes & Flags for all messages ..
    Message[] msgs = folder.getMessages();
    // Use a suitable FetchProfile
    FetchProfile fp = new FetchProfile();
    fp.add(FetchProfile.Item.ENVELOPE);
    folder.fetch(msgs, fp);
    for (int i = 0; i < msgs.length; i++) {
    System.out.println("--------------------------");
    System.out.println("MESSAGE #" + (i + 1) + ":");
    dumpPart(msgs[i]);
    public static void dumpPart(Part p) throws Exception {
    if (p instanceof Message)
    dumpEnvelope((Message)p);
    String ct = p.getContentType();
    try {
    pr("CONTENT-TYPE: " + (new ContentType(ct)).toString());
    } catch (ParseException pex) {
    pr("BAD CONTENT-TYPE: " + ct);
    * Using isMimeType to determine the content type avoids
    * fetching the actual content data until we need it.
    if (p.isMimeType("text/plain")) {
    pr("This is plain text");
    pr("---------------------------");
    System.out.println((String)p.getContent());
    } else {
    // just a separator
    pr("---------------------------");
    public static void dumpEnvelope(Message m) throws Exception {       
    pr(" ");
    Address[] a;
    // FROM
    if ((a = m.getFrom()) != null) {
    for (int j = 0; j < a.length; j++)
    pr("FROM: " + a[j].toString());
    // TO
    if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
    for (int j = 0; j < a.length; j++) {
    pr("TO: " + a[j].toString());
    // SUBJECT
    pr("SUBJECT: " + m.getSubject());
    // DATE
    Date d = m.getSentDate();
    pr("SendDate: " +
    (d != null ? d.toString() : "UNKNOWN"));
    static String indentStr = " ";
    static int level = 0;
    * Print a, possibly indented, string.
    public static void pr(String s) {
    System.out.print(indentStr.substring(0, level * 2));
    System.out.println(s);
    }END OF PART 2
    END OF PROGRAM 2
    P.S: CHECKING !!
    STEP 1.
    First compile and execute the PROGRAM 1 with your USERNAME & PASSWORD. This will send a mail to your own account.
    STEP 2.
    Now compile both PART 1 & PART 2 of PROGRAM 2. Then, execute PART 1 - Main.java. This will retrive the mail sent in step 1. njoy! :)
    In future, I hope this is added to the demo programs of the Java Mail API download package.
    This is for 3 main reasons...
    1. To prevent a lot of silly questions being posted on this forum [like the ones I did :(].
    2. To give the first time Java Mail user with a real time working example without code modification [code has to use command line args like the demo programs - for instant results].
    3. Also, this is what google has to say..
    "The Gmail Team is committed to making sure you always can access your mail. That's why we're offering POP access and auto-forwarding. Both features are free for all Gmail users and we have no plans to charge for them in the future."
    http://mail.google.com/support/bin/answer.py?answer=13295
    I guess bshannon & Java Mail team is hearing this....
    Again, Hurray and thanks for helping me make it!! cheers & no more frowned faces!!
    (: (: (: (: (: GO JCODERS GO!! :) :) :) :) :)
    codeace
    -----                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    

    Thanks for the reply,
    I did checked by enabling session debuging and also checked pop settings it's enabled for all
    mails, I tried deleting some very old messages and now the message count is changed to 310.
    This may be the problem with gmail.
    Bellow is the output i got,
    DEBUG: setDebug: JavaMail version 1.4ea
    DEBUG: getProvider() returning javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc]
    DEBUG POP3: connecting to host "pop.gmail.com", port 995, isSSL false
    S: +OK Gpop ready for requests from 121.243.255.240 n22pf5432603pof.2
    C: USER [email protected]
    S: +OK send PASS
    C: PASS my_password
    S: +OK Welcome.
    C: STAT
    S: +OK 310 26900234
    Custom output: messageCount : 310
    C: QUIT
    S: +OK Farewell.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Extract Mail Attachment using Java Mail

    Hello Friends
    A day ago I entered into Java Mail , now I am able to send mail from my Java Program.
    The help I need from you is I wanna save the attachment coming in the mail using Java.
    For eg : a mail reched my Inbox contains .xls or .csv file which I wanna save to some place.
    Plss guide me to acheive this friends.
    Regards
    Vicky

    String host = "";
    String username = "";
    String password = "";
    String srcDir = "INBOX";
    String tarDir = "";
         String subject = "";
    String filepath = "C:/Documents and Settings/name/Desktop";
    String filename = "demo";
    Properties props = System.getProperties();
    props.put("mail.host", host);
    Session session = Session.getDefaultInstance(props, null);
    Store store = session.getStore("imap");
    store.connect(host, username, password);
    Folder folder = store.getFolder(srcDir);
              Folder dFolder = store.getFolder(tarDir);
    folder.open(Folder.READ_WRITE);
              Message message[] = folder.getMessages();
              java.util.Date yesterdayDate = new Date(System.currentTimeMillis() - 24*60*60*1000);
    for (int p = 0; p < message.length; p++) {
                   java.util.Date messageReceivedDate = message[p].getReceivedDate();
                   if(messageReceivedDate.after(yesterdayDate))
                        if (message[p].getSubject().equals(subject)) {
                             Multipart mp = (Multipart)(message[p].getContent());
                             for (int i = 0, n = mp.getCount(); i < n; i++) {
    Part part = mp.getBodyPart(i);
    String disposition = part.getDisposition();
    if ((disposition != null) && (disposition.equals("ATTACHMENT") || disposition.equals("INLINE")))) {
    String fullpath = filepath+"/" + filename+".csv";               
    File file = new File(fullpath);
    InputStream in = part.getInputStream();
    FileOutputStream fos = new FileOutputStream(file);
    byte[] buf = new byte[part.getSize()];
    int c = 0;
                             while ((c = in.read(buf)) != -1) {
    fos.write(buf, 0, c);
                                       in.close();
                                       fos.close();
                                  } // if (disposition) closing
                             }// inner for loop closing
    /* ----------------------------------------------------Move Message to new folder--------------------------------------------------------------------- */
    if (message.length != 0) {
    folder.copyMessages(message, dFolder);
    folder.setFlags(message, new Flags(Flags.Flag.DELETED), true);
    // Dump out the Flags of the moved messages, to insure that
    // all got deleted
    for (int i = 0; i < message.length; i++)
                                  if (!message.isSet(Flags.Flag.DELETED))
                                       System.out.println("Message # " + message[i] + " not deleted");
                             } //for
    }// if (message.length != 0)
    // System.out.println("*** Message moved to "+tarDir+" Directory ***");
                        }//if loop closing - checking message subject
                   }// if loop closing checking date
    }// outer for() loop closing

  • Problem installing java mail api1.4.1

    i installed javamail api1.4.1 by unzipping and setting the classpath for activation(of JAF) and mail(of JavaMail API).. but when i compile a sample program(progname is msgsend) which already exists in the mainAPI directory, i get a message saying-
    java.lang.NoClassDefFoundError: javaapplication13_email/msgsend
    Exception in thread "main"
    i'm not able to figure out the problem..

    I'm guessing you're a beginning Java programmer and you're confused about how directories
    and package names work.
    Did you put the source code in a "javaapplication13_email" directory? Did you modify the
    source code to add a "package javaapplication13_email;" statement?
    Are you using the command line "javac" program to compile?
    In the directory where msgsend.java is, using "javac msgsend.java" should compile it.
    If it's still not working for you, provide more details about what you're doing.

  • Want to send PDF as attachement using Java Mail

    HI,
    I am using Java mail API for sending PDF as attachment. Here is my sample code
    messageBodyPart = new MimeBodyPart();
    messageBodyPart.setDataHandler(new DataHandler("String data for PDF using iText", "text/plain" ));
    I am generating String for PDF file using iTEXT but I am unable to find out mimetype for passing into DataHandler as second paramete.
    Any idea?
    Thanks
    Shailesh

    Don't convert the data to String. It isn't text so
    you'll damage the binary content by doing that. In
    the "demos" directory of your JavaMail download
    you'll find a ByteArrayDataSource class you can use
    instead of a FileDataSource. Yes, this worked for me. I create the pdf in memory as as StringBuffer and I just changed the code from
    messageBodyPart.setDataHandler(new DataHandler(pdf.toString(), "application/pdf"));
    to
    messageBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(pdf.toString(), "application/pdf")));
    and it worked.
    Thanks a lot for your help,
    Dennis

Maybe you are looking for

  • Home sharing stops working

    Hi, For a while now Home Sharing has been broken for me.  It works when I first start iTunes but after a period of time I can no longer see the library through any of my devices, ATV, iPhone, iPad.  The amount of time before it stops working is incon

  • Connect MacBook 2010 to two external monitors

    I have a VGA cable that has an adapter that turns into USB and another one that is an adapter for an HDMI so it can go into my laptop. The one with the HDMI works, but the USB/VGA one doesn't work. Any suggestions?

  • How do i log into iCloud

    How do I log into iCloud and then look at all my photos uploaded?

  • Cache-flush VM-related performance issue

    Dear forum, I've got a peculiar performance issue going on with the BDB pagecache being flushed to disk. I've managed to reproduce the issue perfectly on three out of three quite different systems that I've tried on, so it is at least quite well-defi

  • Can i use an html signature with mail in SL?

    my company uses a standard html signature. is there a way that i can use it with mail app? how do i do that?