使用 JavaMail 从 GMail 读取完整的电子邮件

Reading the full email from GMail using JavaMail(使用 JavaMail 从 GMail 读取完整的电子邮件)

本文介绍了使用 JavaMail 从 GMail 读取完整的电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 javamail,但无法从我的 gmail 电子邮件中获取 HTML.我有以下内容:

I am making use of javamail and I am having trouble getting the HTML from my gmail emails. I have the following:

Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "myemail@gmail.com", "password");
System.out.println(store);

Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
Message messages[] = inbox.getMessages();
for(Message message:messages) {
System.out.println(message); // com.sun.mail.imap.IMAPInputStream@cec0c5

以上都可以正常工作,但我无法打印或获取实际的 HTML 或文本电子邮件.我刚刚得到了某种 InputStream,我该如何轻松处理以获取电子邮件的原始 HTML?

The above all works fine but I can't print or get the actual HTML or Text email. I just get some sort of InputStream, how do I deal with this easily to get the raw HTML of the email?

我也尝试循环浏览消息,但这并没有让我走得太远:

I also tried looping through the message but that didn't get me very far:

Message message[] = inbox.getMessages();

    for (int i=0, n=message.length; i<n; i++) {
       System.out.println(i + ": " + message[i].getFrom()[0] 
         + "	" + message[i].getSubject());
       String content = message[i].getContent().toString();
       if (content.length() > 200) 
    content = content.substring(0, 600);
       System.out.print(content);

}

感谢大家的帮助.

推荐答案

InputStream 对象包含电子邮件的正文.您需要阅读整个流以阅读整个消息正文.例如,这篇 SO 帖子 详细介绍了如何使用 Apache 库将整个 InputStream 写入 OutputStream,例如 System.out.这将是一个很好的起点,因为您可以将整个消息正文打印到控制台.否则,您需要使用一些缓冲区等,将数据从流中拉出并将其放入您想要放入的任何内容中.还有 this SO post 详细说明,使用相同的库,如何转换 InputStream 转换成 String.

The InputStream object contains the body of the email. You need to read the entirety of the stream to read the entire body of the message. For instance, this SO post details how to write an entire InputStream to an OutputStream such as System.out using an Apache library. That would be a good place to start as you could print the entire message body to the console. Otherwise, you'll need to use some buffers, etc, to pull the data out of the stream and put it into whatever you want to put it in. There is also this SO post that details, using the same library, how to convert an InputStream into a String.

这篇关于使用 JavaMail 从 GMail 读取完整的电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:使用 JavaMail 从 GMail 读取完整的电子邮件

基础教程推荐