帮我用java写一个工具类,基于imap协议监控某个人的邮件,当有新邮件收到时触发打印
时间: 2024-02-05 14:10:31 浏览: 78
邮件接收IMAP类
4星 · 用户满意度95%
好的,以下是一个简单的 Java 工具类,可以基于 IMAP 协议监控某个人的邮件,当有新邮件收到时触发打印。
```java
import java.util.Properties;
import javax.mail.*;
import javax.mail.event.MessageCountAdapter;
import javax.mail.event.MessageCountEvent;
public class EmailMonitor {
private String host;
private String username;
private String password;
private String folder;
public EmailMonitor(String host, String username, String password, String folder) {
this.host = host;
this.username = username;
this.password = password;
this.folder = folder;
}
public void start() {
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
props.setProperty("mail.imaps.host", host);
props.setProperty("mail.imaps.user", username);
props.setProperty("mail.imaps.password", password);
try {
Session session = Session.getInstance(props);
Store store = session.getStore();
store.connect();
Folder inbox = store.getFolder(folder);
inbox.open(Folder.READ_ONLY);
inbox.addMessageCountListener(new MessageCountAdapter() {
@Override
public void messagesAdded(MessageCountEvent event) {
Message[] messages = event.getMessages();
for (Message message : messages) {
try {
System.out.println("New email received from: " + message.getFrom()[0] + ", Subject: " + message.getSubject());
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
});
while (true) {
Thread.sleep(1000);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String host = "imap.gmail.com";
String username = "your.email@gmail.com";
String password = "yourpassword";
String folder = "INBOX";
EmailMonitor monitor = new EmailMonitor(host, username, password, folder);
monitor.start();
}
}
```
你需要将 `host`、`username`、`password` 和 `folder` 这四个变量替换为你自己的邮箱服务器地址、邮箱账号、密码和要监控的文件夹名称。然后就可以通过 `monitor.start()` 方法启动监控,当有新邮件到达时会触发打印。
阅读全文