使用Java下载邮件附件 [英] download mail attachment with Java

查看:124
本文介绍了使用Java下载邮件附件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看了参考文档,而Spring似乎对发送邮件有很好的支持。但是,我需要登录一个邮件帐户,阅读消息,并下载任何附件。是否正在下载Spring邮件API支持的邮件附件?



我知道您可以使用Java Mail API执行此操作,但是在过去我发现,不愉快的工作。



编辑:我收到了几则回复,指出教程描述如何使用附件发送邮件,但是我请问关于如何从收到邮件 读取附件。



干杯,
Don

解决方案

这是我用于下载电子邮件(附件处理)的类。你必须看看它正在做的一些事情(比如忽略日志记录类和数据库写入)。我也重新命名了一些软件包,方便阅读。



一般的想法是,所有附件都被保存为文件系统中的单个文件,每个e -mail将作为记录保存在数据库中,并带有指向所有附件文件路径的一组子记录。



专注于doEMailDownload方法。 >

  / ** 
*版权所有(c)2008 Steven M. Cherry
*保留所有权利。
* /
包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;

/ **
*这将连接到我们的传入电子邮件服务器,并下载在服务器上找到的任何电子邮件
*。电子邮件将被存储在我们的内部数据库中进一步处理
*。附件将被写出来分开文件
*,然后由数据库条目引用。这是由
*调度程序每分钟左右运行。
*
* @author Steven M. Cherry
* /
public class DownloadEMail implements ActionLogicImplementation {

protected String receiving_host;
protected String receive_user;
protected String receive_pass;
protected String receive_protocol;
protected boolean receive_secure;
protected String receive_attachments;

/ **这将运行我们的逻辑* /
public void ExecuteRequest(IOConn ioc)throws Exception {
Log.Trace(Enter);

Log.Debug(执行下载文件);
ioc.initializeResponseDocument(DownloadEMail);

//从服务器接收配置:
received_host = Settings.getValue(ioc,server.email.receiving.host);
received_user = Settings.getValue(ioc,server.email.receiving.username);
received_pa​​ss = Settings.getValue(ioc,server.email.receiving.password);
received_protocol = Settings.getValue(ioc,server.email.receiving.protocol);
String tmp_secure = Settings.getValue(ioc,server.email.receiving.secure);
received_attachments = Settings.getValue(ioc,server.email.receiving.attachments);

//对性能检查参数:
if(receiving_host == null || received_host.length()== 0){
ioc.SendReturn();
ioc.Close();
Log.Trace(退出);
return; //没有主机定义。
}
if(received_user == null || received_user.length()== 0){
ioc.SendReturn();
ioc.Close();
Log.Trace(退出);
return; //没有用户定义
}
if(receiving_pass == null || received_pa​​ss.length()== 0){
ioc.SendReturn();
ioc.Close();
Log.Trace(退出);
return; //没有通过定义。
}
if(received_protocol == null || received_protocol.length()== 0){
Log.Debug(EMail接收协议未定义,默认为POP);
received_protocol =POP;
}
if(tmp_secure == null ||
tmp_secure.length()== 0 ||
tmp_secure.compareToIgnoreCase(false)== 0 ||
tmp_secure.compareToIgnoreCase(no)== 0
){
received_secure = false;
} else {
received_secure = true;
}
if(receiving_attachments == null || receiving_attachments.length()== 0){
Log.Debug(EMail received attachmentments not defined,default to ./email/attachments/ );
received_attachments =./email/attachments/;
}

//现在做真正的工作。
doEMailDownload(ioc);

ioc.SendReturn();
ioc.Close();
Log.Trace(退出);
}

protected void doEMailDownload(IOConn ioc)throws Exception {
//创建空属性
属性props = new Properties();
//获取会话
会话session = Session.getInstance(props,null);

//获取商店
Store store = session.getStore(received_protocol);
store.connect(received_host,received_user,receiving_pass);

//获取文件夹
文件夹文件夹= store.getFolder(INBOX);
folder.open(Folder.READ_WRITE);

尝试{

//获取目录列表
消息消息[] = folder.getMessages();

for(int i = 0; i< messages.length; i ++){
//获取消息的详细信息:
EMail email = new EMail();
email.fromaddr = messages [i] .getFrom()[0] .toString();
地址[] to = messages [i] .getRecipients(Message.RecipientType.TO);
email.toaddr =; (int j = 0; j< to.length; j ++)
{
email.toaddr + = to [j] .toString()+;;
}
地址[] cc;
尝试{
cc = messages [i] .getRecipients(Message.RecipientType.CC);
} catch(Exception e){
Log.Warn(异常检索CC addrs:%s,e.getLocalizedMessage());
cc = null;
}
email.cc =;
if(cc!= null){
for(int j = 0; 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 =;
矢量< EMailAttach> vema = new Vector< EMailAttach>();
对象内容=消息[i] .getContent();
if(content instanceof java.lang.String){
email.body =(String)content;
} else if(content instanceof Multipart){
Multipart mp =(Multipart)content; (int j = 0; j< mp.getCount(); j ++){
Part part = mp.getBodyPart(j);



String disposition = part.getDisposition();

if(disposition == null){
//检查是否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);
//
// image / gif,text / html,...
的特殊非附件案例EMailAttach ema = new EMailAttach();
ema.name = decodeName(part.getFileName());
文件savedir = new File(received_attachments);
savedir.mkdirs();
文件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))
){
//检查是否plain
MimeBodyPart mbp =(MimeBodyPart)part;
if(mbp.isMimeType(text / plain)){
Log.Debug(Mime type is plain);
email.body + =(String)mbp.getContent();
} else {
Log.Debug(保存文件(%s),part.getFileName());
EMailAttach ema = new EMailAttach();
ema.name = decodeName(part.getFileName());
文件savedir = new File(received_attachments);
savedir.mkdirs();
文件savefile = File.createTempFile(emailattach,.atch,savedir);
ema.path = savefile.getAbsolutePath();
ema.size = part.getSize();
vema.add(ema);
ema.size = saveFile(savefile,part);
}
}
}
}

//将所有内容插入到数据库中:
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));
}

//提交此消息及其所有附件
ioc.getDBConnection()。commit();

//最后从服务器中删除该消息。
messages [i] .setFlag(Flags.Flag.DELETED,true);
}

