java - 使用Javamail获取附件

标签 java jakarta-mail imap

早上好,

我已经在这个项目上工作了几天,但现在已经停止了。下载附件似乎需要很长时间,而且似乎是在将文件写入磁盘行。我读过很多选项(FileChannel、bulk 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;
    }
}

函数.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");

下载 7mb 文件的时间从 128 秒缩短到 12 秒。

最佳答案

如果partialfetch为假,则不使用fetchsize;它将在一个请求中下载整个附件。只要您有足够的内存来容纳最大的附件,就可以了。否则,请将partialfetch设置为true(默认)并将fetchsize设置得足够大,以便在不使用过多内存的情况下提供合理的性能。

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

关于java - 使用Javamail获取附件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42352275/

相关文章:

java - 错误 : java. util.concurrent.ExecutionException : com. android.builder.internal.aapt.v2.Aapt2Exception:AAPT2 错误:查看日志了解详细信息

java - 在 java 中收集 arraylist 的更快方法

java - 将 Java Mail StartTLS 与信任库结合使用

exchange-server - 如何通过 IMAP 抑制已读回执?

python - 为什么 imaplib 在每封电子邮件后返回一个单独的括号?

Javax.Mail尝试使用gmail的imap扩展来访问X-GM-MSGID

java - org.springframework.beans.factory.UnsatisfiedDependencyException : Error creating bean. ..期望单个匹配的bean,但发现12

java - 我们需要在 Eclipse 中将 System.getProperty 的值传递到哪里

android - 如何使用javaxmail android读取gmail的已发送邮件

Javamail Pop3 session 超时?