使用IMAP(javamail API)访问来自gmail的电子邮件
2022-09-01 17:40:02
我正在尝试在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(); }
}
}
}