当前位置: 首页 > 面试题库 >

使用Java下载邮件附件

赵俊侠
2023-03-14
问题内容

我查看了参考文档,Spring似乎对发送邮件有很好的支持。但是,我需要登录到邮件帐户,阅读邮件并下载所有附件。Spring mail
API是否支持下载邮件附件?

我知道您可以使用Java Mail API来执行此操作,但是在过去,我发现使用它非常冗长且令人不愉快。

编辑 :我收到了一些指向教程的答复,这些教程描述了如何发送带有附件的邮件,但是我要问的是如何从 收到的 邮件中 读取 附件。

干杯,唐


问题答案:

这是我用于下载电子邮件(带有附件处理)的类。您必须浏览一下它正在做的一些事情(例如忽略日志记录类和数据库写操作)。为了方便阅读,我还对一些软件包进行了重命名。

通常的想法是,所有附件都保存为文件系统中的单个文件,每封电子邮件都保存为数据库中的记录,其中包含一组指向所有附件文件路径的子记录。

专注于doEMailDownload方法。

/**
  * Copyright (c) 2008 Steven M. Cherry
  * All rights reserved.
  */
package utils.scheduled;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Timestamp;
import java.util.Properties;
import java.util.Vector;

import javax.mail.Address;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeBodyPart;

import glob.ActionLogicImplementation;
import glob.IOConn;
import glob.log.Log;
import logic.utils.sql.Settings;
import logic.utils.sqldo.EMail;
import logic.utils.sqldo.EMailAttach;

/**
  * This will connect to our incoming e-mail server and download any e-mails
  * that are found on the server.  The e-mails will be stored for further processing
  * in our internal database.  Attachments will be written out to separate files
  * and then referred to by the database entries.  This is intended to be  run by 
  * the scheduler every minute or so.
  *
  * @author Steven M. Cherry
  */
public class DownloadEMail implements ActionLogicImplementation {

    protected String receiving_host;
    protected String receiving_user;
    protected String receiving_pass;
    protected String receiving_protocol;
    protected boolean receiving_secure;
    protected String receiving_attachments;

    /** This will run our logic */
    public void ExecuteRequest(IOConn ioc) throws Exception {
        Log.Trace("Enter");

        Log.Debug("Executing DownloadEMail");
        ioc.initializeResponseDocument("DownloadEMail");

        // pick up our configuration from the server:
        receiving_host = Settings.getValue(ioc, "server.email.receiving.host");
        receiving_user = Settings.getValue(ioc, "server.email.receiving.username");
        receiving_pass = Settings.getValue(ioc, "server.email.receiving.password");
        receiving_protocol = Settings.getValue(ioc, "server.email.receiving.protocol");
        String tmp_secure = Settings.getValue(ioc, "server.email.receiving.secure");
        receiving_attachments = Settings.getValue(ioc, "server.email.receiving.attachments");

        // sanity check on the parameters:
        if(receiving_host == null || receiving_host.length() == 0){
            ioc.SendReturn();
            ioc.Close();
            Log.Trace("Exit");
            return; // no host defined.
        }
        if(receiving_user == null || receiving_user.length() == 0){
            ioc.SendReturn();
            ioc.Close();
            Log.Trace("Exit");
            return; // no user defined.
        }
        if(receiving_pass == null || receiving_pass.length() == 0){
            ioc.SendReturn();
            ioc.Close();
            Log.Trace("Exit");
            return; // no pass defined.
        }
        if(receiving_protocol == null || receiving_protocol.length() == 0){
            Log.Debug("EMail receiving protocol not defined, defaulting to POP");
            receiving_protocol = "POP";
        }
        if(tmp_secure == null || 
            tmp_secure.length() == 0 ||
            tmp_secure.compareToIgnoreCase("false") == 0 ||
            tmp_secure.compareToIgnoreCase("no") == 0
        ){
            receiving_secure = false;
        } else {
            receiving_secure = true;
        }
        if(receiving_attachments == null || receiving_attachments.length() == 0){
            Log.Debug("EMail receiving attachments not defined, defaulting to ./email/attachments/");
            receiving_attachments = "./email/attachments/";
        }

        // now do the real work.
        doEMailDownload(ioc);

        ioc.SendReturn();
        ioc.Close();
        Log.Trace("Exit");
    }

