java.lang.ClassCastException: java.lang.String cannot be cast to javax.mail.Multipart

爱⌒轻易说出口 提交于 2019-12-13 04:41:40

问题


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

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();
    }

回答1:


Understand the Exception First!!!

Your message content returning String and you are trying to type cast to Multipart.

Object content = msg.getContent();  
if (content instanceof String)  
{  
    String body = (String)content;  
    ...  
}  
else if (content instanceof Multipart)  
{  
    Multipart mp = (Multipart)content;  
    ...  
}  



回答2:


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.



来源:https://stackoverflow.com/questions/23116465/java-lang-classcastexception-java-lang-string-cannot-be-cast-to-javax-mail-mult

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!