我正在尝试阅读我的消息,我可以让它打印标题,但来自和内容显示有趣。 这是我用来显示消息的代码:
int j = message.length-1;
for (int i=j;i>=0;i--) {
System.out.println("Message " + (i + 1));
System.out.println("From : " + message[i].getFrom());
System.out.println("Subject : " + message[i].getSubject());
try {
System.out.println("Body: " + message[i].getContent());
} catch (IOException ex) {
System.out.println(ex);
}
}
输出如下:
Message 1:
From: [javax.mail.internet.InternetAddress;@175831e]
Subject: Hello //This is correct
Body: javax.mail.internet.MimeMultipart@15b5219
为什么不打印from语句的实际电子邮件地址?为什么不打印实际的身体内容? (我只对纯文本感兴趣。)
整个代码:
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.search.*;
import java.util.*;
import com.sun.mail.imap.*;
import java.io.*;
public class MailClient {
public static void main(String[] args) {
try {
Properties props = new Properties();
props.put("mail.store.protocol","imaps");
Session session;
session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com","email@gmail.com","password");
IMAPFolder folder = (IMAPFolder) store.getFolder("inbox");
folder.open(Folder.READ_ONLY);
Flags seen = new Flags(Flags.Flag.SEEN);
FlagTerm unseenFlagTerm = new FlagTerm(seen,false);
Message message[] = folder.search(unseenFlagTerm);
int j = message.length-1;
for (int i=j;i>=0;i--) {
System.out.println("Message " + (i + 1));
System.out.println("From : " + message[i].getFrom());
System.out.println("Subject : " + message[i].getSubject());
try {
System.out.println("Body: " + message[i].getContent());
} catch (IOException ex) {
System.out.println(ex);
}
}
System.out.println(newMsg);
folder.close(false);
store.close();
}
catch (MessagingException e) {
System.out.println("Error: " + e);
}
}
}
谢谢!
答案 0 :(得分:7)
对于纯文本和HTML消息:
String content= messages[i].getContent().toString();
对于多部分消息:
Multipart multipart = (Multipart) messages[i].getContent();
for (int j = 0; j < multipart.getCount(); j++) {
BodyPart bodyPart = multipart.getBodyPart(j);
String disposition = bodyPart.getDisposition();
if (disposition != null && (disposition.equalsIgnoreCase("ATTACHMENT"))) { // BodyPart.ATTACHMENT doesn't work for gmail
System.out.println("Mail have some attachment");
DataHandler handler = bodyPart.getDataHandler();
System.out.println("file name : " + handler.getName());
}
else {
System.out.println("Body: "+bodyPart.getContent());
content= bodyPart.getContent().toString();
}
答案 1 :(得分:3)
JavaMail常见问题解答告诉您如何access the main text body of a message。
答案 2 :(得分:2)
更改此
message[i].getFrom()
到
message[i].getFrom()[0].toString())
答案 3 :(得分:0)
尝试使用下一个:
message[i].writeTo(System.out);