使用 IMAP(javamail API)从 gmail 访问电子邮件
我正在尝试借助 JavaMail API 通过 IMAP 访问来自 Gmail 帐户的电子邮件.我想知道为什么该代码适用于一个电子邮件帐户但不适用于另一个.
I am trying to access emails from Gmail accounts through IMAP with the help of the JavaMail API. I was wondering why the code works for one email account but doesn't work for another.
我可以访问两个电子邮件帐户的 Inbox
文件夹.但是对于其中一个电子邮件帐户,无法访问 SPAM([Gmail]/Spam)
等其他文件夹,并且会引发 FolderNotFoundException
异常.有人可以解释发生了什么问题吗?
I am able to access the Inbox
folder of both email accounts. But for one of the email accounts, other folders like SPAM([Gmail]/Spam)
are not able to be accessed and it throws a FolderNotFoundException
exception. Could anybody please explain what is going wrong?
提前谢谢你.
代码如下:
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:
"+ msg.getContent());
System.out.println(msg.getContentType());
}
}
finally
{
if (folder != null && folder.isOpen()) { folder.close(true); }
if (store != null) { store.close(); }
}
}
}
推荐答案
其中一个帐户是否有任何机会使用非英文 UI?
Is one of the accounts using non-english UI by any chance?
Gmail 文件夹名称已根据用户本地化设置进行本地化.
Gmail folder names are localized with respect to the user localization settings.
目前获取本地化文件夹名称的唯一方法是使用 XLIST 命令.
Currently the only way to get the name of the localized folder is by using XLIST command.
相关文章