Get attachment contents using javamail

I use javamail to automate email processing.

I managed to get a connection to the pop3 server and get messages. Some of them contain an attachment. Based on the email header, I can β€œpredict” the file name of the attachment I need to receive.

But I can not get its contents :(

I have a function

public byte[] searchForContent(Part part,String fileName){
    if(part.getFileName()!=null){
        if(part.getFileName().equals(fileName)){
            byte[] content = new byte[part.getSize()];
            part.getInputStream().read(content);
            return content[]
        }
    }
    return null;
}

The function works very well (i.e. returning the content only if this part was the attachment described by fileName). But the array returns it too large.

A loaded attachment is 256 bytes long, and the function returns content of 352 bytes long.

I think the problem comes from the headers, but I cannot be sure.

How can you go only to the content?

Thank.

+3
2

- .

eaj: part.getSize() . .

InputStream, part.getInputStream(), .

, :

public byte[] searchForContent(Part part,String fileName){
    if(part.getFileName()!=null){
        if(part.getFileName().equals(fileName)){
            InputStream stream=part.getInputStream();

            byte[] buffer = new byte[512];
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            int bytesRead;
            while ((bytesRead = stream.read(buffer) != -1)
            {
                baos.write(buffer, 0, bytesRead);
            }
            return baos.toByteArray();
        }
    }
    return null;
}
0

, API javax.mail.Part.getSize()

, - . , .

, , , , Part.getContent() . getContent() , , (, ).

0

Source: https://habr.com/ru/post/1775728/


All Articles