热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

java邮件附件下载_用Java下载邮件附件

这是我用来下载电子邮件的类(附件处理).您将不得不浏览它正在做的一些事情(比如忽略日志记录类和数据库写入).为了便于阅读,我还重新命名了一些软件包.一般的想法是所有附件都保存为文件

这是我用来下载电子邮件的类(附件处理).您将不得不浏览它正在做的一些事情(比如忽略日志记录类和数据库写入).为了便于阅读,我还重新命名了一些软件包.

一般的想法是所有附件都保存为文件系统中的单个文件,并且每个电子邮件都作为记录保存在数据库中,并带有一组指向所有附件文件路径的子记录.

专注于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

// 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

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

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 vema = new Vector();

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

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.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;

}

}



推荐阅读
  • Nginx使用(server参数配置)
    本文介绍了Nginx的使用,重点讲解了server参数配置,包括端口号、主机名、根目录等内容。同时,还介绍了Nginx的反向代理功能。 ... [详细]
  • Java序列化对象传给PHP的方法及原理解析
    本文介绍了Java序列化对象传给PHP的方法及原理,包括Java对象传递的方式、序列化的方式、PHP中的序列化用法介绍、Java是否能反序列化PHP的数据、Java序列化的原理以及解决Java序列化中的问题。同时还解释了序列化的概念和作用,以及代码执行序列化所需要的权限。最后指出,序列化会将对象实例的所有字段都进行序列化,使得数据能够被表示为实例的序列化数据,但只有能够解释该格式的代码才能够确定数据的内容。 ... [详细]
  • 开发笔记:加密&json&StringIO模块&BytesIO模块
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了加密&json&StringIO模块&BytesIO模块相关的知识,希望对你有一定的参考价值。一、加密加密 ... [详细]
  • 本文介绍了OC学习笔记中的@property和@synthesize,包括属性的定义和合成的使用方法。通过示例代码详细讲解了@property和@synthesize的作用和用法。 ... [详细]
  • 使用Ubuntu中的Python获取浏览器历史记录原文: ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • 个人学习使用:谨慎参考1Client类importcom.thoughtworks.gauge.Step;importcom.thoughtworks.gauge.T ... [详细]
  • 本文详细介绍了Java中vector的使用方法和相关知识,包括vector类的功能、构造方法和使用注意事项。通过使用vector类,可以方便地实现动态数组的功能,并且可以随意插入不同类型的对象,进行查找、插入和删除操作。这篇文章对于需要频繁进行查找、插入和删除操作的情况下,使用vector类是一个很好的选择。 ... [详细]
  • [大整数乘法] java代码实现
    本文介绍了使用java代码实现大整数乘法的过程,同时也涉及到大整数加法和大整数减法的计算方法。通过分治算法来提高计算效率,并对算法的时间复杂度进行了研究。详细代码实现请参考文章链接。 ... [详细]
  • ubuntu用sqoop将数据从hive导入mysql时,命令: ... [详细]
  • 本文讨论了在手机移动端如何使用HTML5和JavaScript实现视频上传并压缩视频质量,或者降低手机摄像头拍摄质量的问题。作者指出HTML5和JavaScript无法直接压缩视频,只能通过将视频传送到服务器端由后端进行压缩。对于控制相机拍摄质量,只有使用JAVA编写Android客户端才能实现压缩。此外,作者还解释了在交作业时使用zip格式压缩包导致CSS文件和图片音乐丢失的原因,并提供了解决方法。最后,作者还介绍了一个用于处理图片的类,可以实现图片剪裁处理和生成缩略图的功能。 ... [详细]
  • 本文介绍了在CentOS上安装Python2.7.2的详细步骤,包括下载、解压、编译和安装等操作。同时提供了一些注意事项,以及测试安装是否成功的方法。 ... [详细]
  • 本文介绍了Swing组件的用法,重点讲解了图标接口的定义和创建方法。图标接口用来将图标与各种组件相关联,可以是简单的绘画或使用磁盘上的GIF格式图像。文章详细介绍了图标接口的属性和绘制方法,并给出了一个菱形图标的实现示例。该示例可以配置图标的尺寸、颜色和填充状态。 ... [详细]
  • Android工程师面试准备及设计模式使用场景
    本文介绍了Android工程师面试准备的经验,包括面试流程和重点准备内容。同时,还介绍了建造者模式的使用场景,以及在Android开发中的具体应用。 ... [详细]
  • 本文介绍了PhysioNet网站提供的生理信号处理工具箱WFDB Toolbox for Matlab的安装和使用方法。通过下载并添加到Matlab路径中或直接在Matlab中输入相关内容,即可完成安装。该工具箱提供了一系列函数,可以方便地处理生理信号数据。详细的安装和使用方法可以参考本文内容。 ... [详细]
author-avatar
蟹子的宿命
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有