我試圖通過IMAP藉助JavaMail API從Gmail帳戶訪問電子郵件。我想知道爲什麼代碼適用於一個電子郵件帳戶,但不適用於另一個。使用IMAP(javamail API)從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","[email protected]", "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(); }
}
}
}
哇。這工作! :-) – 2014-03-25 09:59:32
謝謝你。 :-) – kukis 2014-12-14 10:44:18