使用 Java Mail API 读取邮件内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19784271/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 20:10:47  来源:igfitidea点击:

Reading Mail Content Using Java Mail API

javajavamail

提问by Nag

I am able to get the from field and subject field correctly , But i am getting the Mail Content in Object Format even though i m using toString() method..

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

please check with the following source code

请检查以下源代码

    try {
        Session session = Session.getInstance(props, null);
        Store store = session.getStore();
        store.connect("imap.gmail.com", "[email protected]", "****");
        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 <[email protected]>
   SENT DATE:Tue Nov 05 12:28:24 IST 2013
   SUBJECT:test
  CONTENT:javax.mail.internet.MimeMultipart@5117f31e

回答by Petr Mensik

You need to iterate through all multiparts, then check MIMEtype of the Partin order to know if you have to treat it like a text or an attachment.

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

for(int i=0;i<multipart.getCount();i++) {
    BodyPart bodyPart = multipart.getBodyPart(i);
    if (bodyPart.isMimeType("text/*")) {
        String s = (String) bodyPart.getContent();
    }
}

回答by Dark Knight

bp.getContent().toString()

bp.getContent().toString()

will give you mail body only when your mail is not multipart(ie if your mail is multipart mail then it will not work)

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