java.lang.ClassCastException: java.lang.String 不能转换为 javax.mail.Multipart
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23116465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java.lang.ClassCastException: java.lang.String cannot be cast to javax.mail.Multipart
提问by user3542073
This is my code below taken from a java tutorial - however my issue comes in when I try and recieve a normal message sent from a computer, as opposed to sent through GMail. If I recieve the email through GMail it runs fine and returns the mail, however trying to retrieve a mail from a conventional desktop mail client returns
这是我从 Java 教程中获取的以下代码 - 但是当我尝试接收从计算机发送的普通消息而不是通过 GMail 发送时,我的问题就出现了。如果我通过 GMail 收到电子邮件,它运行良好并返回邮件,但是尝试从传统桌面邮件客户端检索邮件返回
Error:
错误:
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)
Code:
代码:
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();
}
采纳答案by Mani
Understand the Exception First!!!
首先了解异常!!!
Your message content returning String and you are trying to type cast to Multipart.
您的消息内容返回 String 并且您正在尝试将类型转换为 Multipart。
Object content = msg.getContent();
if (content instanceof String)
{
String body = (String)content;
...
}
else if (content instanceof Multipart)
{
Multipart mp = (Multipart)content;
...
}
回答by Bill Shannon
Not all messages are multipart. You need to understand the structure of MIME messages. Start with this JavaMail FAQ entry. Then look at the msgshow.java sample program.
并非所有消息都是多部分的。您需要了解 MIME 消息的结构。从这个 JavaMail FAQ 条目开始。然后查看msgshow.java 示例程序。