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();
    }
有帮助吗?

解决方案

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;  
    ...  
}  

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top