以下是我从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();
}
String
和MultiPart
没有共同的继承关系,因此您无法将它们进行强制类型转换。 - Rogue