gpt4 book ai didi

java - 使用 Java Mail API 从 Gmail 导出所有电子邮件

转载 作者:行者123 更新时间:2023-12-01 13:01:57 26 4
gpt4 key购买 nike

所以我正在尝试编写一个程序,从我的电子邮件地址抓取所有电子邮件并将它们保存到文本文件中,我遇到的问题是使用 Java Mail API 抓取多于 1 封电子邮件。

这是我用来获取电子邮件的方法,效果很好,但我想获取收件箱中的每封电子邮件:

    public static void checkMail(String username, String password) {
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getInstance(props, null);
Store store = session.getStore();
store.connect("imap.gmail.com", username, password);
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Message msg = inbox.getMessage(inbox.getMessageCount());
Address[] in = msg.getFrom();
for (Address address : in) {
System.out.println("FROM:" + address.toString());
}
Multipart mp = (Multipart) msg.getContent();
BodyPart bp = mp.getBodyPart(0);
System.out.println("SENT DATE:" + msg.getSentDate());
System.out.println("SUBJECT:" + msg.getSubject());
System.out.println("CONTENT:" + bp.getContent());
} catch (Exception mex) {
mex.printStackTrace();
}
}

如果有人可以向我展示如何执行此操作或解释它,那么我将不胜感激。

最佳答案

如果您想要文件夹收件箱中的所有邮件,请执行以下操作:

public static void checkMail(String username, String password) {
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getInstance(props, null);
Store store = session.getStore();
store.connect("imap.gmail.com", username, password);
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Message[] msgs = inbox.getMessages();

for (Message msg : msgs) {
try {
Address[] in = msg.getFrom();
for (Address address : in) {
System.out.println("FROM:" + address.toString());
}
Multipart mp = (Multipart) msg.getContent();
BodyPart bp = mp.getBodyPart(0);
System.out.println("SENT DATE:" + msg.getSentDate());
System.out.println("SUBJECT:" + msg.getSubject());
System.out.println("CONTENT:" + bp.getContent());
} catch (Exception e) {

e.printStackTrace();
}
}
// close folder and store (normally in a finally block)
inbox.close(false);
store.close();

} catch (Exception mex) {
mex.printStackTrace();
}
}

如果您想要从其他文件夹发送邮件,则必须对所有文件夹执行相同的操作。您可以使用 store.getDefaultFolder().list() 获取它们(对所有文件夹递归执行此操作,因为文件夹可以包含子文件夹)

protected void recurseFolders(final Folder folder) {
// folder can hold messages
if ((folder.getType() & Folder.HOLDS_MESSAGES) != 0) {

// process them

}

// folder can hold other folders
if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0) {
for (final Folder subfolder : folder.list()) {

// process them recursive
recurseFolders(subfolder);

}
}

}

看这里:https://github.com/salyh/elasticsearch-river-imap

关于java - 使用 Java Mail API 从 Gmail 导出所有电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23453999/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com