1

我能够正确获取 from 字段和主题字段,但是即使我使用 toString() 方法,我也会以对象格式获取邮件内容。

请检查以下源代码

    try {
        Session session = Session.getInstance(props, null);
        Store store = session.getStore();
        store.connect("imap.gmail.com", "mymail@gmail.com", "****");
        Folder inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_ONLY);
        Message msg = inbox.getMessage(inbox.getMessageCount());
        Address[] in = msg.getFrom();
        for (Address address : in) {
            System.out.println("FROM:" + address.toString());
        }

        Object obj = msg.getContent();
        //Multipart mp = (Multipart)obj;

        Multipart mp = (Multipart) msg.getContent();
       // MimeBodyPart part = (MimeBodyPart)mp.getBodyPart(0);
        BodyPart bp = ((Multipart) msg.getContent()).getBodyPart(0);

        // Object body = msg.getContent();

        //String value = String.valueOf(body);

        System.out.println("SENT DATE:" + msg.getSentDate());
        System.out.println("SUBJECT:" + msg.getSubject());
        System.out.println("CONTENT:" + bp.getContent().toString());
    } catch (Exception mex) {
        mex.printStackTrace();
    }
}

}

    output console:

   FROM:Myname <mymail@gmail.com>
   SENT DATE:Tue Nov 05 12:28:24 IST 2013
   SUBJECT:test
  CONTENT:javax.mail.internet.MimeMultipart@5117f31e
4

2 回答 2

6

您需要遍历所有多部分,然后检查MIME类型Part以了解是否必须将其视为文本或附件。

for(int i=0;i<multipart.getCount();i++) {
    BodyPart bodyPart = multipart.getBodyPart(i);
    if (bodyPart.isMimeType("text/*")) {
        String s = (String) bodyPart.getContent();
    }
}
于 2013-11-05T08:12:32.627 回答
1

bp.getContent().toString()

只有当您的邮件不是多部分邮件时才会给您邮件正文(即,如果您的邮件是多部分邮件,那么它将不起作用)

于 2013-11-05T08:13:07.800 回答