    protected void doEMailDownload(IOConn ioc) throws Exception {
        // Create empty properties
        Properties props = new Properties();
        // Get the session
        Session session = Session.getInstance(props, null);

        // Get the store
        Store store = session.getStore(receiving_protocol);
        store.connect(receiving_host, receiving_user, receiving_pass);

        // Get folder
        Folder folder = store.getFolder("INBOX");
        folder.open(Folder.READ_WRITE);

        try {

            // Get directory listing
            Message messages[] = folder.getMessages();

            for (int i=0; i < messages.length; i++) {
                // get the details of the message:
                EMail email = new EMail();
                email.fromaddr = messages[i].getFrom()[0].toString();
                Address[] to = messages[i].getRecipients(Message.RecipientType.TO);
                email.toaddr = "";
                for(int j = 0; j < to.length; j++){
                    email.toaddr += to[j].toString() + "; ";
                }
                Address[] cc;
                try {
                    cc = messages[i].getRecipients(Message.RecipientType.CC);
                } catch (Exception e){
                    Log.Warn("Exception retrieving CC addrs: %s", e.getLocalizedMessage());
                    cc = null;
                }
                email.cc = "";
                if(cc != null){
                    for(int j = 0; j < cc.length; j++){
                        email.cc += cc[j].toString() + "; ";
                    }
                }
                email.subject = messages[i].getSubject();
                if(messages[i].getReceivedDate() != null){
                    email.received_when = new Timestamp(messages[i].getReceivedDate().getTime());
                } else {
                    email.received_when = new Timestamp( (new java.util.Date()).getTime());
                }


                email.body = "";
                Vector<EMailAttach> vema = new Vector<EMailAttach>();
                Object content = messages[i].getContent();
                if(content instanceof java.lang.String){
                    email.body = (String)content;
                } else if(content instanceof Multipart){
                    Multipart mp = (Multipart)content;

                    for (int j=0; j < mp.getCount(); j++) {
                        Part part = mp.getBodyPart(j);

                        String disposition = part.getDisposition();

                        if (disposition == null) {
                            // Check if plain
                            MimeBodyPart mbp = (MimeBodyPart)part;
                            if (mbp.isMimeType("text/plain")) {
                                Log.Debug("Mime type is plain");
                                email.body += (String)mbp.getContent();
                            } else {
                                Log.Debug("Mime type is not plain");
                                // Special non-attachment cases here of 
                                // image/gif, text/html, ...
                                EMailAttach ema = new EMailAttach();
                                ema.name = decodeName(part.getFileName());
                                File savedir = new File(receiving_attachments);
                                savedir.mkdirs();
                                File savefile = File.createTempFile("emailattach", ".atch", savedir );
                                ema.path = savefile.getAbsolutePath();
                                ema.size = part.getSize();
                                vema.add(ema);
                                ema.size = saveFile(savefile, part);
                            }
                        } else if ((disposition != null) && 
                            (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE) ) 
                        ){
                            // Check if plain
                            MimeBodyPart mbp = (MimeBodyPart)part;
                            if (mbp.isMimeType("text/plain")) {
                                Log.Debug("Mime type is plain");
                                email.body += (String)mbp.getContent();
                            } else {
                                Log.Debug("Save file (%s)", part.getFileName() );
                                EMailAttach ema = new EMailAttach();
                                ema.name = decodeName(part.getFileName());
                                File savedir = new File(receiving_attachments);
                                savedir.mkdirs();
                                File savefile = File.createTempFile("emailattach", ".atch", savedir );
                                ema.path = savefile.getAbsolutePath();
                                ema.size = part.getSize();
                                vema.add(ema);
                                ema.size = saveFile( savefile, part);
                            }
                        }
                    }
                }

                // Insert everything into the database:
                logic.utils.sql.EMail.insertEMail(ioc, email);
                for(int j = 0; j < vema.size(); j++){
                    vema.get(j).emailid = email.id;
                    logic.utils.sql.EMail.insertEMailAttach(ioc, vema.get(j) );
                }

                // commit this message and all of it's attachments
                ioc.getDBConnection().commit();

                // Finally delete the message from the server.
                messages[i].setFlag(Flags.Flag.DELETED, true);
            }

            // Close connection 
            folder.close(true); // true tells the mail server to expunge deleted messages.
            store.close();
        } catch (Exception e){
            folder.close(true); // true tells the mail server to expunge deleted messages.
            store.close();
            throw e;
        }

    }

    protected int saveFile(File saveFile, Part part) throws Exception {

        BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(saveFile) );

        byte[] buff = new byte[2048];
        InputStream is = part.getInputStream();
        int ret = 0, count = 0;
        while( (ret = is.read(buff)) > 0 ){
            bos.write(buff, 0, ret);
            count += ret;
        }
        bos.close();
        is.close();
        return count;
    }

    protected String decodeName( String name ) throws Exception {
        if(name == null || name.length() == 0){
            return "unknown";
        }
        String ret = java.net.URLDecoder.decode( name, "UTF-8" );

        // also check for a few other things in the string:
        ret = ret.replaceAll("=\\?utf-8\\?q\\?", "");
        ret = ret.replaceAll("\\?=", "");
        ret = ret.replaceAll("=20", " ");

        return ret;
    }

}


 类似资料:
  • 如何从内容类型为“多部分/备选”的邮件中下载附件;

  • 我正在一个apache camel项目中下载收件箱中的任何附件,以实现我遵循http://camel.apache.org/mail.html中使用附件的邮件示例中的信息。除了附件的文件名带有特殊的字符或空格外,其他操作都很正常。例如,如果附件的文件名为“voucher.pdf”,则程序将运行并下载该文件,但如果附件的文件名为“Pase de abordar en Línea(1).pdf”,则会

  • 问题内容: 我编写了一些代码来下载我所做的网络广播的一集。它获取剧集的URL,并获取保存它的位置。但是,它最多只能下载16MB,然后自动取消。我不完全确定要增加此值需要更改什么值。是否可以,有人可以指出正确的方向吗?谢谢! 下载代码: 问题答案: 快速查看transferFrom的文档: 好。 计数的值1 << 24(来自原始问题)等于16M 我想这就是您的问题的答案:-)

  • 我写的剧本的最终目标是从rally下载所有附件。我能够成功地连接到服务器,请求工作区中的所有附件,最后,通过迭代检索每个附件的内容。这将生成“AttachmentContent”的动态对象。对于任何API来说都是新的#和。NET,我现在被卡住了。我无法找到一种方法来访问此对象的内容并将其下载到我的计算机上的文件中。我在下面评论的这句话是我当前遇到错误并被卡住的地方。任何帮助都将不胜感激。提前谢谢!

  • 本文向大家介绍java、javascript实现附件下载示例,包括了java、javascript实现附件下载示例的使用技巧和注意事项,需要的朋友参考一下 在web开发中,经常需要开发“下载”这一模块,以下给出一个简单的例子。 在服务器端,使用java开发: 当我们在前端请求这个地址时,服务器先找出文件,设置响应头,然后通过流输出到浏览器端。 浏览器在头中发现该响应的主体是流文件,则自动会调用另存

  • 我试图通过javamail和imap从我的电子邮件下载所有新的电子邮件附件。这一切都很好,但有些附件在PDF中被解码为BASE64,这是我的声明 如何获取此附件并将其下载到硬盘? 到目前为止已经尝试过了,第一个IF语句使用Base64解码捕获附件。 如果有一种简单易行的方法可以将附件下载到我的磁盘,也可以使用NodeJS。尝试过node-imap,但我在那里遇到了同样的错误。