JavaMail - Pop3

Hi to all.
I have added mail.jar & activation.jar in my classpath
When i run my "msgshow" application (from demo of JavaMail) then i get following error.-----------
Exception in thread "main" java.lang.NoSuchMethodError
at com.sun.mail.pop3.Protocol.<init>(Protocol.java:57)
at com.sun.mail.pop3.POP3Store.getPort(POP3Store.java:108)
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:59)
at javax.mail.Service.connect(Service.java:227)
at javax.mail.Service.connect(Service.java:131)
at msgshow.main(msgshow.java:108)
Press any key to continue . . .
My code is here.
import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class msgshow {
static String protocol="pop3";
static String host = "host";
static String user = "uname";
static String password ="pasword";
static String mbox = "INBOX";
static String url = null;
static int port = -1;
static boolean verbose = false;
static boolean debug = false;
static boolean showStructure = false;
public static void main(String argv[]) {
int msgnum = 4;
     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("-v")) {
          verbose = true;
     } else if (argv[optind].equals("-D")) {
          debug = true;
     } else if (argv[optind].equals("-f")) {
          mbox = argv[++optind];
     } else if (argv[optind].equals("-L")) {
          url = argv[++optind];
     } else if (argv[optind].equals("-p")) {
          port = Integer.parseInt(argv[++optind]);
     } else if (argv[optind].equals("-s")) {
          showStructure = true;
     } else if (argv[optind].equals("--")) {
          optind++;
          break;
     } else if (argv[optind].startsWith("-")) {
          System.out.println(
"Usage: msgshow [-L url] [-T protocol] [-H host] [-p port] [-U user]");
          System.out.println(
"\t[-P password] [-f mailbox] [msgnum] [-v] [-D] [-s]");
          System.exit(1);
     } else {
          break;
try {
     if (optind < argv.length)
     msgnum = Integer.parseInt(argv[optind]);
     // Get a Properties object
     Properties props = System.getProperties();
     // Get a Session object
     Session session = Session.getDefaultInstance(props, null);
     session.setDebug(debug);
     // 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)
               System.out.println("host " + host + "port " + port + "\n user " + user + "\n password " + password);
          store.connect(host, user, password);
          System.out.println("afrer");
          else
          store.connect();
     // Open the Folder
     Folder folder = store.getDefaultFolder();
     if (folder == null) {
     System.out.println("No default folder");
     System.exit(1);
     folder = folder.getFolder(mbox);
     if (folder == null) {
     System.out.println("Invalid folder");
     System.exit(1);
     // 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);
     int totalMessages = folder.getMessageCount();
     if (totalMessages == 0) {
          System.out.println("Empty folder");
          folder.close(false);
          store.close();
          System.exit(1);
     if (verbose) {
          int newMessages = folder.getNewMessageCount();
          System.out.println("Total messages = " + totalMessages);
          System.out.println("New messages = " + newMessages);
          System.out.println("-------------------------------");
     if (msgnum == -1) {
          // Attributes & Flags for all messages ..
          Message[] msgs = folder.getMessages();
          // Use a suitable FetchProfile
          FetchProfile fp = new FetchProfile();
          fp.add(FetchProfile.Item.ENVELOPE);
          fp.add(FetchProfile.Item.FLAGS);
          fp.add("X-Mailer");
          folder.fetch(msgs, fp);
          for (int i = 0; i < msgs.length; i++) {
          System.out.println("--------------------------");
          System.out.println("MESSAGE #" + (i + 1) + ":");
          dumpEnvelope(msgs);
          // dumpPart(msgs[i]);
     } else {
          System.out.println("Getting message number: " + msgnum);
          Message m = null;
          try {
          m = folder.getMessage(msgnum);
          dumpPart(m);
          } catch (IndexOutOfBoundsException iex) {
          System.out.println("Message number out of range");
     folder.close(false);
     store.close();
     } catch (Exception ex) {
     System.out.println("Oops, got exception! " + ex.getMessage());
     ex.printStackTrace();
     System.exit(1);
public static void dumpPart(Part p) throws Exception {
     if (p instanceof Message)
     dumpEnvelope((Message)p);
     /** Dump input stream ..
     InputStream is = p.getInputStream();
     // If "is" is not already buffered, wrap a BufferedInputStream
     // around it.
     if (!(is instanceof BufferedInputStream))
     is = new BufferedInputStream(is);
     int c;
     while ((c = is.read()) != -1)
     System.out.write(c);
     pr("CONTENT-TYPE: " + p.getContentType());
     * 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("---------------------------");
     if (!showStructure)
          System.out.println((String)p.getContent());
     } else if (p.isMimeType("multipart/*")) {
     pr("This is a Multipart");
     pr("---------------------------");
     Multipart mp = (Multipart)p.getContent();
     level++;
     int count = mp.getCount();
     for (int i = 0; i < count; i++)
          dumpPart(mp.getBodyPart(i));
     level--;
     } else if (p.isMimeType("message/rfc822")) {
     pr("This is a Nested Message");
     pr("---------------------------");
     level++;
     dumpPart((Part)p.getContent());
     level--;
     } else if (!showStructure) {
     * If we actually want to see the data, and it's not a
     * MIME type we know, fetch it and check its Java type.
     Object o = p.getContent();
     if (o instanceof String) {
          pr("This is a string");
          pr("---------------------------");
          System.out.println((String)o);
     } else if (o instanceof InputStream) {
          pr("This is just an input stream");
          pr("---------------------------");
          InputStream is = (InputStream)o;
          int c;
          while ((c = is.read()) != -1)
          System.out.write(c);
     } else {
          pr("This is an unknown type");
          pr("---------------------------");
          pr(o.toString());
     } else {
     pr("This is an unknown type");
     pr("---------------------------");
public static void dumpEnvelope(Message m) throws Exception {
     pr("This is the message envelope");
     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"));
     // FLAGS
     Flags flags = m.getFlags();
     StringBuffer sb = new StringBuffer();
     Flags.Flag[] sf = flags.getSystemFlags(); // get the system flags
     boolean first = true;
     for (int i = 0; i < sf.length; i++) {
     String s;
     Flags.Flag f = sf[i];
     if (f == Flags.Flag.ANSWERED)
          s = "\\Answered";
     else if (f == Flags.Flag.DELETED)
          s = "\\Deleted";
     else if (f == Flags.Flag.DRAFT)
          s = "\\Draft";
     else if (f == Flags.Flag.FLAGGED)
          s = "\\Flagged";
     else if (f == Flags.Flag.RECENT)
          s = "\\Recent";
     else if (f == Flags.Flag.SEEN)
          s = "\\Seen";
     else
          continue;     // skip it
     if (first)
          first = false;
     else
          sb.append(' ');
     sb.append(s);
     String[] uf = flags.getUserFlags(); // get the user flag strings
     for (int i = 0; i < uf.length; i++) {
     if (first)
          first = false;
     else
          sb.append(' ');
     sb.append(uf[i]);
     pr("FLAGS: " + sb.toString());
     // X-MAILER
     String[] hdrs = m.getHeader("X-Mailer");
     if (hdrs != null)
     pr("X-Mailer: " + hdrs[0]);
     else
     pr("X-Mailer NOT available");
static String indentStr = " ";
static int level = 0;
* Print a, possibly indented, string.
public static void pr(String s) {
     if (showStructure)
     System.out.print(indentStr.substring(0, level * 2));
     System.out.println(s);
Thanks..
Bhavin Shah
Yuou can mail me at [email protected]

hello,
pass the run time arguments containing protocol, user name etc as specified.
Indrayani

Similar Messages

  • Hi javamail pop3 problem

    hello...
    i have a written code for retrieving mail from pop3 server...and its working fine except one problem....(if it is a problem)....
    when i retrieve mails i open outlook express and it again retrieves the same mails i have retirieved from my code....is this a normal behaviour as pop3 deletes all the retrieved messages....and when i first receive message using outlook my code is unable to find those messages .....so why this difference....should my code deliberately and explicitly delete messages after retrieving them or pop3 does it as its default behaviour....

    The emails on the POP3 server are not deleted from the server as they retrieved.
    In Outlook Express as well as in Outlook you can set the properties for your email account to leave a copy of the message on the server. The initial setting is to delete the message from the server as you retrieve it.
    In JavaMail in order to delete the email from the server you need to open the folder object for Read/Write, then to set the DELETED flag on the message to �true�;
    When you close the folder, deleted messages will be removed if you set the expunge parameter to �true�.
    As in the following code:
    Folder folder = store.getFolder("INBOX");
    folder.open(Folder.READ_WRITE);
    Message message = folder.getMessage(1);
    message.setFlag(Flags.Flag.DELETED, true);
    folder.close(true);

  • JavaMail Pop3 problems

    I am trying to read emails from a pop3 account. Even using the code provided by sun in the JavaMail examples directory, I can't seem to connect. I am getting this error:
    java.net.ConnectException: Connection refused: no further information
    at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:63)
    at javax.mail.Service.connect(Service.java:227)
    at msgshow.main(msgshow.java , Compiled Code)
    Can someone explain to me how to remedy this problem? Thank you in advance.
    Jimmy

    I have a similar problem . I want to extract the contents of the mail which is nothing but FORM ,with a set of KEY_VALUE pair to ACCESS.Can anybody help me with this issue?It is urgent!!!

  • Javamail - no pop3 provider

    Hello,
    i have a problem with the javamail-1.3.1 API within the Oracle 9i (9.2.0.3) on Linux.
    I would like to retrieve a POP3 account and process the incoming mails within a Java Stored Procedure.
    I uploaded the javamail classes (imap.jar, mailapi.jar, pop3.jar, smtp.jar and the acivation.jar) into my account with the loadjava tool ( -resolve). When i try now to connect to a pop3 account, i get the error:
    javax.mail.NoSuchProviderException: No provider for pop3
    On the terminal my function works properly, so i list the available javamail providers and notice that on the oracle 9i the pop3 provider is missing.
    my sourcecode fragment:
    Properties props = System.getProperties();
    Session session = Session.getDefaultInstance(props, null);
    Provider[] providers = session.getProviders();
    for (int z = 0; z < providers.length; z++)
    System.out.println (providers[z]);
    store = session.getStore("pop3"); // within the Oracle, i get here the above error
    terminal - provider list:
    javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsy stems, Inc]
    Oracle 9i - provider list:
    javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun
    Microsystems, Inc]
    Where is my pop3 provider and how can register my pop3 mail provider within the oracle 9i ?
    best regards
    Adam Caban

    Good job coming up with the workaround, verpixelt! I guess it seems that Apple's philosophy is to make it 'even that much easier' to setup an email account on the iphone in iOS5, however, my legacy email account is not IMAP, and yet it tried to create an IMAP account, which wreaked havoc on my ability to use my email account on my iphone. Your solution of setting up the account with the wrong password gave me the ability to make the IMAP/POP choice which then allowed my email account to function normally on my iPhone 4S. Thanks. 
    Apple, - please put the IMAP/POP selection option back in for email account setup on the iPhone. Thank you.

  • ADVANTAGES OF IMAP OVER POP3 IN JAVAMAIL

    Hi Everyone,
    Can any one explain me about the advantages of using IMAP over POP3 in JavaMail. I'll be greatly appreciate if anyone help me out.
    Thanks in advance,
    Chags

    dear
    i am also working on that,
    but still search the topic
    if u find plz reply me on [email protected]
    you can see also
    http://computer.org/proceedings/lcn/8141/81410545abs.htm
    with regards
    kashif

  • Javamail + smtp/pop3 servers

    Hi,
    I run the demo in the javamail-1.2. it worked but there is no mail received.
    I think the problem is with my smtp server.
    my smtp was 1st smtp, the program runs but I have the message : invalid adresse receiver.(all addresses : yahoo, private...)
    I changed it to surgemail wich is pop3 and smtp serevr mail. I have no error message but I didn't receive any mail.
    how to solve this problem?
    thank you for your time.

    maybe you need to be using smtp-auth... there is an example with javamail.

  • Whats SMTP/POP3  host server address in JavaMail

    Hello friends,
    I came to know that we could send mail through Java through JavaMail
    I downloaded some eg code ( for sending mail to some one )
    I downloaded the mail.jar and activation.jar (and put it in right palce where it was asked to)
    I am using java 1.6 SE
    what i could not understand is what is
    POP3 server
    SMTP server
    How / What to put server address in the code
    Please help me. Here is the below code
    import javax.mail.*;
    import javax.mail.internet.*;
    import javax.activation.*;
    import java.io.*;
    import java.util.Properties;
    public class MailClient
         public void sendMail(String mailServer, String from, String to,
                                 String subject, String messageBody,
                                 String[] attachments) throws
    MessagingException, AddressException
              // Setup mail server
             Properties props = System.getProperties();
             props.put("mail.smtp.host", mailServer);
             // Get a mail session
             Session session = Session.getDefaultInstance(props, null);
             // Define a new mail message
             Message message = new MimeMessage(session);
            /// System.out.println(" 1");
             message.setFrom(new InternetAddress(from));
             message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
             message.setSubject(subject);
             // Create a message part to represent the body text
             BodyPart messageBodyPart = new MimeBodyPart();
             messageBodyPart.setText(messageBody);
             //use a MimeMultipart as we need to handle the file attachments
             Multipart multipart = new MimeMultipart();
             //add the message body to the mime message
             multipart.addBodyPart(messageBodyPart);
             // add any file attachments to the message
             addAtachments(attachments, multipart);
             // Put all message parts in the message
             message.setContent(multipart);
             // Send the message
             Transport.send(message);
         protected void addAtachments(String[] attachments, Multipart multipart)
                         throws MessagingException, AddressException
             for(int i = 0; i<= attachments.length -1; i++)
                 String filename = attachments;
    MimeBodyPart attachmentBodyPart = new MimeBodyPart();
    //use a JAF FileDataSource as it does MIME type detection
    DataSource source = new FileDataSource(filename);
    attachmentBodyPart.setDataHandler(new DataHandler(source));
    //assume that the filename you want to send is the same as the
    //actual file name - could alter this to remove the file path
    attachmentBodyPart.setFileName(filename);
    //add the attachment
    multipart.addBodyPart(attachmentBodyPart);
    public static void main(String[] args)
    try
         MailClient client = new MailClient();
    String server="pop3.mydomain.com";
    String from="[email protected]";
    String to = "[email protected]";
    String subject="Test";
    String message="Testing";
    String[] filenames =
    {"c:\\somefile.txt"};
    client.sendMail(server,from,to,subject,message,filenames);
    System.out.println(" Mail Has been sent");
    catch(Exception e)
    e.printStackTrace(System.out);
    } and the error i get after running this is
    javax.mail.MessagingException: Could not connect to SMTP host: pop3.mydomain.com, port: 25;
      nested exception is:
         java.net.ConnectException: Connection timed out: connect
         at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1391)
         at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:412)
         at javax.mail.Service.connect(Service.java:288)
         at javax.mail.Service.connect(Service.java:169)
         at javax.mail.Service.connect(Service.java:118)
         at javax.mail.Transport.send0(Transport.java:188)
         at javax.mail.Transport.send(Transport.java:118)
         at MailClient.sendMail(MailClient.java:39)
         at MailClient.main(MailClient.java:76)
    Caused by: java.net.ConnectException: Connection timed out: connect
         at java.net.PlainSocketImpl.socketConnect(Native Method)
         at java.net.PlainSocketImpl.doConnect(Unknown Source)
         at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
         at java.net.PlainSocketImpl.connect(Unknown Source)
         at java.net.SocksSocketImpl.connect(Unknown Source)
         at java.net.Socket.connect(Unknown Source)
         at java.net.Socket.connect(Unknown Source)
         at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:233)
         at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)
         at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1359)
         ... 8 more
    Thanks                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    I followed ur Advice
    I got another code which works perfecty as i wanted
    this uses Gmail SMTP
    Thanks
    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);
    }

  • Javamail fetch returns string 'POP3'

    When I try to fetch mail, I only get the string 'POP3'.
    There is no exception generated.
    This worked fine in the past, does this have something to do with security.
    I'm lost.
    Thx. in advance.

    You might want to change your code, then. My crystal ball is not working right now so I can't make any suggestions about what part of your code you should look at.

  • Can we show pop3 output by java FX?

    suppose i hava a .java where i have code to access my pop3.can it be possible to show that INBOX in java FX window??

    <%@ page import="java.util.*, javax.mail.*, javax.mail.internet.*" %>
            <%
            Properties props = new Properties();
            //Properties props = System.getProperties();
    props.put("mail.pop3.host","pop3.gmail.com");
    // Setup authentication, get session
    props.put("mail.smtp.starttls.enable","true");
    Session sessions = Session.getInstance(props,
                        new javax.mail.Authenticator()
                   protected PasswordAuthentication getPasswordAuthentication()
                   { return new PasswordAuthentication("[email protected]","mogambo");     }
    // Get the store
    Store store = sessions.getStore("pop3s");
    store.connect("pop.gmail.com",995,"[email protected]","mogambo");
    Folder fd=store.getDefaultFolder().getFolder("INBOX");
    fd.open(Folder.READ_ONLY);
    Message [] msg=fd.getMessages();
    //store.connect();
    for(int i=0;i<msg.length;i++){
        out.write("m" + (i+1));
    //msg.writeTo(System.out);
    fd.close(false);
    store.close();
    %>
    look this code is serving the pupose of javamail...................now i want to shoe the massage in java FX which will be shown onClick a button say *"feed back"*
    now how can i do that i must pass the stored *Message* object to the java FX component...............if i am not wrong it is now the concern of java FX stuff.....
    becoz the stage area should be dinamic....................and my java mail object should be familiar with it..................
    Edited by: coolsayan.2009 on May 11, 2009 9:23 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Trying to send e-mail using JavaMail, JBoss 5, and JNDI

    Hello there,
    Am using JBoss 5.1.0GA and JDK 1.5.0_19 on OS X Leopard.
    Created a working SendMailServlet.
    Have now decided to refactor it into two separate classes (extract out JavaMail code to a separate class and create a ServletController).
    Am also trying to use JNDI to access the connection properties in the mail-service.xml configuration file residing in JBoss.
    The Mailer class contains the reusable functionality needed to send an e-mail:
    public class Mailer {
         private Session mailSession;
         protected void sendMsg(String email, String subject, String body)
         throws MessagingException, NamingException {
              Properties props = new Properties();
              InitialContext ictx = new InitialContext(props);
              Session mailSession = (Session) ictx.lookup("java:/Mail");
    //          Session mailSessoin = Session.getDefaultInstance(props);
              String username = (String) props.get("mail.smtps.user");
              String password = (String) props.get("mail.smtps.password");
              MimeMessage message = new MimeMessage(mailSession);
              message.setSubject(subject);
              message.setRecipients(javax.mail.Message.RecipientType.TO,
                        javax.mail.internet.InternetAddress.parse(email, false));
              message.setText(body);
              message.saveChanges();
              Transport transport = mailSession.getTransport("smtps");
              try {
                   transport.connect(username, password);
                   transport.sendMessage(message, message.getAllRecipients());
                   Logger.getLogger(this.getClass()).warn("Message sent");
              finally {
                   transport.close();
    }The MailController class serves as a standard Java Servlet which invokes the Mailer.class's sendMsg() method:
    public class MailController extends HttpServlet {
         /** static final HTML setting for content type */
         private static final String HTML = "text/html";
         myapp/** static final HTML setting for content type */
         private static final String PLAIN = "text/plain";
         public void doGet(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException {
              doPost(request, response);
         public void doPost(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException {
              response.setContentType(PLAIN);
              PrintWriter out = response.getWriter();
              String mailToken = TokenUtil.getEncryptedKey();
              String body = "Hello there, " + "\n\n"
                        + "Wanna play a game of golf?" + "\n\n"
                     + "Please confirm: https://localhost:8443/myapp/confirm?token="
                     + mailToken + "\n\n" + "-Golf USA";
              Mailer mailer = new Mailer();
              try {
                   mailer.sendMsg("[email protected]", "Golf Invitation!", body);
                   out.println("Message Sent");
              catch (MessagingException e) {
                   e.printStackTrace();
              catch (NamingException e) {
                   e.printStackTrace();
    }Have the mail configuration set under $JBOSS_HOME/server/default/deploy/mail-service.xml:
    <server>
      <mbean code="org.jboss.mail.MailService" name="jboss:service=Mail">
        <attribute name="JNDIName">java:/Mail</attribute>
        <attribute name="User">user</attribute>
        <attribute name="Password">password</attribute>
        <attribute name="Configuration">
          <configuration>
            <property name="mail.store.protocol" value="pop3"/>
            <property name="mail.transport.protocol" value="smtp"/>
            <property name="mail.user" value="user"/>
            <property name="mail.pop3.host" value="pop3.gmail.com"/>
            <property name="mail.smtp.host" value="smtp.gmail.com"/>
            <property name="mail.smtp.port" value="25"/>
            <property name="mail.from" value="[email protected]"/>
            <property name="mail.debug" value="true"/>
          </configuration>
        </attribute>
        <depends>jboss:service=Naming</depends>
      </mbean>
    </server>web.xml (Deployment Descriptor):
    <servlet>
        <servlet-name>MailController</servlet-name>
        <servlet-class>com.myapp.MailController</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>MailController</servlet-name>
        <url-pattern>/sendmail</url-pattern>
    </servlet-mapping>This is what is outputted when I start JBOSS and click point my browser to:
    https://localhost:8443/myapp/sendmail
    [MailService] Mail Service bound to java:/Mail
    [STDOUT] DEBUG: JavaMail version 1.4ea
    [STDOUT] DEBUG: java.io.FileNotFoundException:
    /System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Home/lib/javamail.providers
    (No such file or directory)
    [STDOUT] DEBUG: !anyLoaded
    [STDOUT] DEBUG: not loading resource: /META-INF/javamail.providers
    [STDOUT] DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
    [STDOUT] DEBUG: getProvider() returning
    javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc]
    [STDOUT] DEBUG SMTP: useEhlo true, useAuth false
    [STDOUT] DEBUG SMTP: trying to connect to host "localhost", port 465, isSSL true
    [STDERR] javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 465;
      nested exception is:
         java.net.ConnectException: Connection refused
    [STDERR]      at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1282)
    [STDERR]      at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370)
    [STDERR]      at javax.mail.Service.connect(Service.java:275)
    [STDERR]      at javax.mail.Service.connect(Service.java:156)
    [STDERR]      at javax.mail.Service.connect(Service.java:176)
    [STDERR]      at com.myapp.Mailer.sendMsg(Mailer.java:45)
    [STDERR]      at com.myapp.MailController.doPost(MailController.java:42)
    [STDERR]      at com.myapp.MailController.doGet(MailController.java:26)Why am I getting this java.net.ConnectException: Connection refused exception?
    Happy programming,
    Mike
    Edited by: mwilson72 on Aug 21, 2009 4:49 PM

    Hi Peter,
    Nice to hear from you again!
    Per your advice, this is what my mail-service.xml config file looks like now:
    <?xml version="1.0" encoding="UTF-8"?>
    <server>
      <mbean code="org.jboss.mail.MailService" name="jboss:service=Mail">
      <attribute name="JNDIName">java:/Mail</attribute>
      <attribute name="User">user</attribute>
      <attribute name="Password">password</attribute>
      <attribute name="Configuration">
         <configuration>
            <property name="mail.store.protocol" value="pop3"/>
         <property name="mail.transport.protocol" value="smtps"/>
            <property name="mail.smtp.starttls.enable" value="true"/>
            <property name="mail.smtps.auth" value="true"/> 
            <property name="mail.user" value="user"/>
            <property name="mail.pop3.host" value="pop3.gmail.com"/>
            <property name="mail.smtp.host" value="smtp.gmail.com"/>
            <property name="mail.smtps.port" value="465"/>
            <property name="mail.from" value="[email protected]"/>
            <property name="mail.debug" value="true"/>
         </configuration>
       </attribute>
       <depends>jboss:service=Naming</depends>
      </mbean>
    </server>Now, when I restart JBoss and point my browser to:
    https://localhost:8443/myapp/sendmail
    I get this exception:
    [STDOUT] DEBUG SMTP: useEhlo true, useAuth true
    [STDOUT] DEBUG SMTP: useEhlo true, useAuth true
    [STDOUT] DEBUG SMTP: trying to connect to host "localhost", port 465, isSSL true
    [STDERR] javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 465;
      nested exception is:
         java.net.ConnectException: Connection refused
    [STDERR] at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1282)
    [STDERR] at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370)
    [STDERR] at javax.mail.Service.connect(Service.java:297)
    [STDERR] at javax.mail.Service.connect(Service.java:156)
    [STDERR] at javax.mail.Service.connect(Service.java:176)
    [STDERR] at com.myapp.Mailer.sendMsg(Mailer.java:45)
    [STDERR] at com.myapp.MailController.doPost(MailController.java:42)
    [STDERR] at com.myapp.MailController.doGet(MailController.java:26)Does anyone know what I am possibly doing wrong? Is it my code or is it the config file?
    -Mike

  • Sending attachments with emails in Javamail

    I'm trying to send attachments with emails using Javamail. Following is the code through which I'm trying to achieve that. It works as expected on a JRE1.6 environment. But on JRE1.5, the content of the file gets added to the mail body as text.I want the file to be sent as an attachment.
    Any pointers on the observed difference in behavior would be highly appreciated!
    String msgText = mailInfo.getMessage();
            String attachmentFileName = mailInfo.getFileName();
            MimeBodyPart mimeBodyPart = new MimeBodyPart();
            mimeBodyPart.setText(msgText);
            // create the second message part
            MimeBodyPart attachmentBodyPart = new MimeBodyPart();
            // attach the file to the message
            FileDataSource fileDataSource = new FileDataSource(attachmentFileName);
            attachmentBodyPart.setFileName(fileDataSource.getName());
            attachmentBodyPart.setDataHandler(new DataHandler(fileDataSource));
            // create the Multipart and add its parts to it
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(mimeBodyPart);
            multipart.addBodyPart(attachmentBodyPart);
            message.setContent(multipart);The email in case of JRE1.5 is as follows
    {color:#0000ff}------=_Part_0_33189144.1233078680250
    Content-Type: text/plain; charset=us-ascii
    Content-Transfer-Encoding: 7bit
    Hi...Test Mail
    ------=_Part_0_33189144.1233078680250
    Content-Type: application/octet-stream; name=corba_architecture.pdf
    Content-Transfer-Encoding: base64
    Content-Disposition: attachment; filename=corba_architecture.pdf
    Content-ID: Attachment
    JVBERi0xLjIgDSXi48/TDQogDTggMCBvYmoNPDwNL0xlbmd0aCA5IDAgUg0vRmlsdGVyIC9GbGF0
    ZURlY29kZSANPj4Nc3RyZWFtDQpIiUWPW07DMBBFV+A93E9QlWBP/Kj5awt8USFRbyBKnTQIkshK
    YfvYcQoaybrSzDkzFhCxQgemeWkUyKTXEIeSHMGjZXvHSFBJCpXUpQLcE+NIlbCHFw4pUxeuZQUv
    ueY25gYxk9mKmH9wtwvNpZ99M1+jc2wxXzxweHvf73AP9xGFhaIsTyC3/w6ZDYfxaxoHP8w4jmf/
    ------=_Part_0_33189144.1233078680250-- {color}

    Following is the debug trace obtained on running the program on 1.5.
    +12:45:57,218 INFO [MailerThread] EmailManager:306 - Sending message {toAddress [email protected],+
    +replyTo =null,+
    +cc =null,+
    +message =Hi...Test Mail,+
    +subject =test mail,+
    +contentType =null fileName =C:\docs\cbe\dist computing\A.txt }+
    Loading javamail.default.providers from jar:file:/C:/docs/cbe/lib/mail-1.4.jar!/META-INF/javamail.default.providers
    DEBUG: loading new provider protocol=imap, className=com.sun.mail.imap.IMAPStore, vendor=Sun Microsystems, Inc, version=null
    DEBUG: loading new provider protocol=imaps, className=com.sun.mail.imap.IMAPSSLStore, vendor=Sun Microsystems, Inc, version=null
    DEBUG: loading new provider protocol=smtp, className=com.sun.mail.smtp.SMTPTransport, vendor=Sun Microsystems, Inc, version=null
    DEBUG: loading new provider protocol=smtps, className=com.sun.mail.smtp.SMTPSSLTransport, vendor=Sun Microsystems, Inc, version=null
    DEBUG: loading new provider protocol=pop3, className=com.sun.mail.pop3.POP3Store, vendor=Sun Microsystems, Inc, version=null
    DEBUG: loading new provider protocol=pop3s, className=com.sun.mail.pop3.POP3SSLStore, vendor=Sun Microsystems, Inc, version=null
    DEBUG: getProvider() returning provider protocol=smtp; type=javax.mail.Provider$Type@77eaf8; class=com.sun.mail.smtp.SMTPTransport; vendor=Sun Microsystems, Inc
    DEBUG SMTP: useEhlo true, useAuth false
    DEBUG SMTP: trying to connect to host "10.16.68.131", port 25, isSSL false
    +220 mailhost5.vmware.com ESMTP Postfix (mailhost5)+
    DEBUG SMTP: connected to host "10.16.68.131", port: 25
    EHLO sbanerjee
    +250-mailhost5.vmware.com+
    +250-PIPELINING+
    +250-SIZE 26800000+
    +250-VRFY+
    +250-ETRN+
    +250-ENHANCEDSTATUSCODES+
    +250-8BITMIME+
    +250 DSN+
    DEBUG SMTP: Found extension "PIPELINING", arg ""
    DEBUG SMTP: Found extension "SIZE", arg "26800000"
    DEBUG SMTP: Found extension "VRFY", arg ""
    DEBUG SMTP: Found extension "ETRN", arg ""
    DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
    DEBUG SMTP: Found extension "8BITMIME", arg ""
    DEBUG SMTP: Found extension "DSN", arg ""
    DEBUG SMTP: use8bit false
    MAIL FROM:<[email protected]>
    +250 2.1.0 Ok+
    RCPT TO:<[email protected]>
    +250 2.1.5 Ok+
    DEBUG SMTP: Verified Addresses
    DEBUG SMTP:   [email protected]
    DATA
    +354 End data with <CR><LF>.<CR><LF>+
    ------=_Part_0_3278348.1233126957281
    Content-Type: text/plain; charset=us-ascii
    Content-Transfer-Encoding: 7bit
    Hi...Test Mail
    ------=_Part_0_3278348.1233126957281
    Content-Type: text/plain; charset=us-ascii; name=A.txt
    Content-Transfer-Encoding: 7bit
    Content-Disposition: attachment; filename=A.txt
    Content-ID: Attachment
    adasdasdd
    ------=_Part_0_3278348.1233126957281--
    +.+
    +250 2.0.0 Ok: queued as 5BE5BDC100+
    +12:45:59,125 INFO [MailerThread] EmailManager:331 - Message {toAddress [email protected],+
    +replyTo =null,+
    +cc =null,+
    +message =Hi...Test Mail,+
    +subject =test mail,+
    +contentType =null fileName =C:\docs\cbe\dist computing\A.txt } sent to the SMTP server successfully+

  • Gettting attachments using JAVAMAIL

    Hi,
    I am dealing with an application which wants me to go through the mailbox and get the attachments of specific emails. These attachments are of different kinds. The attachments can vary from being rtf document, to Word, html, fo.. documents.. I got this skeleton code from the tutorial but dont know what to fill in..
    if (disposition == null) {
    // Check if plain
    MimeBodyPart mbp = (MimeBodyPart)part;
    if (mbp.isMimeType("text/plain")) {
    // Handle plain
    } else {
    // Special non-attachment cases here of
    // image/gif, text/html, ...
    What is it meant by handling plain? How do i handle html, worf, rtf documents.. Thanks a lot in advance.. Thanks
    Abhishek

    Try this as a reference. It works PERFECTLY. Ignore the comments.
    //If the content is ATTACHMENT
    filename = part.getFileName();
    if (filename != null) {
    filename = filename.trim();
    if(filename.equalsIgnoreCase(fileNameDownload.trim())) {
                                            //System.out.println("Downloading DOWN 1");
                                            session_id = this.DL_sessionid;
                                            directory = ATTACHMENTPath + m_user + "_" + session_id + "/";
                                            if(download) {
                                                 pushFile(part.getFileName(),part.getInputStream(),resp);
                                            } else {
                                                 saveFile(part.getFileName(), directory, part.getInputStream(), resp);
                                       filectr++;
         private void saveFile(String fileName, String Directory, InputStream input, HttpServletResponse resp)
              String myfile="";
              try
                   //Correct the file name;
                   String p_filename = javaFileParser(fileName);
                   File newDir = new File(Directory);
                   //Check if the directory does not exists!
                   if(!newDir.exists()) { //If it doesn't..
                        //Create the directory
                        newDir.mkdir();
                   String complete_path = Directory + p_filename;
                   File myFile=new File(complete_path);
                   //Check if a filename like this already exists!
                   if(myFile.exists()) {
                        //If it does..
                        //delete the current file residing into the directory
                        myFile.delete();
                   //Write the file (START)
                   FileOutputStream fos = new FileOutputStream(myFile);
                   BufferedOutputStream bos = new BufferedOutputStream(fos);
                   BufferedInputStream bis = new BufferedInputStream(input);
                   int aByte;
                   while ((aByte = bis.read()) != -1)
                   bos.write(aByte);
                   bos.flush();
                   bos.close();
                   bis.close();
                   //(END)
              catch (Exception x)
                   System.out.println("Error : " + x);
         private void pushFile(String fileName,InputStream input, HttpServletResponse resp)
              try
                   //Download the file to the Client's machine
                   ServletOutputStream stream = resp.getOutputStream();
                   resp.setContentType("application/octet-stream");
                   resp.setHeader("Content-Disposition","attachment;filename="+fileName.trim()+";");
                   //BufferedInputStream fif = new BufferedInputStream(new FileInputStream(complete_path));
                   BufferedInputStream fif = new BufferedInputStream(input);
                   int data;
                   while((data = fif.read()) != -1)
                   stream.write(data);
                   stream.flush();
                   fif.close();
                   stream.close();
              catch (Exception x)
                   System.out.println("Error : " + x);
         private String javaFileParser(String filename)
              //System.out.println("In EmailObject javaFileParser");
              String n_filename="";
              //Check if the file starts with '=?iso8859'
              //If it does, it will need parsing
              if(filename.startsWith("=?iso")) {
                   n_filename = filename.substring(15,filename.lastIndexOf("?"));
              } else
                   n_filename = filename;
              return n_filename;
    I suggest don't use JavaMail.. It has BUGS on some other email type. If not in POP3 then in IMAP.. Specialy when it receives "Enriched" contents types. Better yet don't use Java. It has lots of Bugs.

  • How to run the Program given in JavaMail 1.4 Demos (folderlist.java)

    Hi All,
    in the distribution of JavaMail 1.4, some programs are given, i want to run folderlist.java. But i m unable to run it? Can somebody tell me how to run it?
    i tried like this:
    java folderlist -T IMAP -H email.abcdef.com -U user -P password
    java folderlist -T POP -H email.abcdef.com -U user -P password
    But it is not working giving some error like :
    Exception in thread "main" javax.mail.NoSuchProviderException: No provider for POP
    at javax.mail.Session.getProvider(Session.java:455)
    at javax.mail.Session.getStore(Session.java:530)
    at javax.mail.Session.getStore(Session.java:510)
    at folderlist.main(folderlist.java:117)

    Hi bshannon,
    I had tried with the protocol names you given, but same is the result, can u tell me i m giving only protocol, host, user, password.
    Is this sufficient to connect or i need to supply all the params like url , root, verbose, pattern, etc.
    I m getting the access to server in other programs. Since our server doesn't support imap. so i tried like this
    E:\downloads\javamail-1.4\demo>java folderlist -P pop3 -H email.abc.com -U username -P password
    Exception in thread "main" javax.mail.NoSuchProviderException: Invalid protocol: null
            at javax.mail.Session.getProvider(Session.java:431)
            at javax.mail.Session.getStore(Session.java:530)
            at javax.mail.Session.getStore(Session.java:510)
            at javax.mail.Session.getStore(Session.java:496)
            at folderlist.main(folderlist.java:119)

  • GMail POP3 problem: Not getting messages with sender "me"

    HI guys,
    I have an account called [email protected] , I successfully sent mails to the same using javamail.In this messages,sender is marked as "me".
    Now I want to read all the messages in inbox,including the messages sent by same account itself.(messages with "me" sender).
    But I notices that javamail doesnt read any messages which the sender is "me".
    Is there a solution for this?
    thanks in advance,
    umanga
    Edited by: virtualumanga on Jun 6, 2008 7:09 PM
    Edited by: virtualumanga on Jun 6, 2008 7:10 PM

    Ok.Heres what happens.
    When I send emails to the same account using gmail webbase application , those mails (which the sender is "me") are read from my Java-POP3 code.
    But when I send mail using my Java-SMTP code , and try to retrieve them using same Java-POP3 program,those mails are not read.
    Here is my temp account that I am using
    user : [email protected]
    password: umanga123
    You can see there are 3 mails (please dont delete them) , which were sent using my Java-SMTP code.And one mail which is,sent from my yahoo account.
    Below Is the java-POP3 code that I am reading my messages.You can run them your self and see that the messages with "me" and not reading,only the message from yahoo is reading.
    You can test following code without any modifications..
    Please help,
    thanks in advance.
    public class MailGet {
         public static void main(String args[]) throws Exception
              String host="pop.gmail.com";
              String user="fhb.test";
              String pwd="umanga123";
              //String from="[email protected]";
              //String to="umanga@quicksilver";
              Properties props=new Properties();
              props.put("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
              props.put("mail.pop3.socketFactory.fallback", "false");
              props.put("mail.pop3.port", "995");
              props.put("mail.pop3.socketFactory.port", "995");
              //FileInputStream fis=new FileInputStream("/home/umanga/pop.prop");
              //props.load(fis);
              Session session=Session.getDefaultInstance(props,
                        null);
         try {     
              Store store=session.getStore("pop3s");
              store.connect(host,user,pwd);
              Folder folder=store.getDefaultFolder().getFolder("Inbox");
              folder.open(Folder.READ_WRITE);
             System.out.println("Getting messages");
              Message msg[]=folder.getMessages();
             System.out.println(folder.getMessageCount()+" "+folder.getUnreadMessageCount());
             for(int i=0;i<msg.length;i++)
                  System.out.println("Subject: "+msg.getSubject() );          
         folder.close(true);
         } catch (Exception e) {e.printStackTrace(); }     
    Edited by: virtualumanga on Jun 7, 2008 4:45 AM
    Edited by: virtualumanga on Jun 7, 2008 4:46 AM
    Edited by: virtualumanga on Jun 7, 2008 5:21 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Problem in Mail deletion in POP3

    Hi
    I am using Pop3.
    I opened folder using
    folder.open (Folder.READ_WRITE);
    setting flag for deletion
    mimeMessages.setFlag (Flags.Flag.DELETED, true);
    then in finally block closing the folder
    if (mailbox.isConnected ()) {
    if(folder != null && folder.isOpen()) {
    try {
    folder.close (true);
    sometimes it is not deleting the messages.
    Please suggest something.
    Thanks
    Atal

    I am sorry but what do u mean by this? can u please explain in detail.
    actually most of times it works fine but in few cases mail deletion is failing.
    In my code: after folder.close (true); I just take a dump that comes successfully.
    The MailBox folder has been closed after deleting the ToBeDeleted Mails, if any, by folder.close method.
    MessageId of 1 th message which has been marked for Deletion : 1150475083.23686.prod-util-1.aspdeploy.com,S=57857
    MessageId of 2 th message which has been marked for Deletion : 1150475117.23813.prod-util-1.aspdeploy.com,S=6808
    MessageId of 3 th message which has been marked for Deletion : 1150475120.23818.prod-util-1.aspdeploy.com,S=9425
    MessageId of 4 th message which has been marked for Deletion : 1150475140.23852.prod-util-1.aspdeploy.com,S=6121
    these 4 messages were marked for deletion.
    then close called. after
    The MailBox folder has been closed after deleting the ToBeDeleted Mails, if any, by folder.close method.
    message, it again tries to retrieve the folder with messages
    Retrieving messages for mailbox ..
    MessageId of the: 1 th message is 1150475083.23686.prod-util-1.aspdeploy.com,S=57857
    MessageId of the: 2 th message is 1150475117.23813.prod-util-1.aspdeploy.com,S=6808
    MessageId of the: 3 th message is 1150475120.23818.prod-util-1.aspdeploy.com,S=9425
    MessageId of the: 4 th message is 1150475140.23852.prod-util-1.aspdeploy.com,S=6121
    MessageId of the: 5 th message is 1150475338.13255.prod-util-2.aspdeploy.com,S=7458
    MessageId of the: 6 th message is 1150475387.13339.prod-util-2.aspdeploy.com,S=6394
    MessageId of the: 7 th message is 1150475393.13357.prod-util-2.aspdeploy.com,S=59238
    MessageId of the: 8 th message is 1150475553.13615.prod-util-2.aspdeploy.com,S=86236
    first 4 messages are same which were not deleted.
    I have just attached the code. If you want to have a look then plz.
    thanks
    atal
    package com.deploy.email;
    import com.baltimore.jpkiplus.vaults.Vault;
    import com.baltimore.jpkiplus.x509.JCRYPTO_X509Certificate;
    import com.baltimore.jsmt.smime.JSMTException;
    import com.baltimore.jsmt.smime.SMIMEv2;
    import com.deploy.email.api.EmailException;
    import com.deploy.email.api.InitException;
    import com.deploy.email.api.ReceivedMessage;
    import com.deploy.email.config.LogicalMailboxConfiguration;
    import com.deploy.email.config.MailConfiguration;
    import com.deploy.email.config.PhysicalMailboxConfiguration;
    import com.deploy.email.util.SecureEmailHelper;
    import com.sun.mail.pop3.POP3Folder;
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.BufferedReader;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    import java.util.ArrayList;
    import java.util.Enumeration;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Vector;
    import javax.mail.Address;
    import javax.mail.AuthenticationFailedException;
    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.Store;
    import javax.mail.UIDFolder;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;
    import javax.naming.NamingException;
    import org.apache.log4j.Logger;
    * This class spawns a thread for each mailbox and pulls messages from those mailboxes at a specified interval.
    * Use start to initialize and stop to end the threads
    * Bug Fixes
    * - 8399 Broke out the mailServer into two separate potential servers; sendMailServer and receiveMailServer
    * This class was updated to reflect the receiveMailServer setting
    * 04/25/03 John Gemski
    * - 10619 Added support for the Lotus Notes Client as per the 3.x fix. Copied logic from 3.x as detailed
    * by Hari in the bug report
    * 08/13/03 John Gemski
    * - Added Email Client Calendaring support - John Gemski 10/21/2003
    * @see com.deploy.email.EmailChannel
    public class RetrieveMail implements Runnable {
    /** Used to tell the threads when to stop */
    private static boolean keepRunning=true;
    //anish For nationwide
    private int maximumsizeofinbox=-1;
    /** The messages on the mail server that have been pulled but not deleted */
    private HashMap messagesOnServer;
    /** These are the mailbox types. Will only be one here for the Azetra impl */
    private static List logicalMailboxes;
    /** The list of running threads. Need to be tracked so they can be interrupted upon stop */
    private static ArrayList receiveThreads;
    /** A reference to the EmailChannel object, which may contain updated information. */
    private static EmailChannel emailChannel = EmailChannel.getInstance();
    private static Logger log = Logger.getLogger(EmailChannel.LOGGER_MODULE_NAME);
    // Thread variables
    /** the configuration for the physical mailbox from which the emails are being pulled. */
    private PhysicalMailboxConfiguration tPhysicalMailbox;
    /** the logical type (OLJB, ScanWorld, Task Response, Resume) that the physical mailbox thread is pulling for */
    private String tLogicalType;
    /** JavaMail Store */
    private Store mailbox;
    // Acceptable Protocols to retrieve mail from the mail server.
    public static final int RECEIVE_MAIL_PROTOCOL_POP3 = 0;
    public static final int RECEIVE_MAIL_PROTOCOL_IMAP = 1;
    public static final int NUM_RECEIVE_MAIL_PROTOCOLS = 2;
    public static String [] RECEIVE_MAIL_PROTOCOL_NAME;
    /** Indicates whether or not the Secure Email feature is enabled. */
    private static boolean secureEmailEnabled =false;
    static {
    RECEIVE_MAIL_PROTOCOL_NAME = new String [NUM_RECEIVE_MAIL_PROTOCOLS];
    RECEIVE_MAIL_PROTOCOL_NAME [RECEIVE_MAIL_PROTOCOL_POP3] = "pop3";
    RECEIVE_MAIL_PROTOCOL_NAME [RECEIVE_MAIL_PROTOCOL_IMAP] = "imap";
    // FIX for socket hang issue (FIX PR 14253) while processing the mail
    public static final String SOCKET_READ_ERROR = "No inputstream from datasource";
    /** Constructor for new RetrieveMail thread.
    * @param phys_config the mailbox configuration for a specific physical mailbox (i.e. [email protected])
    * @param logical_type the logical type for this mailbox ("Resumes", "OLJB", "ScanWorld", or "TaskResponse")
    private RetrieveMail(PhysicalMailboxConfiguration phys_config, String logical_type) {
    this.tPhysicalMailbox = phys_config;
    this.tLogicalType = logical_type;
    * Retrieve email messages from a mail server for the particular physical mailbox indicated with the thread
    * @throws EmailException if any fatal error occurs with the retrieval or processing of the incoming emails
    private void retrieveMessages () throws EmailException {
    Vector msgVector = new Vector ();
    Vector deleteMsgVector = new Vector ();
    ReceivedMessage [] recMessages;
    MailConfiguration mailConfig = emailChannel.getMailConfiguration();
    long maxReceivedEmailSize = mailConfig.getMaximumReceiveSize();
    //Anish for Bug 20366 for Nationwide Patch 06
    maximumsizeofinbox = mailConfig.getMaximumsizeofinbox();
    // Synchronize on the mailbox object for the mailbox from which we
    // are going to retrieve messages. We don't want more than one
    // thread connected to a mailbox at a time, but we don't want to
    // prevent multiple different threads from being connected to
    // multiple different mailboxes simultaneously.
    synchronized (mailbox) {
    boolean throwingException = false;
    Folder folder = null;
    try {
    /* Fix for 8399 - use the getReceiveMailServer call instead of the
    * getMailServer call
    // Connect to the server for receiving mail.
    mailbox.connect (mailConfig.getReceiveMailServer(),
    tPhysicalMailbox.getMailboxName(),
    tPhysicalMailbox.getMailboxPassword());
    // We are only interested in the "INBOX" folder.
    folder = mailbox.getFolder ("INBOX");
    // Open with write permissions as well, so we can delete messages from the server
    folder.open (Folder.READ_WRITE);
    // Anish for Bug 20366 for Nationwide Patch 06
    //int numMessages = folder.getMessageCount ();
    int numMessages1 = folder.getMessageCount ();
    int numMessages = 0;
    //log.info("Anish123 " + maximumsizeofinbox);
    if (maximumsizeofinbox < 0)
    numMessages = numMessages1;
    else
              if (numMessages1 > maximumsizeofinbox) {
              numMessages = maximumsizeofinbox;
              //log.info("Anish try 1 " + numMessages1);
              else {
              numMessages = numMessages1;
              //log.info("Anish try 2 " + numMessages);
    //     log.info("Anish try 4 " + numMessages);
    // End by anish
    if (numMessages > 0) { // There are messages to retrieve
    Message [] messagesRaw = folder.getMessages ();
    // We need to cast the messages to MIME message objects so
    // that we can access some MIME message-specific functionality.
    MimeMessage [] mimeMessages = new MimeMessage [numMessages];
    for (int i = 0; i < numMessages; i++) {
    mimeMessages = (MimeMessage) messagesRaw [i];
    // We can only get messages totalling maxReceivedMessageSize bytes.
    // Calculate how many messages we may get and still stay under the limit.
    int numMessagesToRetrieve = 0;
    int i = 0;
    if( maxReceivedEmailSize > 0) {
    int totalSize = 0;
    numMessagesToRetrieve = 0;
    boolean reachedLimit = false;
    while ((i < numMessages) && !reachedLimit) {
    int messageSize = mimeMessages[i].getSize ();
    int newTotalSize = totalSize + messageSize;
    if (newTotalSize > maxReceivedEmailSize) {
    //if this is the first message then break out and process it
    if( i == 0 ) {
    i++;
    totalSize = newTotalSize;
    reachedLimit = true;
    else {
    totalSize = newTotalSize;
    i++;
    numMessagesToRetrieve = i;
    i = 0;
    else {
    numMessagesToRetrieve = mimeMessages.length;
    while( i < numMessagesToRetrieve )
    boolean gotMessage = false;
    String uniqueID = null;
    if( numMessagesToRetrieve > 0 ) {
    // Get the ID for the message
    uniqueID = getUniqueID (mimeMessages[i], folder);
    //By Anurag for Req#2907 to add Debugging Logs start
    log.info("MessageId of the: " + (i+1) + " th message is " + uniqueID);
    //By Anurag for Req#2907 to add Debugging Logs End
    // Check if we have previoiusly retrieved this message.
    Object value = messagesOnServer.get (uniqueID);
    gotMessage = (value != null);
    if (!gotMessage) { // Make sure message is filled in.
    boolean processMessage = true;
    try {
    if(secureEmailEnabled) {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    mimeMessages[i].writeTo(os);
    InternetAddress[] senders = (InternetAddress[])mimeMessages[i].getFrom();
    InternetAddress[] recipients = (InternetAddress[])mimeMessages[i].getRecipients (Message.RecipientType.TO);
    Exception lastException = null;
    Vault v = null;
    for (int countRecipients = 0; countRecipients < recipients.length; countRecipients++) {
    lastException = null;
    v = null;
    // try to get the recipient's address from the Vault hash table
    log.info("Trying to get Vault for address: " + recipients[countRecipients].getAddress ());
    v = SecureEmailHelper.getVault (recipients[countRecipients].getAddress ());
    // we can't decrypt if we don't have a private key from the vault!
    if (v == null) {
    log.info("The PFX file for the email account: " + recipients[countRecipients].getAddress () + " is not found or invalid. Please correct.");
    lastException = new EmailException(EmailException.REASON_UNKNOWN, "The PFX file for the email account: " + recipients[countRecipients].getAddress () + " is not found or invalid. Please correct.");
    else {
    break;
    // if we came out with all exceptions, throw the last one we received.
    if (lastException != null) {
    log.error(lastException.getMessage(), lastException);
    throw lastException;
    SMIMEv2 smimer = new SMIMEv2(v);
    // Set up input and output streams to read an S/MIME message
    byte[] originalMessageBytes = os.toByteArray();
    String origMessStr = new String(originalMessageBytes);
    // The SMIMEv2 can't handle extra characters.
    // Noticed that messages contained an "+OK", which was causing problems
    // removed the entire line
    if(origMessStr.startsWith("+OK")) {
    int index = origMessStr.indexOf("\n");
    origMessStr = origMessStr.substring(index+1);
    byte[] revMessageStr = origMessStr.getBytes();
    ByteArrayInputStream input_source = new ByteArrayInputStream(revMessageStr);
    ByteArrayOutputStream output_sink = null;
    boolean smimeRecognized=true;
    boolean wasSigned=false;
    boolean wasEncrypted=false;
    // Making changes to reflect Baltimore's suggestion about layers
    ByteArrayInputStream newMessage = null;
    boolean done=false;
    // According to Baltimore, there can be two layers of encryption
    // inner and outer. It could be encrypted & signed, with it being either
    // encrypted on the outer layer and signed on the inner, or vice versa.
    // We want to ensure that this loop breaks out after either
    // 1. there were 2 layers sign/encrypted or encrypted/signed
    // 2. there was an error
    int layers=0;
    while(!done && layers < 2) {
    output_sink = new ByteArrayOutputStream();
    layers++;
         try {
    // This step must be don't before any cryptographic operations. It lets the SMIMEv2 class
    // figure out what it has as an input and where to place the output
    smimer.attachStreams(input_source, true, output_sink, false, false);
    catch (JSMTException jse) {
    // This is common since unencrypted and unsigned data cannot perform this function
    // Ideally, Baltimore says to use the type SMIMEv2.TYPE_DATA, but it never gets this
    // far since this fails.
    // We will skip the attempts to decrypt/verify the signature, since we know we won't
    // be able to interpret what type of message it is.
    smimeRecognized=false;
    // Will only be one layer
    done=true;
         log.debug("SMIME recognized: " + smimeRecognized);
    if(smimeRecognized) {
    // Get the S/MIME message type
    int nextdata = smimer.getMessageType();
    log.info("SMIME message type: " + nextdata);
    if (nextdata == smimer.TYPE_SIGNED) { // Signed message
    wasSigned=true;
    boolean matchedSender = false;
    // Didn't know you could have multiple "from" in an email address
    // Right now, only one of the "froms" has to have a certificate
    for(int s=0; s < senders.length; s++) {
    // get the sender's address
    String from_sender = senders[s].getAddress();
    try {
    // retrieve the certificates from the LDAP
    JCRYPTO_X509Certificate[] senderCerts = null;
    senderCerts = SecureEmailHelper.getCertificatesFromLDAP(from_sender);
    if(senderCerts!=null) {
    // verify() needs to take in a chain of certificates
    com.baltimore.jsmt.pkcs7.CertificateChain cc= new com.baltimore.jsmt.pkcs7.CertificateChain();
    // create certificate chain
    for(int k=0; k < senderCerts.length; k++) {
    cc.addCertificate(senderCerts[k]);
    // verify the Certificate Chain against the message's certs
    if(smimer.verify(cc)) {
    // found a match, the message was verified
    matchedSender=true;
    break;
    else
    log.error("Could not verify the sender" + from_sender);
    done=true;
    catch(NamingException ne) {
    log.error("There was a problem connecting to the LDAP for " + from_sender,ne);
    done=true;
    // if none of the senders matched, we need to not process
    // the email message, since it will be unreadable
    if(!matchedSender) {
    StringBuffer sendString = new StringBuffer();
    for(int s=0; s < senders.length; s++) {
    String from_sender = senders[s].getAddress();
    sendString.append(" : " );
    sendString.append(from_sender);
    processMessage = false;
    log.error("Could not find certificate for any of the senders" + sendString.toString());
    done=true;
    else if (nextdata == smimer.TYPE_ENVELOPED) { // Encrypted message
    log.debug("SMIME Encrypted message!");
    wasEncrypted = true;
    try {
    log.debug("SMIME Decrypting message...");
    // Decrypts the message
    smimer.openEnvelope();
    catch (JSMTException jse) {
    // Could not decrypt message
    log.error("Could not decrypt message: " + jse.getMessage (), jse);
    processMessage = false;
    done=true;
    else {
    log.debug("Unrecognized type");
    // doesn't seem to get here since Baltimore toolkit doesn't accept
    // nonencrypted, nonsigned emails (it should though). Keep here for future
    // releases of the toolkit
    done = true;
    // Now that we have output_sink,
    // retrieve the bytes
    byte[] processedBytes = output_sink.toByteArray();
    newMessage = new ByteArrayInputStream(processedBytes);
    input_source = new ByteArrayInputStream(processedBytes);
    else {
    // only for the first time around, revert to original
    if(layers==1) {
    // Keep original message
    newMessage = new ByteArrayInputStream(revMessageStr);
    log.debug("wasSigned: " + wasSigned + " wasEncrypted: " + wasEncrypted);
    // create the mime message again
    mimeMessages[i] = new MimeMessage(emailChannel.getSession(),newMessage);
    mimeMessages[i].setFrom (senders[0]);
    mimeMessages[i].setRecipients (Message.RecipientType.TO, recipients);
    // decrypted/verified data is automatically written to output_sink
    input_source.close();
    output_sink.close();
    // If the message wasn't signed, we can still process the message
    // if the settings allow the server to process unsigned messages
    // If not, set the flag to not process this message
    if(!tPhysicalMailbox.getAcceptUnsignedEmail() && !wasSigned) {
         log.info("Server configuration does not allow unsigned emails.");
    processMessage = false;
    // If the message wasn't encrytped, we can still process the message
    // if the settings allow the server to process unencrypted messages
    // If not, set the flag to not process this message
    if(!tPhysicalMailbox.getAcceptUnencryptedEmail() && !wasEncrypted) {
    log.info("Server configuration does not allow unencrypted emails.");
    processMessage = false;
    if(processMessage) {
    MimeMessage m = mimeMessages[i];
    if( maxReceivedEmailSize > 0 && m.getSize() > maxReceivedEmailSize ) {
    try {
    m = constructDummyMsg( m, m.getSize() );
    catch (Exception e) {
    // Add message to a list of messages to be deleted after
    // finished retrieving messages.
    deleteMsgVector.addElement (uniqueID);
    ReceivedMessage receivedMessage =
    new ReceivedMessage (m, uniqueID);
    msgVector.addElement (receivedMessage);
    else {
    log.info("Email could not be processed.");
    deleteMsgVector.addElement (uniqueID);
    catch (EmailException ee) {
    log.error("Email Exception", ee);
    deleteMsgVector.addElement (uniqueID);
    } // mail socket hang fix
    catch (javax.mail.MessagingException e) {
    String message = e.getMessage();
    // if it's a socket hang issue due to network outage, we want to logout and refetch the messages.
    if (message.equals(SOCKET_READ_ERROR)) {
    log.error("Socket timed out. Closing the connection", e);
    messagesOnServer.clear();
    throw new EmailException(

Maybe you are looking for