为什么我不能使用toString解析javamail附件?

时间:2010-08-10 22:31:05

标签: java android imap javamail multipart

在我看来,下面的代码段应该有效,但是“mp.getBodyPart(1).getContent()。toString()”返回

  

com.sun.mail.util.BASE64DecoderStream@44b07df8

而不是附件的内容。

public class GMailParser {
    public String getParsedMessage(Message message) throws Exception {
        try {
            Multipart mp = (Multipart) message.getContent();
            String s = mp.getBodyPart(1).getContent().toString();
            if (s.contains("pattern 1")) {
                return "return 1";
            } else if (s.contains("pattern 2")) {
                return "return 2";
            }
            ...

2 个答案:

答案 0 :(得分:3)

它只是意味着BASE64DecoderStream类不提供自定义toString定义。默认的toString定义是显示类名+'@'+ Hash Code,这就是你所看到的。

要获取Stream的“内容”,您需要使用read()方法。

答案 1 :(得分:1)

这将根据需要完全解析BASE64DecoderStream附件。

private String getParsedAttachment(BodyPart bp) throws Exception {
    InputStream is = null;
    ByteArrayOutputStream os = null;
    try {
        is = bp.getInputStream();
        os = new ByteArrayOutputStream(256);
        int c = 0;
        while ((c = is.read()) != -1) {
            os.write(c);
        }
        String s = os.toString(); 
        if (s.contains("pattern 1")) { 
            return "return 1"; 
        } else if (s.contains("pattern 2")) { 
            return "return 2"; 
        } 
        ...