同志们,
我想构建一个可以从邮箱读取电子邮件的应用程序。我已检查 SMTP 和 IMAP 的设置是否已激活。
方法在这里
public Message[] readMails() throws MessagingException {
Properties properties = new Properties();
properties.put("mail.store.protocol", "imap");
properties.put("mail.imap.host", "imap.web.de");
properties.put("mail.imap.port", "993");
properties.put("mail.imap.ssl.enable", "true");
properties.put("mail.imap.auth", "true");
Session session = Session.getInstance(properties);
Store store = session.getStore("imap");
store.connect("imap.web.de", 993, "user", "password");
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_WRITE);
// Fetch unseen messages from inbox folder
Message[] messages = inbox.search(
new FlagTerm(new Flags(Flags.Flag.SEEN), false));
// Sort messages from recent to oldest
Arrays.sort(messages, (m1, m2) -> {
try {
return m2.getSentDate().compareTo(m1.getSentDate());
} catch (MessagingException e) {
throw new RuntimeException(e);
}
});
return messages;
}
如果我执行该方法会在这里抛出异常
Store store = session.getStore("imap"); //thorws NoSuchProviderException: imap
我检查了 github 上的视频和其他项目。没有成功。
我终于解决了我自己的问题。
我的项目中的 JavaMail API 版本似乎存在冲突。我的 pom.xml 中有 javax.mail:javax.mail-api:1.6.2 和 com.sun.mail:imap:2.0.1 。这两个依赖项导致了冲突。
我删除了 javax.mail。
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>imap</artifactId>
<version>2.0.1</version>
</dependency>