使用Javamail获取附件

时间:2017-02-20 18:54:55

标签: java javamail imap

早上好,

我已经在这个项目上工作了几天,并且已经停止了。下载附件似乎需要永远,它似乎是在磁盘行的写入文件。我已经阅读了很多选项(FileChannel,批量getContent和其他一些但不能使这个代码以合理的速率执行)我不确定是否唯一的瓶颈是从O365下载文件然而我想我会问一个问题,看看是否有人可以查看这段代码并希望告诉我我做错了什么。该应用程序的目标是登录Exchange Online(o365)并下载某个邮箱中的所有附件。请注意,此代码已被修改了很多次,以确定我是否可以通过使用线程等来提高性能:

正如我所说,我已经将所有内容转移到了很多地方,试图让这项工作更好,所以请不要因为某些代码没有太多意义而让我感到厌烦。我不想让其他人完成这个项目,我正在寻找一种我没有很多经验的语言的指导。

    package o365connect;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeBodyPart;

/**
 *
 * @author Charlie
 */
public class AttDownload extends Thread {
        public static int Lower = 0;
        public static int Upper = 0;
        public static int Counter = 0;
        public static Session session;
        public static Store store;
        public static Properties props = new Properties();
        public static boolean fTest = false;
    AttDownload(int i, int ii) {
        Lower = i;
        Upper = ii;
    }
    AttDownload() throws UnknownHostException {
        super();
    }
    @Override
    public void run() {
        String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
        String pop3Host = "outlook.office365.com";
        String mailStoreType = "imap";
        String path = "Inbox/Scans to file";
        String userName = "XXX@XXX.com";
        String password = "XXXXXXX";
        Folder emailFolder;
        try {
            props.setProperty("mail.imaps.socketFactory.class", SSL_FACTORY);
            props.setProperty("mail.imaps.socketFactory.fallback", "false");
            props.setProperty("mail.imaps.port", "993");
            props.setProperty("mail.imaps.socketFactory.port", "993");
            props.put("mail.imaps.host", "outlook.office365.com");
            session = Session.getInstance(props);
            int Size = functions.MBSize(pop3Host, userName, password, path);
            System.out.println(Size);
            store = session.getStore("imaps");
            store.connect(pop3Host, userName, password);
            emailFolder = store.getFolder(path);
            emailFolder.open(Folder.READ_ONLY);
            try {
                Message[] messages;
                messages = emailFolder.getMessages(Lower, Upper);
                System.out.println("starting thread for - " + Lower + " - " + Upper);
                int ASuc = receiveEmail(messages);
            } catch (MessagingException | IOException ex) {
                Logger.getLogger(AttDownload.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (NoSuchProviderException ex) {
            Logger.getLogger(AttDownload.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MessagingException ex) {
            Logger.getLogger(AttDownload.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public static int receiveEmail(Message messagesarr[]) throws IOException, MessagingException {
            for (Message messagesarr1 : messagesarr) {
                try {
                    Message message = messagesarr1;
                    Object content = message.getContent();
                    if (content instanceof String) {
                    } else if (content instanceof Multipart) {
                        Multipart multipart = (Multipart) message.getContent();
                        for (int k = 0; k < multipart.getCount(); k++) {
                            MimeBodyPart bodyPart = (MimeBodyPart) multipart.getBodyPart(k);
                            if (Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {
                                long startTime = System.currentTimeMillis();
                                int ran = (int) startTime;
                                String fileName;
                                String fName = bodyPart.getFileName();
                                if (fName != null && !fName.isEmpty()) {
                                    fileName = fName.replaceAll("\\s+", "");
                                } else {
                                    continue;
                                }
                                if ("ATT00001.txt".equals(fileName)) {
                                    continue;
                                } else {
                                    System.out.println("starting copy of - " + fileName);
                                }
                                String destFilePath = "D:/Scans/";
                                bodyPart.saveFile(destFilePath + bodyPart.getFileName());
                                long stopTime = System.currentTimeMillis();
                                System.out.println("finished copying of - " + fileName + "  -  " + (stopTime - startTime) + " miliseconds.");
                                System.out.println(Counter);
                                Counter++;
                            } else {
                            }
                        }

                    }
                }catch (MessagingException e) {
                    System.out.println(e);
                }
            }
        return 1;
    }
}

Functions.java

package o365connect;

import javax.mail.Folder;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
import static o365connect.AttDownload.store;

/**
 *
 * @author Oliver
 */
public class functions {

    public static int TestUser(String pop3host, String Username, String Password) throws NoSuchProviderException, MessagingException {
        try {
            Session session = Session.getInstance(AttDownload.props);
            store = session.getStore("imaps");
            store.connect(pop3host, Username, Password);
            return 0;
        } catch (MessagingException e) {
            System.out.println(e + "User Name Invalid");
            return 1;
        }
    }

    public static Folder TestFolder(Store store, String Path) throws MessagingException {
        Folder emailFolder;
        emailFolder = store.getFolder(Path);
        emailFolder.open(Folder.READ_ONLY);
        AttDownload.fTest = true;
        emailFolder.close(false);
        return emailFolder;
    }

    public static int MBSize(String pop3Host, String userName, String password, String Path) {
        int Size = 0;
        Session session = Session.getInstance(AttDownload.props);
        try {
            Store store = session.getStore("imaps");
            store.connect(pop3Host, userName, password);
            Folder emailFolder = store.getFolder(Path);
            emailFolder.open(Folder.READ_ONLY);
            Size = emailFolder.getMessageCount();
            emailFolder.close(false);
            store.close();
            return Size;
        } catch (MessagingException e) {
            System.out.println(e + "MBSize");
        }
        return Size;
    }
}

O365Connect.java

package o365connect;

import java.io.IOException;
import javax.mail.MessagingException;

public class O365Connect {



    public static void main(String[] args) throws IOException, MessagingException, InterruptedException {
        MainScreen ms = new MainScreen();
        ms.setVisible(true);
        AttDownload dl = new AttDownload(1, 1000);
       dl.start();

    }
}

编辑:

props.put("mail.imaps.fetchsize", "819200");
props.put("mail.imaps.partialfetch", "false");

加速,128秒到12秒下载7mb文件。

1 个答案:

答案 0 :(得分:2)

如果partialfetch为false,则不使用fetchsize;它将在一个请求中下载整个附件。只要你有足够的记忆力来获得最大可能的依恋,那就没问题了。否则,将partialfetch设置为true(默认值)并将fetchsize设置得足够大,以便在不使用过多内存的情况下提供合理的性能。

JavaMail属性在每个协议提供程序的页面上的javadocs中描述。例如,com.sun.mail.imap package javadoc page上描述了IMAP提供程序属性。