Properties props = new Properties();
props.setProperty("mail.transport.protocol", "imap"); // 使用的协议, imap | pop3
props.setProperty("mail.imap.host", "smtp.qq.com"); // 邮箱的收件服务器地址
// 获取连接
Session session = Session.getDefaultInstance(props);
session.setDebug(false);
IMAPStore store = (IMAPStore) session.getStore(protocol);
store.connect(emailboxServer, username, authCode); // imap服务器的登录认证, 邮箱账号用户名,授权码
IMAPFolder inbox = (IMAPFolder) store.getFolder("INBOX");
inbox.open(Folder.READ_WRITE);
Message[] messages = inbox.getMessages();
for (Message message : messages) {
IMAPMessage imapMessage = (IMAPMessage) message;
Flags flags = imapMessage.getFlags();
if (flags.contains(Flags.Flag.SEEN)) {
continue;
}
CustomerEmail email = new CustomerEmail();
email.setEmailId(inbox.getUID(imapMessage)); // 邮件唯一标识
email.setDeliveryDate(format.format(imapMessage.getSentDate())); // 发件日期
String subject = imapMessage.getSubject(); // 主题
email.setSubject(subject);
InternetAddress from = (InternetAddress) imapMessage.getFrom()[0]; // 发件人
email.setFrom(from.getAddress());
InternetAddress to = (InternetAddress) imapMessage.getReplyTo()[0]; // 收件人
email.setTo(to.getAddress());
if (message.isMimeType("TEXT/*")) { // 仅包含正文的简单邮件
System.out.println("邮件正文: " + message.getContent());
} else {
parseMessage((MimeMultipart) message.getContent(), email); // 解析稍复杂邮件
}
}
/**
* 解析邮件
*/
public static void parseMessage (MimeMultipart part, CustomerEmail email) throws MessagingException, IOException {
byte[] bytes = new byte[1024];
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
for (int i = 0; i < part.getCount(); i++) {
BodyPart body = part.getBodyPart(i);
if (body.isMimeType("text/html")) {
System.out.println("html格式正文: " + (String) body.getContent());
} else if (body.isMimeType("text/plain")) {
System.out.println("纯文本格式正文: " + (String) body.getContent());
} else if (body.isMimeType("multipart/*")) {
MimeMultipart multipart = (MimeMultipart) body.getContent();
parseMessage(multipart, email);
} else { // 附件
InputStream inputStream = body.getDataHandler().getInputStream();
int len = 0;
while( (len = inputStream.read(bytes)) != -1 ){
outStream.write(bytes, 0, len);
}
inputStream.close();
byte[] data = outStream.toByteArray();
String fileName = body.getFileName();
File tempFile = new File(FileUtils.getTempDirectoryPath() + File.separator + System.currentTimeMillis() + fileName );
FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
fileOutputStream.write(data);
fileOutputStream.close();
System.out.println("邮件附件本地路径: " + tempFile.getAbsolutePath());
}
}
}
标签:body,Java,imap,email,new,imapMessage,邮件
From: https://www.cnblogs.com/hui0618/p/16627515.html