package com.wgh.dao;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.mail.BodyPart;
import javax.mail.FetchProfile;
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.UIDFolder;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import javax.mail.search.AndTerm;
import javax.mail.search.MessageIDTerm;
import javax.mail.search.NotTerm;
import javax.mail.search.OrTerm;
import javax.mail.search.SearchTerm;
import sun.io.ByteToCharUTF8;
import com.sun.mail.pop3.POP3Folder;
import com.wgh.model.ReceiveEmailForm;
import com.wgh.tools.ConnDB;
import com.wgh.tools.StringUtils;
public class ReceiveEmailDAO {
private ConnDB conn = new ConnDB();
private String contentMail = "";
// 建立与邮件接收服务器的连接
public Store connectStore(String host, String username, String password) {
String protocol = "pop3";
Properties prop = new Properties(); //实例化Properties类
prop.setProperty("mail.store.protocol", "pop3"); //指定采用POP3协议接收邮件
prop.setProperty("mail.pop3.host", host); //指定POP3服务器
Session mailSession = Session.getDefaultInstance(prop, null); //创建Session
mailSession.setDebug(false); //设置调试标志为false,表示不调试
Store store = null;
try {
store = mailSession.getStore(protocol); //获取store对象
store.connect(host, username, password); //建立与邮件服务器的连接
// System.out.println("已经成功建立连接");
} catch (Exception e) {
e.printStackTrace();
if(null!=store){
if(store.isConnected()){ //当store已经连接
try {
store.close(); //关闭与邮件服务器的连接
} catch (MessagingException e1) {
e1.printStackTrace();
}
}
store=null;
}
}
return store;
}
// 查询已读邮件的方法
public String queryIsRead(String addressee) {
String messageId = "";
String sql = "SELECT * FROM tb_isRead WHERE addressee='" + addressee
+ "'";
ResultSet rs = conn.executeQuery(sql);
try {
while (rs.next()) {
messageId = messageId + rs.getString(2) + ",";
}
} catch (SQLException e) {
e.printStackTrace();
}
conn.close();
return messageId;
}
// 获取邮件内容
public List<ReceiveEmailForm> showEmail(String host, String username,
String password, String flag) {
List<ReceiveEmailForm> list = new ArrayList<ReceiveEmailForm>();
try {
Store store = connectStore(host, username, password);// 建立与邮件接收服务器的连接
POP3Folder folder = (POP3Folder) store.getFolder("inbox");
folder.open(Folder.READ_WRITE); //打开邮件夹
// 查询发件人为wgh@sina.com的邮件
// SearchTerm st=new FromStringTerm("wgh@wgh.com");
// Message[] message=folder.search(st);
// 查询未读邮件
// Flags flagss=new Flags(Flags.Flag.SEEN);
// FlagTerm st=new FlagTerm(flagss,flag);
//
// Message[] message=folder.search(st);
// *************************************************
FetchProfile profile = new FetchProfile();
// profile.add(UIDFolder.FetchProfileItem.UID);
// profile.add(FetchProfile.Item.ENVELOPE);
Message[] message = null;
String str_messageId = queryIsRead(username); // 已经阅读的邮件ID组成的字符串
if (!"".equals(str_messageId)) {
String[] isRead = str_messageId.split(",");
if ("0".equals(flag)) { // 未读邮件
// 生成搜索条件
NotTerm[] arrIsRead = new NotTerm[isRead.length];
for (int i = 0; i < isRead.length; i++) {
arrIsRead[i] =new NotTerm(new MessageIDTerm(isRead[i]));
}
SearchTerm st = new AndTerm(arrIsRead);
message = folder.search(st);
folder.fetch(message, profile);
} else { // 已读邮件
// 生成搜索条件
MessageIDTerm[] arrIsRead = new MessageIDTerm[isRead.length];
for (int i = 0; i < isRead.length; i++) {
arrIsRead[i] = new MessageIDTerm(isRead[i]);
}
SearchTerm st = new OrTerm(arrIsRead);
message = folder.search(st);
folder.fetch(message, profile);
}
} else {
if ("0".equals(flag)) { // 未读邮件
message = folder.getMessages(); // 获取全部邮件
folder.fetch(message, profile);
}
}
String mail_content = "";
String mail_attach = "";
Message messageI = null;
/******************************循环读取邮件信息******************************/
if(message!=null){
for (int i = message.length - 1; i >= 0; i--) {
MimeMessage m = (MimeMessage) message[i];
ReceiveEmailForm f = new ReceiveEmailForm();
messageI = message[i];
f.setMessageId(m.getMessageID()); // 邮件ID
f.setAddresser(messageI.getFrom()[0].toString()); // 发件人
/*************获取邮件主题**********************************************/
MimeMessage part=(MimeMessage) message[i];
String head=part.getHeader("SUBJECT")[0]; //获取邮件的头
if(head.toLowerCase().startsWith("=?gb")){ //获取GBK或GB2312编码的邮件主题
f.setTitle(messageI.getSubject());
}else{
f.setTitle(new String(messageI.getSubject().getBytes("ISO-8859-1"),"GBK")); // 邮件主题
}
/********************************************************************/
f.setSendTime(messageI.getSentDate().toLocaleString()); // 发送时间
String[] obj = getMailAttach(part, i); //调用获取邮件附件的方法
message[i].getFlags().getSystemFlags().toString();
mail_content = obj[0]; //邮件内容
mail_attach = obj[1]; //邮件附件
if (mail_attach == null || mail_attach.equals("")) {
mail_attach = "0";
} else {
mail_attach = "1";
}
f.setAdjunct(mail_attach); // 附件
list.add(f); // 将邮件信息保存到List集合中
}
}
/***********************************************************************/
folder.close(false); //关闭邮件夹
store.close(); //关闭与邮件服务器的连接
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
//插入已读标记
public void inIsRead(String messageId,String addressee){
//将该邮件的MessageID插入到tb_isRead数据表中,表示该邮件已读
String sql="INSERT INTO tb_isRead (messageId,addressee) VALUES('"+messageId+"','"+addressee+"')";
System.out.println("插入已读邮件:"+sql);
conn.executeUpdate(sql);
}
// 获取邮件的附件信息
public String[] getMailAttach(Part part, int emailv) throws Exception {
String contenttype = part.getContentType();
int nameindex = contenttype.indexOf("name");
String fileName1 = "";
String fileName = "";
boolean conname = false;
if (nameindex != -1)
conname = true;
if(part.isMimeType("multipart/report")){ //获取UTF-7编码的邮件内容
contentMail=decodeStream(part.getInputStream(),"UTF-7");
}else{
if ((part.isMimeType("text/plain") && !conname) || (part.isMimeType("text/html") && !conname)) {
if(part.isMimeType("text/plain; CHARSET=US-A")){ //获取ISO-8859-1编码的邮件内容
contentMail =new String(part.getContent().toString().getBytes("ISO-8859-1"),"GBK");
}else if (part.getContent().toString().length() > 0) {
contentMail =part.getContent().toString();
}
}else if (part.isMimeType("multipart/*") ) {
Multipart multipart = (Multipart) part.getContent();
// 获取附件名称(可能包含多个附件)
for (int j = 0; j < multipart.getCount(); j++) {
BodyPart mpart = multipart.getBodyPart(j);
String disposition = mpart.getDisposition();
if ((disposition != null)
&& ((disposition.equals(Part.ATTACHMENT)) || (disposition
.equals(Part.INLINE)))) {
fileName = mpart.getFileName();
StringUtils su=new StringU