package com.mail.tool;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.DateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.StringTokenizer;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
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.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import com.mail.bean.MailBean;
import com.mail.bean.UserBean;
import com.mail.dao.ReceiveDao;
import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.MimeUtility;
public class MailManager {
public int getUnreadCount(UserBean user){//读取未读邮件的个数,POP3没有此功能
int count=0;
try{
Properties props=new Properties();//创建一个空的配置
Session mailSession = Session.getInstance(props);//获取一个Session的实例
mailSession.setDebug(true);
Store store = mailSession.getStore("pop3");//设置接收邮件的服务器类型
store.connect(user.getPop(), user.getEmail(), user.getEmailPSW());//连接服务器
Folder folder = store.getFolder("INBOX");//获取收件箱中的邮件
folder.open(Folder.READ_ONLY);
count=folder.getUnreadMessageCount();//获取未读邮件的个数
folder.close(true);
store.close();
}
catch (Exception e) {
e.printStackTrace();
}
return count;
}
//接收邮件
public boolean receiveMail(UserBean user){
try{
Properties props=new Properties();//创建一个空的配置
Session mailSession = Session.getInstance(props);//获取一个Session实例
mailSession.setDebug(true);
Store store = mailSession.getStore("pop3");//设置接收服务器类型
store.connect(user.getPop(), user.getEmail(), user.getEmailPSW());//连接服务器
Folder folder = store.getFolder("INBOX");//获取收件箱中的邮件
folder.open(Folder.READ_WRITE);//打开Folder
Message message[] = folder.getMessages();//获取所有邮件
ReceiveDao receiveDao = new ReceiveDao();//建立保存邮件的数据库
for (int i = 0; i < message.length; i++){
MailBean mail=new MailBean();
mail.setFrom(((InternetAddress)message[i].getFrom()[0]).getAddress());//读取发件人
mail.setTo(user.getEmail());//读取收件人
mail.setTheme(message[i].getSubject());//读取邮件主题
DateFormat format=DateFormat.getDateInstance(DateFormat.SHORT);//获取邮件发送日期
mail.setDate(format.format(message[i].getSentDate()));
/////////////////////////////////////////////////
Object content = message[i].getContent();//获取邮件所有内容
String textPlain=contentParser(message[i],"text/plain");//解析邮件中的文本正文
String textHtml=contentParser(message[i],"text/html");//解析邮件中的html正文
if(textHtml.length()>0)
mail.setContent(MimeUtility.decodeText(textHtml));
if(textPlain.length()>0)
mail.setContent(MimeUtility.decodeText(textPlain));
if (content instanceof Multipart){//获取邮件中的附件
Multipart mp = (Multipart) message[i].getContent();//判断邮件是否为Multipart
for (int j = 0; j < mp.getCount(); j++){
Part part = mp.getBodyPart(j);//取得Multipart中的BodyPart
String disposition = part.getDisposition();
if ((disposition != null)&&((disposition.equals(Part.ATTACHMENT))
||(disposition.equals(Part.INLINE)))){//判断是否为附件
String filename=MimeUtility.decodeText(part.getFileName());//取得附件文件的文件名
File file = new File(Constants.WEB_ABS_ATTACH_PATH
+ "/" + filename);//新建文件用来保存附件的文件
for (int k = 0; file.exists(); k++){
int index = filename.indexOf(".");
String ext = filename.substring(index);
file = new File(Constants.WEB_ABS_ATTACH_PATH
+ "/"
+ filename.substring(0, index)
+ k + ext);
}
FileOutputStream myFileoutputstream = new FileOutputStream(file);
int chunk = part.getSize();
byte[] buffer = new byte[chunk];
InputStream instream = part.getInputStream();
instream.read(buffer, 0, chunk);
myFileoutputstream.write(buffer, 0, chunk);
instream.close();
myFileoutputstream.close();
String attach=mail.getAttachment();
if(attach.length()>0)attach+=";";
mail.setAttachment(attach+"attachment" + "/"
+ file.getName());
mail.setFlag(MailBean.UNREAD);
}
}
}
//////////////////////////////////////////////////////
mail.setFlag(MailBean.UNREAD);
mail.setUserID(user.getUserID());
if (receiveDao.addReceive(mail))
message[i].setFlag(Flags.Flag.DELETED, true);
}
folder.close(true);
store.close();
return true;
}
catch (Exception e){
e.printStackTrace();
}
return false;
}
//发送邮件
public boolean sendMail(MailBean mail,UserBean user){//发送邮件方法
try{
Properties props =new Properties();
props.put("mail.smtp.host",user.getSmtp());//进行邮件服务器认证
props.put("mail.smtp.auth","true");
Session mailSession = Session.getInstance(props);
mailSession.setDebug(true);
MimeMessage newMessage = new MimeMessage(mailSession);
newMessage.setFrom(new InternetAddress(mail.getFrom()));
newMessage.setSubject(mail.getTheme());
newMessage.setSentDate(new Date());
InternetAddress[] toList = getToList(mail.getTo());
newMessage.setRecipients(Message.RecipientType.TO, toList);
BodyPart mbp = new MimeBodyPart();
mbp.setContent(mail.getContent(), "text/html;charset=GBK");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(mbp);
if (mail.getAttachment().length()>0){
String[] files=mail.getAttachment().split(";");
for(int i=0;i<files.length;i++){//设置邮件附件部分
mbp = new MimeBodyPart();
String attPath=Constants.WEB_ABS_PATH+files[i];
File file=new File(attPath);
DataSource source = new FileDataSource(file);
mbp.setDataHandler(new DataHandler(source));
mbp.setFileName(MimeUtility.encodeText(file.getName()));//编码文件名解决中文乱码
multipart.addBodyPart(mbp);
}
}
newMessage.setContent(multipart);
Transport transport;
transport = mailSession.getTransport("smtp");
transport.connect(user.getSmtp(), user.getEmail(), user.getEmailPSW());
transport.sendMessage(newMessage, newMessage.getAllRecipients());
transport.close();
return true;
}
catch (Exception e){
e.printStackTrace();
}
return false;
}
//取得地址列表
public InternetAddress[] getToList(String toSeq) throws AddressException{
StringTokenizer token = new StringTokenizer(toSeq, ",");
InternetAddress[] addr = new InternetAddress[token.countTokens()];
int i = 0;
while (token.hasMoreTokens()){
addr[i] = new InternetAddress(token.nextToken().toString());
i++;
}
return addr;
}
//解析邮件获取邮件文本
public String contentParser(Part part,String type) throws Exception{
String content="";
if(part.isMimeType(type)){
content=(String)part.getContent();
}
else{
if(part.getContent() instanceof Multipart){
Multipart mp = (Multipart)part.getContent();
int count = mp.getCount();
for (int i = 0; i < count; i++)
content+=contentParser(mp.getBodyPart(i),type);
}
}
return content;
}
}