使用IMAP(javamail API)从gmail访问电子邮件

时间:2012-02-13 15:53:07

标签: java gmail imap javamail

我正在尝试借助JavaMail API通过IMAP访问Gmail帐户中的电子邮件。我想知道为什么代码适用于一个电子邮件帐户但不适用于另一个。

我可以访问两个电子邮件帐户的Inbox文件夹。但对于其中一个电子邮件帐户,其他文件夹(如SPAM([Gmail]/Spam))无法访问,并且会引发FolderNotFoundException异常。有人可以解释一下出了什么问题吗?

提前谢谢。

以下是代码:

import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.Flags.Flag;
import javax.mail.internet.*;

import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.IMAPMessage;


public class FolderFetchIMAP {


    public static void main(String[] args) throws MessagingException, IOException {
        IMAPFolder folder = null;
        Store store = null;
        String subject = null;
        Flag flag = null;
        try 
        {
          Properties props = System.getProperties();
          props.setProperty("mail.store.protocol", "imaps");

          Session session = Session.getDefaultInstance(props, null);

          store = session.getStore("imaps");
          store.connect("imap.googlemail.com","myemailid@gmail.com", "password");

          folder = (IMAPFolder) store.getFolder("[Gmail]/Spam"); // This doesn't work for other email account
          //folder = (IMAPFolder) store.getFolder("inbox"); This works for both email account


          if(!folder.isOpen())
          folder.open(Folder.READ_WRITE);
          Message[] messages = folder.getMessages();
          System.out.println("No of Messages : " + folder.getMessageCount());
          System.out.println("No of Unread Messages : " + folder.getUnreadMessageCount());
          System.out.println(messages.length);
          for (int i=0; i < messages.length;i++) 
          {

            System.out.println("*****************************************************************************");
            System.out.println("MESSAGE " + (i + 1) + ":");
            Message msg =  messages[i];
            //System.out.println(msg.getMessageNumber());
            //Object String;
            //System.out.println(folder.getUID(msg)

            subject = msg.getSubject();

            System.out.println("Subject: " + subject);
            System.out.println("From: " + msg.getFrom()[0]);
           System.out.println("To: "+msg.getAllRecipients()[0]);
            System.out.println("Date: "+msg.getReceivedDate());
            System.out.println("Size: "+msg.getSize());
            System.out.println(msg.getFlags());
            System.out.println("Body: \n"+ msg.getContent());
            System.out.println(msg.getContentType());

          }
        }
        finally 
        {
          if (folder != null && folder.isOpen()) { folder.close(true); }
          if (store != null) { store.close(); }
        }

    }



}

5 个答案:

答案 0 :(得分:13)

其中一个帐户是否有机会使用非英语用户界面?

Gmail文件夹名称已根据用户本地化设置进行了本地化。

目前获取本地化文件夹名称的唯一方法是使用XLIST命令。

答案 1 :(得分:6)

package com.technicalkeeda;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;

public class GmailInbox {

 public static void main(String[] args) {
  GmailInbox gmail = new GmailInbox();
  gmail.read();
 }

 public void read() {
  Properties props = new Properties();
  try {
   props.load(new FileInputStream(new File("C:\\smtp.properties")));
   Session session = Session.getDefaultInstance(props, null);

   Store store = session.getStore("imaps");
   store.connect("smtp.gmail.com", "*************@gmail.com","your_password");

   Folder inbox = store.getFolder("inbox");
   inbox.open(Folder.READ_ONLY);
   int messageCount = inbox.getMessageCount();

   System.out.println("Total Messages:- " + messageCount);

   Message[] messages = inbox.getMessages();
   System.out.println("------------------------------");
   for (int i = 0; i < 10; i++) {
      System.out.println("Mail Subject:- " + messages[i].getSubject());      
   }
   inbox.close(true);
   store.close();

  } catch (Exception e) {
   e.printStackTrace();
  }
 }

}

答案 2 :(得分:1)

它以这种方式工作(看起来它不适用于POP3,但它适用于IMAP):

     Properties props = new Properties();
     props.put("mail.store.protocol", "imaps");
     Session session = Session.getDefaultInstance(props, null);
     Store store = session.getStore("imaps");
     store.connect("imap.gmail.com", [theMailAccount@gmail.com], [thePasswordOrAppPassword]);

     // You possibly will have to use [Google Mail]/All Mail instead
     Folder inbox = store.getFolder("[Gmail]/All Mail");

答案 3 :(得分:0)

我不确定这是否有帮助,但我见过gmail帐户有不同邮箱的情况,即..

Gmail帐户1: -

[[Google Mail]]
[[Google Mail]/All Mail]
[[Google Mail]/Bin]
[[Google Mail]/Drafts]
[[Google Mail]/Important]
[[Google Mail]/Sent Mail]
[[Google Mail]/Spam]
[[Google Mail]/Starred]

Gmail帐户2: -

[[Gmail]]
[[Gmail]/All Mail]
[[Gmail]/Bin]
[[Gmail]/Drafts]
[[Gmail]/Important]
[[Gmail]/Sent Mail]
[[Gmail]/Spam]
[[Gmail]/Starred]

答案 4 :(得分:0)

私有列表getResulr1(){

        try {

            Properties props = new Properties();

            props.put("mail.store.protocol","imaps");

            Session session = Session.getDefaultInstance(props, null);

            Store store = session.getStore("imaps");

            store.connect("imap.gmail.com", "Email Id", "App Password");

            Folder inbox = store.getFolder("inbox");

            //if you want mail from specify floder just change change floder name
            //Folder inbox = store.getFolder("[Gmail]/Drafts");

            inbox.open(Folder.READ_ONLY);

            int messageCount = inbox.getMessageCount();

            Log.e("getFloder ", "getResulr1: "+store.getDefaultFolder().list("*") );

            javax.mail.Folder[] folders = store.getDefaultFolder().list("*");

            for (javax.mail.Folder folder : folders) {

                if ((folder.getType() & javax.mail.Folder.HOLDS_MESSAGES) != 0){

                    Log.e("getFloder ", "getResulr1: "+folder.getName() );

                }
            }

            Log.e("Mail Subject:", "Total Messages:-: "+messageCount );

            javax.mail.Message[] messages = inbox.getMessages();

            System.out.println("------------------------------");

            Log.e("Mail Subject:", "messages: "+messages.toString());

            for (int i = 0; i < messages.length; i++) {

                  Log.e("Mail Subject:", "getResulr1: "+messages[i].getSubject());
            }

            inbox.close(true);

            store.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }