I am trying to read my messages, I can get it to print the header but the from and the content are displayed funny. Here is the code I am using to display the messages:
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);
}
}
The output is as follows:
Message 1:
From: [javax.mail.internet.InternetAddress;@175831e]
Subject: Hello //This is correct
Body: javax.mail.internet.MimeMultipart@15b5219
Why doesn't this print out the actual email address for the from statement? And why doesn't it print out the actual body content? (I am only interesting in the plain text.)
Whole code:
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);
}
}
}
Thanks!
change this
to
For plain text and html messages:
String content= messages[i].getContent().toString();
For Multipart Messages:
The JavaMail FAQ tells you how to access the main text body of a message.
Try to use next: