import jakarta.mail.*;
import jakarta.mail.internet.MimeMultipart;
import java.util.Properties;
import java.util.Scanner;
import javax.swing.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Safelist;
public class Main {
record Account(String host, int port, String user, String password, String inboxName) {}
public static void main(String[] args) throws Exception {
receive10(new Account(, , , , "INBOX"));
}
private static void receive10(Account ac) throws Exception {
Store emailStore = null;
Folder emailFolder = null;
Properties properties = new Properties();
properties.put("mail.store.protocol", "imap");
properties.put("mail.imap.ssl.enable", "true");
properties.put("mail.imap.host", ac.host());
properties.put("mail.imap.port", ac.port());
Session emailSession = Session.getInstance(properties);
try {
emailStore = emailSession.getStore();
emailStore.connect(ac.user(), ac.password());
System.out.println("Connected");
emailFolder = emailStore.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
int c1 = emailFolder.getMessageCount();
int c2 = 0;
for (int i = c1; i > 0 && c2 < 10; i--, c2++) {
System.out.println(emailFolder.getMessage(i).getSubject());
}
while (true) {
System.out.println("Wich to display? (1-10 or empty to quit):");
String line = new Scanner(System.in).nextLine();
if (line == null || line.isBlank()) {
break;
}
int i = c1 - Integer.parseInt(line) + 1;
display1(emailFolder.getMessage(i));
}
} finally {
if (emailFolder != null && emailFolder.isOpen()) {
emailFolder.close(false);
}
if (emailStore != null && emailStore.isConnected()) {
emailStore.close();
}
System.out.println("Disconnected");
}
}
private static void display1(Message message) throws Exception {
StringBuilder sb = new StringBuilder();
sb.append(message.getSentDate()).append("\n\n");
for (Address a : message.getFrom()) {
sb.append(a.toString()).append("\n\n");
}
sb.append(message.getSubject()).append("\n\n");
if (message.isMimeType("text/plain")) {
sb.append(message.getContent().toString());
}
if (message.isMimeType("multipart/*")) {
MimeMultipart mimeMultipart = (MimeMultipart) message.getContent();
for (int i = 0; i < mimeMultipart.getCount(); i++) {
Document document = Jsoup.parse(mimeMultipart.getBodyPart(i).getContent().toString());
document.outputSettings(new Document.OutputSettings().prettyPrint(false));
document.select("br").append("\\n");
document.select("p").prepend("\\n\\n");
String s = document.html().replaceAll("\\\\n", "\n");
sb.append(
Jsoup.clean(
s, "", Safelist.none(), new Document.OutputSettings().prettyPrint(false)))
.append("\n\n");
}
}
JFrame f = new JFrame();
JTextArea ta = new JTextArea(sb.toString());
ta.setLineWrap(true);
f.getContentPane().add(new JScrollPane(ta));
f.setSize(600, 400);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setVisible(true);
}
}