//关闭连接
folder.close(true); // true告诉邮件服务器删除已删除的邮件。
store.close();
} catch(Exception e){
folder.close(true); // true告诉邮件服务器删除已删除的邮件。
store.close();
throw e;


}

protected int saveFile(File saveFile,Part part)throws异常{

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();
返回计数;
}

protected String decodeName(String name)throws异常{
if(name == null || name.length()== 0){
return 未知;
}
String ret = java.net.URLDecoder.decode(name,UTF-8);

//也检查字符串中的其他一些东西:
ret = ret.replaceAll(= \\?utf-8\\??q\\\ \\?,);
ret = ret.replaceAll(\\?=,);
ret = ret.replaceAll(= 20,);

return ret;
}

}


I had a look in the reference doc, and Spring seems to have pretty good support for sending mail. However, I need to login to a mail account, read the messages, and download any attachments. Is downloading mail attachments supported by the Spring mail API?

I know you can do this with the Java Mail API, but in the past I've found that very verbose and unpleasant to work with.

EDIT: I've received several replies pointing towards tutorials that describe how to send mail with attachments, but what I'm asking about is how to read attachments from received mail.

Cheers, Don

解决方案

Here's the class that I use for downloading e-mails (with attachment handling). You'll have to glance by some of the stuff it's doing (like ignore the logging classes and database writes). I've also re-named some of the packages for ease of reading.

The general idea is that all attachments are saved as individual files in the filesystem, and each e-mail is saved as a record in the database with a set of child records that point to all of the attachment file paths.

Focus on the doEMailDownload method.

/**
  * 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;
    }

}

这篇关于使用Java下载邮件附件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