【发布时间】:2011-03-14 00:43:47
【问题描述】:
我正在使用 JavaMail 开发一个项目。我想访问我的 Gmail 收件箱并接收邮件。我通过检查主题来查找特定消息。此消息有一个我保存的附件。该程序在第一次运行时运行良好。问题是一旦我运行程序,任何后续运行都看不到该消息。它不会作为文件夹消息的一部分出现。如果我转到 gmail 帐户并设置“为所有邮件启用 POP(甚至是已经下载的邮件)”(从一开始就是设置)我可以再次看到该消息,然后它再次停止出现在文件夹中。我不明白,任何帮助都会很棒。
这是我获取消息的代码:
Session session2 = Session.getDefaultInstance(props2, null);
Store store = session2.getStore("pop3s");
store.connect(getHost, username, password);
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
System.out.println(folder.getMessageCount());
Message messages[] = folder.getMessages();
for (Message message : messages) {
System.out.println(message.getSubject());
if (message.getSubject().equalsIgnoreCase("Input File")) {
if (message.getContent() instanceof Multipart) {
Multipart multipart = (Multipart) message.getContent();
for (int i = 0, n = multipart.getCount(); i < n; i++) {
Part part = multipart.getBodyPart(i);
String disposition = part.getDisposition();
if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE))))) {
File f = saveFile(part.getFileName(), part.getInputStream());
System.out.println(f.getPath());
}
}
}
}
}
folder.close(false);
store.close();
}
saveFile 方法:
public static File saveFile(String filename, InputStream input) throws FileNotFoundException, IOException {
File file = new File(filename);
for (int i = 0; file.exists(); i++) {
file = new File(filename + i);
}
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
BufferedInputStream bis = new BufferedInputStream(input);
int aByte;
while ((aByte = bis.read()) != -1) {
bos.write(aByte);
}
bos.flush();
bos.close();
bis.close();
return file;
}
【问题讨论】:
标签: java jakarta-mail