Download attachments using Java Mail

前端 未结 4 1658
自闭症患者
自闭症患者 2020-11-28 03:36

Now that I`ve downloaded all the messages, and store them to

Message[] temp;

How do I get the list of attachments for each of those message

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 04:05

    Without exception handling, but here goes:

    List attachments = new ArrayList();
    for (Message message : temp) {
        Multipart multipart = (Multipart) message.getContent();
    
        for (int i = 0; i < multipart.getCount(); i++) {
            BodyPart bodyPart = multipart.getBodyPart(i);
            if(!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) &&
                   StringUtils.isBlank(bodyPart.getFileName())) {
                continue; // dealing with attachments only
            } 
            InputStream is = bodyPart.getInputStream();
            // -- EDIT -- SECURITY ISSUE --
            // do not do this in production code -- a malicious email can easily contain this filename: "../etc/passwd", or any other path: They can overwrite _ANY_ file on the system that this code has write access to!
    //      File f = new File("/tmp/" + bodyPart.getFileName());
            FileOutputStream fos = new FileOutputStream(f);
            byte[] buf = new byte[4096];
            int bytesRead;
            while((bytesRead = is.read(buf))!=-1) {
                fos.write(buf, 0, bytesRead);
            }
            fos.close();
            attachments.add(f);
        }
    }
    

提交回复
热议问题