package com.jxsafe.source.common.applications.source.classinfo.jmail;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
/**
* 邮件接收类
* @author CaoXiang
*
*/
public class GetMail {
private int mailCounter; // 邮件计数
private int mailDownErrorCounter; // 正在下载邮件时,出错的计数器
private boolean[] recordFailure; // 记录下载出错的邮件的序号
private int totalRetryTimes; // 总共重试次数,默认为3
private int retryTimeCounter; // 记下重试的次数
private Store store;
public Folder folder;
private Message[] messages;
private Message message;
private Part part;
private int allMessageCount;
private int messageCount;
private String dateformat; // 默认的日前显示格式
private String protocol; // 服务协议
private String mailHost; // 服务器地址
private String userName; // 用户名
private String password; // 密码
private String emlName; // 下载的邮件名
private String attachPath; // 邮件及附件下载后的存放目录
/**
* 构造一个新的<code>GetMail</code>对象。
*
* @throws IOException
*/
public GetMail() throws IOException {
totalRetryTimes = 3;
dateformat = "yyyy-MM-dd hh:ss";
protocol = "pop3";
mailHost = "POP.163.com";
userName = "sxfsongxianfei1";
password = "1982811";
attachPath = "c://mail//";
emlName = "mails";
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#setMailHost(java.lang.String)
*/
public void setMailHost(String mailHost) {
this.mailHost = mailHost;
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getMailHost()
*/
public String getMailHost() {
return this.mailHost;
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#setUserName(java.lang.String)
*/
public void setUserName(String userName) {
this.userName = userName;
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getUserName()
*/
public String getUserName() {
return this.userName;
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#setPassword(java.lang.String)
*/
public void setPassword(String password) {
this.password = password;
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#setStore(javax.mail.Store)
*/
public void setStore(Store store) {
this.store = store;
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#setFolder(javax.mail.Folder)
*/
public void setFolder(Folder folder) {
this.folder = folder;
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#setMessages(javax.mail.Message[])
*/
public void setMessages(Message[] messages) {
this.messages = messages;
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#setMessage(javax.mail.Message)
*/
public void setMessage(Message message) {
this.message = message;
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getMessage()
*/
public Message getMessage() {
return this.message;
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getAllMessageCount()
*/
public int getAllMessageCount() throws MessagingException {
this.allMessageCount = folder.getMessageCount();
return allMessageCount;
}
/**
* 设置allMessageCount
*
* @throws MessagingException
*/
@SuppressWarnings("unused")
private void setAllMessageCount() throws MessagingException {
this.allMessageCount = this.folder.getMessageCount();
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getMessageCount()
*/
public int getMessageCount() {
this.messageCount = this.messages.length;
return messageCount;
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getNewMessageCount()
*/
public int getNewMessageCount() throws MessagingException {
return this.folder.getNewMessageCount();
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getUnreadMessageCount()
*/
public int getUnreadMessageCount() throws MessagingException {
return this.folder.getUnreadMessageCount();
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getPart()
*/
public Part getPart() {
return (Part) message;
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#setPart(javax.mail.Part)
*/
public void setPart(Part part) {
this.part = part;
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#setAttachPath(java.lang.String)
*/
public void setAttachPath(String attachPath) {
this.attachPath = attachPath;
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getAttachPath()
*/
public String getAttachPath() {
return attachPath;
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#setEmlName(java.lang.String)
*/
public void setEmlName(String emlName) {
this.emlName = emlName;
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getEmlName()
*/
public String getEmlName() {
return emlName;
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#setDateFormat(java.lang.String)
*/
public void setDateFormat(String format) throws Exception {
this.dateformat = format;
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getDateFormat(java.lang.String)
*/
public String getDateFormat(String format) throws Exception {
return this.dateformat;
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getFrom()
*/
public String getFrom() throws Exception {
return getFrom(this.message);
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getFrom(javax.mail.Message)
*/
public String getFrom(Message mimeMessage) throws Exception {
InternetAddress address[] = (InternetAddress[]) mimeMessage.getFrom();
String from = address[0].getAddress();
if (from == null)
from = "";
String personal = address[0].getPersonal();
if (personal == null)
personal = "";
String fromaddr = personal + "<" + from + ">";
return fromaddr;
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getTOAddress()
*/
public String getTOAddress() throws Exception {
return getMailAddress("TO", this.message);
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getCCAddress()
*/
public String getCCAddress() throws Exception {
return getMailAddress("CC", this.message);
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getBCCAddress()
*/
public String getBCCAddress() throws Exception {
return getMailAddress("BCC", this.message);
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getTOAddress(javax.mail.Message)
*/
public String getTOAddress(Message mimeMessage) throws Exception {
return getMailAddress("TO", mimeMessage);
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getCCAddress(javax.mail.Message)
*/
public String getCCAddress(Message mimeMessage) throws Exception {
return getMailAddress("CC", mimeMessage);
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getBCCAddress(javax.mail.Message)
*/
public String getBCCAddress(Message mimeMessage) throws Exception {
return getMailAddress("BCC", mimeMessage);
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getMailAddress(java.lang.String)
*/
public String getMailAddress(String type) throws Exception {
return getMailAddress(type, this.message);
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getMailAddress(java.lang.String, javax.mail.Message)
*/
public String getMailAddress(String type, Message mimeMessage)
throws Exception {
String mailaddr = "";
String addtype = type.toUpperCase();
InternetAddress[] address = null;
if (addtype.equals("TO") || addtype.equals("CC")
|| addtype.equals("BCC")) {
if (addtype.equals("TO")) {
address = (InternetAddress[]) mimeMessage
.getRecipients(Message.RecipientType.TO);
} else if (addtype.equals("CC")) {
address = (InternetAddress[]) mimeMessage
.getRecipients(Message.RecipientType.CC);
} else {
address = (InternetAddress[]) mimeMessage
.getRecipients(Message.RecipientType.BCC);
}
if (address != null) {
for (int i = 0; i < address.length; i++) {
String email = address[i].getAddress();
if (email == null)
email = "";
else {
email = MimeUtility.decodeText(email);
}
String personal = address[i].getPersonal();
if (personal == null)
personal = "";
else {
personal = MimeUtility.decodeText(personal);
}
String compositeto = personal + "<" + email + ">";
mailaddr += "," + compositeto;
}
mailaddr = mailaddr.substring(1);
}
} else {
throw new Exception("Error emailaddr type!");
}
return mailaddr;
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getSubject()
*/
public String getSubject() throws MessagingException {
return getSubject(this.message);
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getSubject(javax.mail.Message)
*/
public String getSubject(Message mimeMessage) throws MessagingException {
String subject = "";
try {
subject = MimeUtility.decodeText(mimeMessage.getSubject());
if (subject == null)
subject = "";
} catch (Exception exce) {
}
return subject;
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getSentDate()
*/
public String getSentDate() throws Exception {
return getSentDate(this.message);
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getSentDate(javax.mail.Message)
*/
public String getSentDate(Message mimeMessage) throws Exception {
Date sentdate = mimeMessage.getSentDate();
SimpleDateFormat format = new SimpleDateFormat(dateformat);
return format.format(sentdate);
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getReplySign()
*/
public boolean getReplySign() throws MessagingException {
return getReplySign(this.message);
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getReplySign(javax.mail.Message)
*/
public boolean getReplySign(Message mimeMessage) throws MessagingException {
boolean replysign = false;
String needreply[] = mimeMessage
.getHeader("Disposition-Notification-To");
if (needreply != null) {
replysign = true;
}
return replysign;
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getMessageId()
*/
public String getMessageId() throws MessagingException {
return getMessageId(this.message);
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getMessageId(javax.mail.Message)
*/
public String getMessageId(Message mimeMessage) throws MessagingException {
return ((MimeMessage) mimeMessage).getMessageID();
}
/**
* 初始化出错邮件数组
*
*/
private void setRecordFailure() {
this.recordFailure = new boolean[getMessageCount()];
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getRecordFailure()
*/
public boolean[] getRecordFailure() {
return this.recordFailure;
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#isNew()
*/
public boolean isNew() throws MessagingException {
return isNew(this.message);
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#isNew(javax.mail.Message)
*/
public boolean isNew(Message mimeMessage) throws MessagingException {
boolean isnew = false;
Flags flags = mimeMessage.getFlags();
Flags.Flag[] flag = flags.getSystemFlags();
for (int i = 0; i < flag.length; i++) {
if (flag[i] == Flags.Flag.SEEN) {
isnew = true;
break;
}
}
return isnew;
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#isContainAttach()
*/
public boolean isContainAttach() throws Exception {
return isContainAttach(this.part);
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#isContainAttach(javax.mail.Part)
*/
public boolean isContainAttach(Part part) throws Exception {
boolean attachflag = false;
String contentType = part.getContentType();
if (part.isMimeType("multipart/*")) {
Multipart mp = (Multipart) part.getContent();
for (int i = 0; i < mp.getCount(); i++) {
BodyPart mpart = mp.getBodyPart(i);
String disposition = mpart.getDisposition();
if ((disposition != null)
&& ((disposition.equals(Part.ATTACHMENT)) || (disposition
.equals(Part.INLINE))))
attachflag = true;
else if (mpart.isMimeType("multipart/*")) {
attachflag = isContainAttach((Part) mpart);
} else {
String contype = mpart.getContentType();
if (contype.toLowerCase().indexOf("application") != -1)
attachflag = true;
if (contype.toLowerCase().indexOf("name") != -1)
attachflag = true;
}
}
} else if (part.isMimeType("message/rfc822")) {
attachflag = isContainAttach((Part) part.getContent());
}
return attachflag;
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getConn()
*/
public void getConn() {
try {
this.getStoreFromServer();
this.getFolderFromStore();
} catch (Exception e) {
mailDownErrorCounter++;
}
}
/**
* 建立Store连接
* @return Store
* @throws Exception
*/
private Store getStoreFromServer() throws Exception {
// 创建session
Session session = Session.getDefaultInstance(System.getProperties(),
null);
// session.setDebug(true);
// 创建store,建立连接
Store store = session.getStore(protocol);
System.out.println("connecting");
store.connect(mailHost, userName, password);
System.out.println("connected successfully");
setStore(store);
return store;
}
/**
* 打开INBox文件夹
* @return Folder
*/
private Folder getFolderFromStore() {
// 打开邮件相应文件夹
Folder getFolder;
try {
getFolder = store.getFolder("INBOX");
getFolder.open(Folder.READ_WRITE);
setFolder(getFolder);
return getFolder;
} catch (MessagingException e) {
System.err.println("获取Folder失败!");
e.printStackTrace();
}
return null;
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getAllMessages()
*/
public Message[] getAllMessages() throws MessagingException {
// 从邮件文件夹获取邮件信息
Message[] messages = folder.getMessages();
setMessages(messages);
setRecordFailure();// 初始化出错数组
// setMessageCount();
return messages;
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getMessages(int[])
*/
public Message[] getMessages(int[] messageNums) throws MessagingException {
Message[] messages = folder.getMessages(messageNums);
setMessages(messages);
setRecordFailure();// 初始化出错数组
// setMessageCount();
return messages;
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getMessages(int, int)
*/
public Message[] getMessages(int start, int end) throws MessagingException {
Message[] messages = folder.getMessages(start, end);
setMessages(messages);
setRecordFailure();// 初始化出错数组
// setMessageCount();
return messages;
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getMessages(int)
*/
public Message getMessages(int start) throws MessagingException {
Message[] messages = folder.getMessages(start, start);
setMessages(messages);
setRecordFailure();// 初始化出错数组
// setMessageCount();
return messages[0];
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#closeConnection()
*/
public void closeConnection() {
try {
messages = null;
message = null;
if (folder.isOpen())
folder.close(true);
store.close();
System.out.println("close");
} catch (Exception e) {
System.out.println("关闭和邮件服务器之间连接时出错!");
e.printStackTrace();
}
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getMail()
*/
public void getMail() throws Throwable {// 抛出异常,用以重掷
try {
parseMessage(message);
} catch (IOException e) {
System.err.println("保存邮件出错,检查保存路径");
throw new IOException("保存邮件出错,检查保存路径");
} catch (MessagingException e) {
System.err.println("邮件转换出错");
throw new MessagingException("邮件转换出错");
} catch (Exception e) {
System.err.println("未知错误");
e.printStackTrace();
throw new Exception("未知错误");
}
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getMail(int)
*/
public void getMail(int index) {
mailDownErrorCounter = 0; // 邮件下载出错计数器置零
try {// 获取邮件下载之前的错误
setMessage(messages[index]);// 设置当前message
System.out.println("正在获取第" + index+1 + "封邮件. . .");
getMail();// 获取当前message
System.out.println("成功获取第" + index+1 + "封邮件");
} catch (Throwable e) {// 获得重掷异常
recordFailure[index] = true;
mailDownErrorCounter++;
System.err.println("下载第" + index + "封邮件时出错");
retry();
}
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getAllMail()
*/
public void getAllMail() {
int mailArrayLength; // 将要下载的邮件的数量。若是重试时,则为还未下载的邮件数量
mailArrayLength = getMessageCount();
System.out.println("一共有邮件" + mailArrayLength + "封");
mailDownErrorCounter = 0; // 邮件下载出错计数器置零
mailCounter = 0;
for (int index = 0; index < mailArrayLength; index++) {
try {
setMessage(messages[index]);// 设置当前message
System.out.println("正在获取第" + (index + 1) + "封邮件. . .");
getMail();// 获取当前message
System.out.println("成功获取第" + (index+1) + "封邮件");
mailCounter++;
} catch (Throwable e) {
recordFailure[index] = true;
mailDownErrorCounter++;
System.err.println("下载第" + index + "封邮件时出错");
}
}
System.out.println("成功下载" + mailCounter + "封邮件");
mailCounter = 0;
if (mailDownErrorCounter != 0)
retry();
}
/*
* 解析邮件
*/
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#parseMessage(javax.mail.Message)
*/
public void parseMessage(Message message) throws IOException,
MessagingException {
Object content = message.getContent();
if (content instanceof Multipart) {
System.out.println("parseMessage....多附档部分");
handleMultipart((Multipart) content);
} else {
System.out.println("parseMessage....单附档部分");
handlePart(message);
}
}
/*
* 解析Multipart
*/
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#handleMultipart(javax.mail.Multipart)
*/
public void handleMultipart(Multipart multipart) throws MessagingException,
IOException {
for (int i = 0, n = multipart.getCount(); i < n; i++) {
handlePart(multipart.getBodyPart(i));
}
}
/*
* 解析指定part,从中提取文件
*/
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#handlePart(javax.mail.Part)
*/
public void handlePart(Part part) throws MessagingException, IOException {
System.out.println("解析part开始.......... handlePart");
String disposition = part.getDisposition(); // Find attachment
String contentType = part.getContentType();
InputStreamReader sbis = new InputStreamReader(part.getInputStream());
if (disposition == null) { // When just body
System.out.println("part部署disposition 为 Null: " + contentType);
// Check if plain
if ((contentType.length() >= 9)
&& (contentType.toLowerCase().substring(0, 9)
.equals("text/plai"))) {
System.out.println(getAttachPath() + getEmlName() + ".txt");
saveFile(getAttachPath() + getEmlName() + ".txt", sbis);
} else if ((contentType.length() >= 8) // Check if html
&& (contentType.toLowerCase().substring(0, 8)
.equals("text/htm"))) {
saveFile(getAttachPath() + getEmlName() + ".html", sbis);
} else if ((contentType.length() >= 9) // Check if gif
&& (contentType.toLowerCase().substring(0, 9)
.equals("image/gif"))) {
saveFile(getAttachPath() + getEmlName() + ".gif", part
.getInputStream());
} else if ((contentType.length() >= 9) // Check if jpeg
&& (contentType.toLowerCase().substring(0, 9)
.equals("image/jpe"))) {
saveFile(getAttachPath() + getEmlName() + ".jpg", part
.getInputStream());
} else if ((contentType.length() >= 10)
&& contentType.toLowerCase().substring(0, 10).equals(
"multipart/")) { // Check if multipart
System.out.println("multipart body: " + contentType);
Multipart mp = (Multipart) (part.getContent());
handleMultipart(mp);
} else { // Unknown type
System.out.println("Other body: " + contentType);
saveFile(getAttachPath() + getEmlName() + ".txt", sbis);
}
} else if (disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
System.out.println(Part.ATTACHMENT + ".. Attachment: "
+ part.getFileName() + " : " + contentType);
// outToFile.println("Attachment: " + part.getFileName() + " : "
// + contentType);
saveFile(getAttachPath() + part.getFileName(), part
.getInputStream());
} else if (disposition.equalsIgnoreCase(Part.INLINE)) {
System.out.println(Part.INLINE + ".. Inline: " + part.getFileName()
+ " : " + contentType);
// outToFile.println("Inline: " + part.getFileName() + " : "
// + contentType);
saveFile(getAttachPath() + part.getFileName(), sbis);
} else { // Should never happen
System.out.println("Other: " + disposition);
// outToFile.println("Other: " + disposition);
saveFile(getAttachPath() + part.getFileName(), sbis);
}
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#saveFile(java.lang.String, java.io.Reader)
*/
public void saveFile(String fileName, Reader input) throws IOException {
if (fileName == null) {
fileName = File.createTempFile(getAttachPath() + "xx", ".out")
.getName();
}
// Do no overwrite existing file
File file = new File(fileName);
int lastDot = fileName.lastIndexOf(".");
System.out.println("文件名称为: " + fileName + ">>后缀。位置为: " + lastDot);
String extension = fileName.substring(lastDot);
String fullFileName = fileName;
fileName = fileName.substring(0, lastDot);
for (int i = 0; file.exists(); i++) {
file = new File(fileName + i + extension);
}
FileWriter fos = new FileWriter(file);
BufferedWriter bos = new BufferedWriter(fos);
BufferedReader bis = new BufferedReader(input);
int aByte;
while ((aByte = bis.read()) != -1) {
bos.write(aByte);
}
bos.flush();
bos.close();
bis.close();
}
private void saveFile(String fileName, InputStream in) throws IOException {
// String temp=part.getFileName();//得到未经处理的附件名字
// temp= MimeUtility.decodeWord(temp);
// String s=temp.substring(11,temp.indexOf("?=")-1);//去到header和footer
// 文件名一般都经过了base64编码,下面是解码
// String fileName=this.base64Decoder(temp);
System.out.println("有附件:" + fileName);
FileOutputStream writer = new FileOutputStream(new File(fileName));
byte[] content = new byte[255];
@SuppressWarnings("unused")
int read = 0;
while ((read = in.read(content)) != -1) {
writer.write(content);
}
writer.close();
in.close();
}
/*
* 把指定文件,转化成MimeMessage
*/
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#readEmlFile(java.lang.String)
*/
public void readEmlFile(String fileName) throws MessagingException {
try {
InputStream fis = new FileInputStream(fileName);
Session mailSession = Session.getDefaultInstance(System
.getProperties(), null);
MimeMessage msg = new MimeMessage(mailSession, fis);
message = msg;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
@SuppressWarnings("unused")
private String getInfoBetweenBrackets(String str) throws Exception {
int i, j; // 用于标识字符串中的"<"和">"的位置
if (str == null) {
str = "error";
return str;
}
i = str.lastIndexOf("<");
j = str.lastIndexOf(">");
if (i != -1 && j != -1)
str = str.substring(i + 1, j);
return str;
}
// 当有邮件无法下载时进行重试
private void retry() {
mailCounter = 0;
while (retryTimeCounter < totalRetryTimes && mailDownErrorCounter != 0) {
if (!store.isConnected() || !folder.isOpen()) {
System.err.println("与服务器连接断开,请重新连接");
closeConnection();
return;
}
System.out.println("第" + (retryTimeCounter + 1) + "次重试");
mailDownErrorCounter = 0; // 邮件下载出错计数器置零
for (int index = 0; index < getMessageCount(); index++) {
if (recordFailure[index]) {
try {
setMessage(messages[index]);// 设置当前message
System.out.println("正在获取第" + index+1 + "封邮件. . .");
getMail();// 获取当前message
System.out.println("成功获取第" + (index + 1) + "封邮件");
mailCounter++;
recordFailure[index] = false;
} catch (Throwable e) {
recordFailure[index] = true;
mailDownErrorCounter++;
System.err.println("重新下载第" + index + "封邮件时出错");
}
}
}
retryTimeCounter++;
}
System.out.println("成功下载" + mailCounter + "封邮件");
mailCounter = 0; // 将邮件计数置零
mailDownErrorCounter = 0;// 下载错误数量归零
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#setDelete(javax.mail.Message)
*/
public void setDelete(Message message) throws MessagingException {
message.setFlag(Flags.Flag.DELETED, true);
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#isDelete(javax.mail.Message)
*/
public boolean isDelete(Message message) throws MessagingException {
return message.isSet(Flags.Flag.DELETED);
}
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#setSeen(javax.mail.Message)
*/
public void setSeen(Message message) throws MessagingException {
message.setFlag(Flags.Flag.SEEN, true);
}
/*
* 解析指定part,从中提取文件
*/
/* (non-Javadoc)
* @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#attachPart(javax.mail.Part)
*/
public void attachPart(Part part) throws MessagingException, IOException {
System.out.println("解析part开始.......... handlePart");
String disposition = part.getDisposition(); // Find attachment
String contentType = part.getContentType();
if (disposition == null) { // When just body
System.out.println("part部署disposition 为 Null: " + contentType);
// Check if plain
if ((contentType.length() >= 9)
&& (contentType.toLowerCase().substring(0, 9)
.equals("text/plai"))) {
} else if ((contentType.length() >= 8) // Check if html
&& (contentType.toLowerCase().substring(0, 8)
.equals("text/htm"))) {
} else if ((contentType.length() >= 9) // Check if gif
&& (contentType.toLowerCase().substring(0, 9)
.equals("image/gif"))) {
saveFile(getAttachPath() + part.getFileName() + ".gif", part
.getInputStream());
} else if ((contentType.length() >= 9) // Check if jpeg
&& (contentType.toLowerCase().substring(0, 9)
.equals("image/jpe"))) {
saveFile(getAttachPath() + part.getFileName() + ".jpg", part
.getInputStream());
} else if ((contentType.length() >= 10)
&& contentType.toLowerCase().substring(0, 10).equals(
"multipart/")) { // Check if multipart
System.out.println("multipart body: " + contentType);
Multipart mp = (Multipart) (part.getContent());
handleMultipart(mp);
} else { // Unknown type
System.out.println("Other body: " + contentType);
}
} else if (disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
System.out.println(Part.ATTACHMENT + ".. Attachment: "
+ part.getFileName() + " : " + contentType);
// outToFile.println("Attachment: " + part.getFileName() + " : "
// + contentType);
saveFile(getAttachPath() + part.getFileName(), part
.getInputStream());
} else if (disposition.equalsIgnoreCase(Part.INLINE)) {
System.out.println(Part.INLINE + ".. Inline: " + part.getFileName()
+ " : " + contentType);
// outToFile.println("Inline: " + part.getFileName() + " : "
// + contentType);
} else { // Should never happen
System.out.println("Other: " + disposition);
// outToFile.println("Other: " + disposition);
}
}
}