java之邮件读取和解析
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class EmailReader {
public static void main(String[] args) {
String host = "your.imap.host";
String username = "your-username";
String password = "your-password";
Properties properties = new Properties();
properties.put("mail.imap.host", host);
properties.put("mail.imap.port", "993");
properties.put("mail.imap.starttls.enable", "true");
Session emailSession = Session.getDefaultInstance(properties);
try {
Store store = emailSession.getStore("imap");
store.connect(host, username, password);
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
Message[] messages = emailFolder.getMessages();
for (Message message : messages) {
Address[] fromAddress = message.getFrom();
String from = fromAddress[0].toString();
String subject = message.getSubject();
String content = message.getContent().toString();
System.out.println("FROM: " + from);
System.out.println("SUBJECT: " + subject);
System.out.println("CONTENT: " + content);
}
emailFolder.close(false);
store.close();
} catch (NoSuchProviderException | MessagingException | IOException e) {
e.printStackTrace();
}
}
}
这段代码演示了如何使用JavaMail API从IMAP服务器读取邮件,并打印出发件人、主题和内容。需要替换your.imap.host
, your-username
, 和 your-password
为实际的邮件服务器地址和凭据。
评论已关闭