简体   繁体   中英

Unable to download PDF attachment with java by using JavaMail

I am creating Email client using JavaMail API. Everything is working fine like I am able to connect to mail server(using IMAP), Delete mail, retrieving received mails and displaying them to user etc.

Now problem comes when it comes to download "PDF Attachments". PDF files are not downloading completely... it is missing some contains.

If some PDF attachment is of size 38 Kb when I am downloading attachment using IE or any other web browser but when I am downloading it using my java code it is of size 37.3 Kb. It is not complete Hence when I try to open it using Adobe Reader it shows error message that "File is corrupted..."

Here is code I have written to download attachment:

public boolean saveFile(String filename,Part part) throws IOException, MessagingException {
    boolean ren = true;
    FileOutputStream fos = null;
    BufferedInputStream fin = null;
    InputStream input = part.getInputStream();

    File pdffile = new File("d:/"+filename);
    try{
        if(!pdffile.exists()){
            fos = new FileOutputStream(pdffile);
            fin = new BufferedInputStream(input);
            int size = 512;
            byte[] buf = new byte[size];
            int len;

            while ( (len = fin.read(buf)) != -1 ) {
                fos.write(buf, 0, len);
            }

            input.close();
            fos.close();
        }else{
            System.out.println("File already exists");
        }
    }catch(Exception e ){
        ren = false;
    }
    return ren;
 }

Am I missing something? Any useful help is appreciated.

Spent a few hours on this and finally figured it out.

props.setProperty("mail.imaps.partialfetch", "false");

did it for me. Almost the same thing as @Shantanu above, but because I was using

store = session.getStore("imaps");

I needed to use "imap s " for the partialfetch as well.

Works like a charm.

Full code below:

// Load mail properties
Properties mailProperties = System.getProperties();
mailProperties.put("mail.mime.base64.ignoreerrors", "true");
mailProperties.put("mail.imaps.partialfetch", "false");

// Connect to Gmail
Session session = Session.getInstance(mailProperties, null);
store = session.getStore("imaps");
store.connect("imap.gmail.com", -1, "username", "password");

// Access label folder
Folder defaultFolder = store.getDefaultFolder();
Folder labelFolder = defaultFolder.getFolder("mylabel");
labelFolder.open(Folder.READ_WRITE);

Message[] messages = labelFolder.getMessages();

saveAttachments(messages);

...

 private void saveAttachments(Message[] messages) throws Exception {

 for (Message msg : messages) {


    if (msg.getContent() instanceof Multipart) {
      Multipart multipart = (Multipart) msg.getContent();

      for (int i = 0; i < multipart.getCount(); i++) {
        Part part = multipart.getBodyPart(i);
    String disposition = part.getDisposition();

    if ((disposition != null) && 
       ((disposition.equalsIgnoreCase(Part.ATTACHMENT) || 
       (disposition.equalsIgnoreCase(Part.INLINE))))) {
        MimeBodyPart mimeBodyPart = (MimeBodyPart) part;
        String fileName = mimeBodyPart.getFileName();

        File fileToSave = new File(fileName);
        mimeBodyPart.saveFile(fileToSave);
     }
        }
      }
    }
}

Finally I found solution at JavaMail FAQ Reading Mail, IMAP section Gmail server is running bug with attachments

First I tried to set partialfetch property false but sometimes it works sometimes it doesn't

    props.setProperty("mail.imap.partialfetch", "false");

There is another way listed in FAQ which is just use copy constructor of MimeMessage and store orignal object in some tempmsg and then get content of tempmsg

    MimeMessage tempmsg = new MimeMessage(msg);
    Multipart part = (Multipart) tempmsg.getContent();

and now perform all operations it should work..

For detailed information about what actually happens goto JavaMail FAQ Reading Mail, IMAP section you will find all answers..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM