java gmail imap,使用JavaMail从GMail中读取完整的电子邮件

在使用JavaMail处理Gmail IMAP时,遇到问题无法直接获取HTML邮件内容,只得到InputStream。要读取邮件的完整HTML,需要处理InputStream。可以参考Stack Overflow上的帖子,使用Apache库将InputStream转换为OutputStream打印整个邮件正文,或者通过缓冲区提取数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

System.out.println(i + ": " + message[i].getFrom()[0]

+ "\t" + message[i].getSubject());

String content = message[i].getContent().toString();

if (content.length() > 200)

content = content.substring(0, 600);

System.out.print(content);

}

Thanks all for any hlep.

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值