问题描述
我正在使用javax.mail开发客户端邮件以读取邮箱内的邮件:
i'm developing a client mail using javax.mail to read mail inside mail box:
Properties properties = System.getProperties();
properties.setProperty("mail.store.protocol", "imap");
try {
Session session = Session.getDefaultInstance(properties, null);
Store store = session.getStore("pop3");//create store instance
store.connect("pop3.domain.it", "mail.it", "*****");
Folder inbox = store.getFolder("inbox");
FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
inbox.open(Folder.READ_ONLY);//set access type of Inbox
Message messages[] = inbox.search(ft);
String mail,sub,bodyText="";
Object body;
for(Message message:messages) {
mail = message.getFrom()[0].toString();
sub = message.getSubject();
body = message.getContent();
//bodyText = body.....
}
} catch (Exception e) {
System.out.println(e);
}
我知道方法 getContent()
返回一个对象,因为内容可能是 String
,一个 MimeMultiPart
,一个 SharedByteArrayInputstream
和其他(我认为)...有没有办法在消息正文中获取文本?谢谢!!
I know that the method getContent()
returns an object cause the content could be a String
, a MimeMultiPart
, a SharedByteArrayInputstream
and other ( i think )... Is there a way to get always the text inside body of message? Thanks!!
推荐答案
此答案扩展。他提出的问题是 MimeMultipart
的内容本身可能是另一个 MimeMultipart
。下面的 getTextFromMimeMultipart()
方法在这种情况下对内容进行递归,直到消息体被完全解析为止。
This answer extends yurin's answer. The issue he brought up was that the content of a MimeMultipart
may itself be another MimeMultipart
. The getTextFromMimeMultipart()
method below recurses in such cases on the content until the message body has been fully parsed.
private String getTextFromMessage(Message message) throws MessagingException, IOException {
String result = "";
if (message.isMimeType("text/plain")) {
result = message.getContent().toString();
} else if (message.isMimeType("multipart/*")) {
MimeMultipart mimeMultipart = (MimeMultipart) message.getContent();
result = getTextFromMimeMultipart(mimeMultipart);
}
return result;
}
private String getTextFromMimeMultipart(
MimeMultipart mimeMultipart) throws MessagingException, IOException{
String result = "";
int count = mimeMultipart.getCount();
for (int i = 0; i < count; i++) {
BodyPart bodyPart = mimeMultipart.getBodyPart(i);
if (bodyPart.isMimeType("text/plain")) {
result = result + "\n" + bodyPart.getContent();
break; // without break same text appears twice in my tests
} else if (bodyPart.isMimeType("text/html")) {
String html = (String) bodyPart.getContent();
result = result + "\n" + org.jsoup.Jsoup.parse(html).text();
} else if (bodyPart.getContent() instanceof MimeMultipart){
result = result + getTextFromMimeMultipart((MimeMultipart)bodyPart.getContent());
}
}
return result;
}
这篇关于如何使用javax.mail读取邮件正文中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!