我想安排我想要阅读新电子邮件的电子邮件服务(也可能每隔一小时后阅读),现在我可以使用java邮件从gmail读取IMAP电子邮件收件箱。现在它是在我的收件箱中查找新电子邮件并解析的重要部分。我用于提供和解析电子邮件的工作代码如下所示。
Session session = Session.getInstance(properties);
try {
IMAPSSLStore store = (IMAPSSLStore)session.getStore(IMAP);
store.connect( host, userName, password ) ;
Folder folderInbox =store.getFolder(IMAP_FOLDER);
folderInbox.open(Folder.READ_ONLY);
// FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
// Message[] arrayMessages= folderInbox.search(ft);
Message[] arrayMessages = folderInbox.getMessages();
for (int i = 0; i < arrayMessages.length; i++) {
MimeMessage message = (MimeMessage) arrayMessages[i];
ByteArrayOutputStream bos = new ByteArrayOutputStream();
message.writeTo(bos);
bos.close();
SharedByteArrayInputStream bis =new SharedByteArrayInputStream(bos.toByteArray());
MimeMessage cmsg = new MimeMessage(session, bis);
bis.close();
String contentType = cmsg.getContentType();
String messageContent = "";
String megSubject = cmsg.getSubject().toString().trim();
if(megSubject.contains(configurationStringToCheckSubject.trim())){
if (contentType.contains("text/plain")
|| contentType.contains("text/html")) {
Object content = cmsg.getContent();
if (content != null) {
messageContent = content.toString().trim();
messageContent=messageContent.replaceAll("\\<.*?\\>", "");
messageContent=messageContent.replaceAll("\n", "");
// System.out.println("normal message is**********\n"+messageContent);
status=compareContents(messageContent, configurationStringToCheckBody);
if(status){
return megSubject;
}
}
}else if (contentType.contains(IMAP_CONTENT_TYPE)) {
Multipart multiPart = (Multipart) cmsg.getContent();
for (int partCount = 0; partCount < numberOfParts; partCount++) {
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
if (!Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
String messageContent1=getText(part) ;
messageContent+=messageContent1;
messageContent=messageContent.replaceAll("\n", "");
status=compareContents(messageContent, configurationStringToCheckBody);
if(status){
return megSubject;
}
}
}
}