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

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

我可以访问这两个电子邮件帐户的收件箱文件夹。但是对于其中一个电子邮件帐户,其他文件夹(如垃圾邮件(Gmail)/垃圾邮件))无法访问,并会引发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(); }
        }

    }



}
是使用非英语UI的帐户之一吗?

相对于用户本地化设置,Gmail文件夹名称已被本地化。

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

http://stackoverflow.com/questions/9263530/accessing-emails-from-gmail-using-imap-javamail-api

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:使用IMAP(javamail API)访问gmail的电子邮件