这是我下面的代码,取自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();
}
首先了解例外情况!!!
您的消息内容返回字符串,并且您正在尝试将类型转换为多部分。
Object content = msg.getContent();
if (content instanceof String)
{
String body = (String)content;
...
}
else if (content instanceof Multipart)
{
Multipart mp = (Multipart)content;
...
}
并非所有邮件都是由多个部分组成的。您需要理解MIME消息的结构。从这个JavaMail FAQ条目开始。然后看看msgshow.java的示例程序。