How can i read multiple email accounts?

hi,
my program is to get emails from multiple email accounts, and grab the attachments, but it doesn't work properly.
If there's only one email account, it works fine, but if there are more, it looks like that the program always goes into the first mail account to read the messages. i suspect that the 'Server' or the 'Session' are not reset before each connection, i printed out the connected 'Folder', it looks fine, but every time the 'Folder.getMessageCount()' returns the same number of messages as the first email account has.
Here's my code:
// this is to get the folder, mostly 'inbox'
// serverString is like: "protocol://username@host/foldername"
// all parameters are retrieved from the Database
public static Folder getMailFolder(String serverString, String username, String password) throws Exception {
        // URLName server = new URLName("protocol://username@host/foldername");
        Folder folder = null;
        URLName server = new URLName(serverString);
        // the session is created by grabbing the authentication using the username and password
        // the MailAuthenticator is an inner class as shown at the bottom
        Session session = Session.getDefaultInstance(new Properties(),
                new MailAuthenticator(username, password));
        folder = session.getFolder(server);
        // this message always show the same number of messages
        System.out.println("folder retrieved for " + serverString + ", with " + folder.getMessageCount() + " messages");
        return folder;
// this method is to get the messages from the folder
public static void getEmailWithSubjectContaining(String emailUrl, String username, String password,
              String regex, String filepath, boolean addPrefix, boolean delete)
         throws Exception {
         Folder folder = getMailFolder(emailUrl, username, password);
        if (folder == null)  return;
        folder.open(Folder.READ_WRITE);
        Message[] msgs = folder.getMessages();
        // Here is my problem, the msgs.length always returns the same value
        // which is the number of messages that the first email account has
        System.out.println("Totally there are " + msgs.length);
        for (int i = 0; i < msgs.length; i++) {
             String pathToSave = filepath;
               String subject = msgs.getSubject();
               System.out.println("Email subject: " + subject);
// examine if the message should be dumped and deleted
               if (!subject.matches(regex)) {
                    System.out.println("Email subject doesn't match regex: " + regex + ", this email is ignored.");
                    continue;
               Part p = (Part) msgs[i];
//               p.getFileName();
               if (addPrefix) {
                    pathToSave = filepath + "/" + getFilenamePrefix(subject);
// this method call is to save the attachment
               dumpAttachment(p, pathToSave);
               msgs[i].setFlag(Flags.Flag.DELETED, delete);
          folder.expunge();
folder.close(false);
// this method calls getEmailWithSubjectContaining using a loop
public static void getEmailWithSubjectContaining(String dbUsername, String dbPassword, String dbUrl) throws Exception {
     Connection con = null;
     if (dbUrl == null || dbUrl.equals("")) dbUrl = "jdbc:mysql://localhost/email_util";
          try {
// here is just simply get the Database connection
               con = MySqlJDBCConnection.getConnection(dbUsername, dbPassword, dbUrl);
               Statement s = con.createStatement();
               String sql = "SELECT * FROM email_fetching_config WHERE active = 1";
               ResultSet rs = s.executeQuery(sql);
               while (rs.next()) {
                    String protocol = rs.getString("protocol");
                    String url = rs.getString("url");
                    String box = rs.getString("email_box");
                    String username = rs.getString("username");
                    String password = rs.getString("password");
                    String regex = rs.getString("sub_regex");
                    String path = rs.getString("save_to");
                    String prefix = rs.getString("append_prefix");
                    boolean delete = rs.getBoolean("delete");
                    String emailUrl = protocol + "://" + username + "@" + url + "/" + box;
                    boolean addPrefix = (!prefix.equals("") || prefix != null);
                    System.out.println("Ready to grab emails from " + emailUrl + ", path to save is: " + path);
                    try {
                         getEmailWithSubjectContaining(emailUrl, username, password, regex, path, addPrefix, delete);
                    } catch (Exception ex) {
          } catch (Exception ex) {
               ex.printStackTrace();
          } finally {
               MySqlJDBCConnection.close();
********* Authenticator *******
class MailAuthenticator extends Authenticator {
private String username;
private String password;
public MailAuthenticator() {
public MailAuthenticator(String username, String password) {
this.username = username;
this.password = password;
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(this.username, this.password);
This is all my program doing, anyone knows what the program is? thanks for your help!
regards                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Assuming you're passing in the right URL, I don't see the problem.
Still, try change session.getDefaultInstance to session.getInstance
and see if that helps. If not, turn on session debugging and check the
protocol trace for clues. If you still can't figure it out, post the protocol
trace.

Similar Messages

  • How can i host multiple email accounts?

    Hi there,
    I've a problem.
    I have installed Lion os x server with the latest updates.
    I need help to set up Separate E-Mail Accounts for each Domain, so each Domain receives it's own mail.
    I have the following domains that i want to host with emails.
    www.example1.com
    www.example2.com
    Hosting of website is not a problem. I have it working including PHP+MYSQL.
    But now..How can i setup to receive and send emails with both domains? (www.example1.com and www.example2.com)
    I want to have something like this:
    www.example1.com:
    [email protected]
    Hostname: server.example1.com
    Outgoing: server.example1.com
    and
    www.example2.com:
    [email protected]
    Hostname: server.example2.com
    Outgoing: server.example2.com
    for www.example1.com it's the standard one and works fine (including apple Push). But realy confusing that i cannot get it work with example2.com.
    Can anybody help me? I've searched the whole web but cannot find a good answer.
    Thank you very much in advance!
    JBressers

    You can run multiple domains in postfix/Mac OS X server, but don't get bogged down with the hostname.
    There is nothing wrong with mail for a [email protected] being delivered to/from a server.example2.com (or vice versa). Most users never see the hostname of the server in the process, so don't bother trying to create multiple hostnames on the server to make this work. If you're really bothered just create records in your DNS that map back to the same IP address (e.g. server.example1.com -> 1.2.3.4, server.example2.com -> CNAME -> server.example1.com) so users can use either hostname.
    For the accounts, there are two ways of managing multiple domains, depending largely on your comfort level with the command line vs. GUI, and how the users map.
    If the usernames are the same (e.g. [email protected] is the same person as [email protected]) then the simplest thing to do is tell postfix to accept mail for both domains - mail addressed to either domain (example1.com or example2.com) will route to the same user's mailbox.
    If your users are different then you can either use Mac OS X-style aliases or postfix aliases.
    The Mac OS X-style aliases work through Workgroup Manager - you add all your users to the main directory, and create additional shortnames for each user's email addresses. For example, you might have a user 'joe' who is also '[email protected]', so add that second email address as a shortname.
    Postfix-style aliases require setting up in the command line, where you create maps of email addresses to users, and is well documented on various postfix-driven web sites.

  • Can I open multiple email accounts on my ipad?

    How can I open multiple email accounts on my ipad?

    Hello Danbonow,
    Yes, to do that, follow this instructions:
    Open Settings.
    Tap "Mail, Contacts, Calendar".
    Select "Add account" and fill the details.
    Sincerely,
    Gonçalo Matos

  • HT204053 how can i create multiple icloud accounts for my family members

    how can i create multiple icloud accounts for my family members

    Thanks...  I appreciate the reply.  Since I wrote the previous email, I actually went and changed my apple id (the main id) and the documentation I looked at said iCloud will set mail up automatically(?)...  I had it working before. 
    Also, I tried to manually set up the ID via the Mail Accounts screen(s) and I can't figure out what my server information is...  Pop or Imap?  What's the outgoing server and the incoming server?
    I typically have never had problems setting up mail accounts (in apple mail) with no problem.
    Can anyone point me in the right direction?
    Thanks in advance!

  • How can I manage six email accounts WITHOUT them all appearing (twice) in the Folders column?

    How can I manage six email accounts WITHOUT them all appearing (twice) in the Folders column?
    All I need is ONE INBOX (like Windows Mail used to do) ...
    I can see in the 'Account' column of each message which email account it's using.
    Then, I either junk or read the message, followed by delete or file to one of my created folders.
    As it is, half my page is depth is taken up by 12 lines of Account names !!!

    That still leaves SIX lines of Account names down the side. All I want is ONE INBOX ... (I can see which account each message belongs to in the 'Account' column...)

  • How can I change my email account address on my Drop Box account. The present address is wrong.

    How can I change my email account address on my Drop Box account? The present address is wrong.

    Dropbox is not in any way associated with Adobe.  Ask Dropbox support, or start using Workspaces at https://www.acrobat.com/

  • How can I transfer my email accounts and emails from my old macbook pro with ML to my new macbook pro with ML

    How can I transfer my email accounts and emails from my old macbook pro with ML to my new macbook pro with ML

    Do you have your system backed up to Time Machine? If so, you can open your user Library and copy your Mail folder from Time Machine to your Desktop on your new machine; then copy THAT folder to your new machine's user Library.
    To get to your user Library, open Finder and Go and press the Option key. Library will show up. Click on it to get into your user Library. Now go into Time Machine and you should see your user Library for Time Machine. Restore the Mail folder to your Desktop.

  • How can I add multiple email addresses to Address Book?

    How can I add multiple email addresses to Address Book?
    Can it be done from an .xlsx file?

    I have tried that, but the system reads the emails as one long email and I can't find any way of separating them - it ignores spaces, colons and I have also tried putting them through a word doc... still does not work. It works perfectly easily on a PC system!! ( I have just moved to a mac!)
    any ideas would be good
    thanks

  • How can I add multiple email addresses  from spreadsheet into email?

    how can I add multiple email addresses  from spreadsheet into email?

    I have tried that, but the system reads the emails as one long email and I can't find any way of separating them - it ignores spaces, colons and I have also tried putting them through a word doc... still does not work. It works perfectly easily on a PC system!! ( I have just moved to a mac!)
    any ideas would be good
    thanks

  • How can I delete an email account?

    How can I delete an email account off the phone?

    Go to your menu, settings, scroll down to accounts.  Select the account and any address you wish to remove.  Press menu again and choose remove account.  Then confirm.

  • How can I delete multiple emails on my Samsung Stratosphere at once?

    How can I delete multiple emails on my Samsung Stratosphere at once? I use AOL and when I delete the emails off of my computer, they do not delete from my phone. So I have hundreds of unwanted messages showing on my phone but I have not found an option to delete all messages, only individually. I would also like to be able to clear the messages from my phone without them deleting from my computer. This was super easy with my blackberry and I have not found anything similar on this phone.

    When I go to the trash folder on my Stratosphere, I can check individual emails and then hit "Menu" and "Delete", but if I hit the "Menu" button before selecting any e-mails, then I see the "Delete all" button, but it's greyed out, so I cannot select it.  There's also a "Restore All" button next to the "Delete all" button, and it's also greyed out.  So, currently the only way I can delete the 100's of e-mails in my trash is to put a check mark next to each one, which is painful.  Anybody else have this problem or know of a solution?

  • How can I delete multiple emails in the mailbox in one time?

    How can I delete multiple emails in one time in the mailbox?

    When inside a folder, listing your emails, tap the Edit button, then select as many emails as you want to then tap trash.

  • TS3899 how can i delete multiple emails from my IPhone 5C from the inbox?

    How can i delete multiple emails from my inbox from my IPhone 5c?

    Use command-click to select multiple messages, one at a time.  Use shift-click to select a contiguous set of messages (just like in the Finder).  Then press the delete key.

  • How can I setup my email account ?

    How can I setup my email account on my home page email app?

    GDHump,
    I know the importance of ensuring your email is set up to your preference! Here's a link that provides the steps to view and edit your email account Servicer settings on the Sony Ericson Xperia Play: Email Account Password and Server Settings Xperia Play by Sony Ericsson | Verizon Wireless. Please let us know if you need anything further.
    TanishaS1_VZW
    Follow us on Twitter @VZWSupport

  • How can I read an email that someone sent me if it is in powerpoint?

    How can I read an email that someone sent me if it is in powerpoint?

    An email in Powerpoint sounds kind of odd, however, you can download neooffice or openoffice to read it. Microsoft hasn't provided a reader for mac in quite awhile.

Maybe you are looking for