这是我从java教程中获取的代码 - 但是当我尝试接收从计算机发送的正常消息时,我的问题就出现了,而不是通过GMail发送。如果我通过GMail收到电子邮件,它运行正常并返回邮件,但尝试从传统的桌面邮件客户端检索邮件返回
错误:
java.lang.ClassCastException: java.lang.String cannot be cast to javax.mail.Multipart
at gridnotifierproject_pcbuild.HandleMailInput.retrieveOneMail(HandleMailInput.java:37)
at gridnotifierproject_pcbuild.GridNotifierProject_PCBuild.main(GridNotifierProject_PCBuild.java:22)
代码:
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getInstance(props, null);
Store store = session.getStore();
store.connect("imap.gmail.com", "***********@gmail.com", "******");
System.out.println("Established Connection to Server!");
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
Message msg = inbox.getMessage(inbox.getMessageCount());
System.out.println("Found specified Folder, retrieving the latest message...");
Address[] in = msg.getFrom();
for (Address address : in) {
System.out.println("FROM:" + address.toString());
}
Multipart mp = (Multipart) msg.getContent();
BodyPart bp = mp.getBodyPart(0);
System.out.println("SENT DATE:" + msg.getSentDate());
System.out.println("SUBJECT:" + msg.getSubject());
System.out.println("CONTENT:" + bp.getContent());
} catch (Exception mex) {
mex.printStackTrace();
}
答案 0 :(得分:6)
首先了解异常!!!
您的邮件内容返回String并且您正尝试将强制转换为Multipart。
Object content = msg.getContent();
if (content instanceof String)
{
String body = (String)content;
...
}
else if (content instanceof Multipart)
{
Multipart mp = (Multipart)content;
...
}
答案 1 :(得分:1)
并非所有消息都是多部分的。您需要了解MIME消息的结构。从this JavaMail FAQ entry开始。然后查看msgshow.java sample program。