public class MailManager {
public static String RECEIVE_MAIL_SERVER = null;
public static String RECEIVE_PROTOCOL = null;
public static String RECEIVE_MAIL_PORT = null;
public static String SEND_MAIL_SERVER = null;
public static String SEND_MAIL_PROTOCOL = null;
public static String SEND_MAIL_PORT = null;
public static String MAIM_SMTP_CLASS = null;
public static String MAIM_IMAP_CLASS = null;
private HttpSession session = null;
private HttpServletResponse response = null;
private Store store = null;
private Document doc = null;
private Element root = null;
private Element code = null;
private Element message = null;
private Element data = null;
private ActiveUser user;
private int attcount = 0;
private String attname = null;
private String attnames = new String();
private String bodyType = null;
private Hashtable<String, String> cidmaps = new Hashtable();
private boolean hasCID = false;
private static Hashtable foldersType;
private MailManager() {
}
public MailManager(HttpSession session, HttpServletResponse response) {
setSession(session);
this.response = response;
this.response.setCharacterEncoding("UTF-8");
this.response.setHeader("Cache-Control", "no-cache");
root = new Element("Result");
doc = new Document(root);
code = new Element("Code");
data = new Element("Data");
message = new Element("Message");
message.setText("");
code.setText("0");
root.addContent(code);
root.addContent(message);
root.addContent(data);
foldersType = new Hashtable();
foldersType.put("inbox", "收件箱");
foldersType.put("sent", "發(fā)件箱");
foldersType.put("draft", "草稿箱");
foldersType.put("trash", "回收站");
foldersType.put("junkmail", "垃圾郵件");
if(this.session.getAttribute("store") != null) {
this.store = (Store) this.session.getAttribute("store");
if(!this.store.isConnected())
try {
this.store.connect();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
connect("
raymonbizos@21cn.com", "789456123");
}
}
public static void init() {
ResourceBundle config = ResourceBundle.getBundle("cn.bizos.mail.resource.Configuration");
RECEIVE_MAIL_SERVER = config.getString("ReceiveMailServer");
RECEIVE_PROTOCOL = config.getString("ReceiveProtocol");
RECEIVE_MAIL_PORT = config.getString("ReceiveMailPort");
SEND_MAIL_SERVER = config.getString("SendMailServer");
SEND_MAIL_PROTOCOL = config.getString("SendProtocol");
SEND_MAIL_PORT = config.getString("SendMailPort");
MAIM_SMTP_CLASS = config.getString("mail.smtp.class");
MAIM_IMAP_CLASS = config.getString("mail.imap.class");
}
public void connect(String userName, String password) {
javax.mail.Session mailSession;
URLName url = null;
//registry
Properties properties = new Properties();
properties.put("mail.transport.protocol", SEND_MAIL_PROTOCOL);
properties.put("mail.store.protocol", RECEIVE_PROTOCOL);
properties.put("mail.smtp.class", "com.sun.mail.smtp.SMTPTransport");
properties.put("mail.imap.class", "com.sun.mail.imap.IMAPStore");
url = new URLName(RECEIVE_PROTOCOL, RECEIVE_MAIL_SERVER, -1, "INBOX",
userName, password);
log("start connect method...");
log("userName: " + userName);
log("password: " + password);
try {
mailSession = Session.getInstance(properties, null);
//mailSession.setDebug(true);
store = mailSession.getStore(url);
store.connect();
user = new ActiveUser();
user.setPassword(password);
user.setUserName(userName);
session.setAttribute("user", user);
session.setAttribute("store", store);
} catch (NoSuchProviderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
code.setText("1");
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
code.setText("1");
}
//writeXMLToClient();
}
public void getChildFolders(String folderName) {
Folder[] childs = null;
String perantName = null;
try {
Folder folder = store.getFolder(folderName);
if(folder.exists()) {
perantName = folder.getFullName();
childs = folder.list();
}
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(childs.length > 0) {
Element el = null;
for(int n = 0; n < childs.length; n++) {
try {
if(childs[n].getParent().getFullName().equals(perantName)) {
el = new Element("folder");
try {
el.setAttribute("name", childs[n].getName());
el.setAttribute("mgsCount", String.valueOf(childs[n].getMessageCount()));
el.setAttribute("newMgsCount", String.valueOf(childs[n].getNewMessageCount()));
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
code.setText("1");
}
data.addContent(el);
}
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
closeStore();
writeXMLToClient();
}
public void getTempFolder() {
Folder[] fl = null;
String parentName = null;
try {
Folder df = store.getDefaultFolder();
fl = df.listSubscribed();
parentName = df.getFullName();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
code.setText("1");
}
if(fl.length > 0) {
Element el = null;
for(int n = 0; n < fl.length; n++) {
try {
if(fl[n].getParent().getFullName().equals(parentName)) {
if(fl[n].exists() && !fl[n].isOpen()) fl[n].open(Folder.READ_WRITE);
el = new Element("folder");
el.setAttribute("name", transition(fl[n].getName()));
el.setAttribute("mgsCount", String.valueOf(fl[n].getMessageCount()));
el.setAttribute("newMgsCount", String.valueOf(fl[n].getNewMessageCount()));
data.addContent(el);
}
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
code.setText("1");
}
}
}
closeStore();
writeXMLToClient();
}
public void getBaseFolders() {
Folder[] fl = null;
String parentName = null;
try {
Folder df = store.getDefaultFolder();
fl = df.list();
parentName = df.getFullName();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
code.setText("1");
}
if(fl.length > 0) {
//Element el = null;
Element favorites = new Element("Favorites");
Element bookmarks = new Element("Bookmarks");
Element bookmark;// = new Element("Bookmark");
Element id;
Element name;
Element url;
Element clientData;
for(int n = 0; n < fl.length; n++) {
try {
if(fl[n].getParent().getFullName().equals(parentName)) {
if(fl[n].exists() && !fl[n].isOpen()) fl[n].open(Folder.READ_WRITE);
bookmark = new Element("Bookmark");
id = new Element("Id");
name = new Element("Name");
url = new Element("Url");
clientData = new Element("ClientData");
bookmark.setContent(id);
name.setText(transition(fl[n].getName()));
String myurl = "/mail/mail.xml?folderName=" + fl[n].getName() + "&newCount=" +
fl[n].getNewMessageCount() + "&mgsCount=" + fl[n].getMessageCount();
url.setText(myurl);
bookmark.addContent(name);
bookmark.addContent(url);
bookmark.addContent(clientData);
bookmarks.addContent(bookmark);
}
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
code.setText("1");
}
}
favorites.addContent(bookmarks);
data.addContent(favorites);
}
closeStore();
writeXMLToClient();
}
public void getMessageCount(String folder) {
Folder f ;
try {
if(!store.isConnected()) store.connect();
f = store.getFolder(folder);
if(f != null && f.exists()) {
if(!f.isOpen()) f.open(Folder.READ_WRITE);
data.setAttribute("folder", transition(folder));
data.setAttribute("mgscount", String.valueOf(f.getMessageCount()));
data.setAttribute("newcount", String.valueOf(f.getNewMessageCount()));
//log("folder: " + folder);
//log("newCount: " + f.getNewMessageCount());
//f.close(false);
}
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//closeStore();
writeXMLToClient();
}
public void getMessages(String folder) {
Folder f = null;
Message[] mgs = null;
String charset = "null";
try {
if(!store.isConnected()) store.connect();
f = store.getFolder(folder);
if(f != null && f.exists()) {
if(!f.isOpen()) {
f.open(Folder.READ_WRITE);
}
f.expunge();
mgs = f.getMessages();
String subject;
if(mgs.length > 0) {
Element el = null;
for(int n = 0; n < mgs.length; n++) {
try {
charset = getCharset(mgs[n]);
if(charset.equals("null")) {
subject = encoding(mgs[n].getSubject(), "GBK");
}else{
subject = mgs[n].getSubject();
}
el = new Element("mgs");
el.setAttribute("mgsnum", String.valueOf(mgs[n].getMessageNumber()));
el.setAttribute("subject", subject.length() > 25? subject.substring(0,25): subject);
el.setAttribute("recieveTime", DateFormat(mgs[n].getReceivedDate()));
el.setAttribute("from", getFrom(mgs[n].getFrom()));
el.setAttribute("state", getMessagState(mgs[n]));
el.setAttribute("folder", mgs[n].getFolder().getName());
}catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
code.setText("1");
}
data.addContent(el);
}
}
//f.close(false);
}
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
code.setText("1");
}
/*
try {
f.close(false);
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
//closeStore();
writeXMLToClient();
}
public void getSeenMessage(String folder) {
Folder f = null;
Message[] mgs = null;
try {
if(!store.isConnected()) store.connect();
f = store.getFolder(folder);
if(f != null && f.exists()) {
if(!f.isOpen()) f.open(Folder.READ_WRITE);
mgs = f.getMessages();
}
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
code.setText("1");
}
if(mgs != null && mgs.length > 0) {
String subject;
String charset;
Element el = null;
for(int n = 0; n < mgs.length; n++) {
try {
String mgstate = getMessagState(mgs[n]);
if("/mail/images/seen.gif".equals(mgstate)) {
charset = getCharset(mgs[n]);
if(charset.equals("null")) {
subject = encoding(mgs[n].getSubject(), "GBK");
}else{
subject = mgs[n].getSubject();
}
el = new Element("mgs");
el.setAttribute("mgsnum", String.valueOf(mgs[n].getMessageNumber()));
el.setAttribute("subject", subject.length() > 25? subject.substring(0,25): subject);
el.setAttribute("recieveTime", DateFormat(mgs[n].getReceivedDate()));
el.setAttribute("from", getFrom(mgs[n].getFrom()));
el.setAttribute("state", getMessagState(mgs[n]));
el.setAttribute("folder", mgs[n].getFolder().getName());
data.addContent(el);
}
}catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
code.setText("1");
}
}
}
//closeStore();
writeXMLToClient();
}
public void getAnseredMessage(String folder) {
Folder f = null;
Message[] mgs = null;
try {
if(!store.isConnected()) store.connect();
f = store.getFolder(folder);
if(f != null && f.exists()) {
if(!f.isOpen()) f.open(Folder.READ_WRITE);
mgs = f.getMessages();
}
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
code.setText("1");
}
if(mgs != null && mgs.length > 0) {
for(int n = 0; n < mgs.length; n++) {
String mgstate = getMessagState(mgs[n]);
if("/mail/images/ansered.gif".equals(mgstate)) {
buildMessageData(mgs[n]);
}
}
}
//closeStore();
writeXMLToClient();
}
private void buildMessageData(Message mgs) {
String subject;
String charset;
Element el = null;
try {
charset = getCharset(mgs);
if(charset.equals("null")) {
subject = encoding(mgs.getSubject(), "GBK");
}else{
subject = mgs.getSubject();
}
el = new Element("mgs");
el.setAttribute("mgsnum", String.valueOf(mgs.getMessageNumber()));
el.setAttribute("subject", subject.length() > 25? subject.substring(0,25): subject);
el.setAttribute("recieveTime", DateFormat(mgs.getReceivedDate()));
el.setAttribute("from", getFrom(mgs.getFrom()));
el.setAttribute("state", getMessagState(mgs));
el.setAttribute("folder", mgs.getFolder().getName());
data.addContent(el);
}catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
code.setText("1");
}
}
public void getNewMessages(String folder) {
Folder f = null;
Message[] mgs = null;
String charset = "null";
try {
if(!store.isConnected()) store.connect();
f = store.getFolder(folder);
if(f != null && f.exists()) {
if(!f.isOpen()) f.open(Folder.READ_WRITE);
mgs = f.getMessages();
}
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
code.setText("1");
}
String subject;
if(mgs.length > 0) {
Element el = null;
for(int n = 0; n < mgs.length; n++) {
try {
String mgstate = getMessagState(mgs[n]);
if("/mail/images/new.gif".equals(mgstate)) {
charset = getCharset(mgs[n]);
if(charset.equals("null")) {
subject = encoding(mgs[n].getSubject(), "GBK");
}else{
subject = mgs[n].getSubject();
}
el = new Element("mgs");
el.setAttribute("mgsnum", String.valueOf(mgs[n].getMessageNumber()));
el.setAttribute("subject", subject.length() > 25? subject.substring(0,25): subject);
el.setAttribute("recieveTime", DateFormat(mgs[n].getReceivedDate()));
el.setAttribute("from", getFrom(mgs[n].getFrom()));
el.setAttribute("state", getMessagState(mgs[n]));
el.setAttribute("folder", mgs[n].getFolder().getName());
data.addContent(el);
}
}catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
code.setText("1");
}
}
}
//closeStore();
writeXMLToClient();
}
public void getMessageBody(String mgsnum, String folder, String type) {
javax.mail.Folder f;
MimeMessage message;
Object content;
Element mgsBody = new Element("mgsBody");
data.addContent(mgsBody);
try {
f = store.getFolder(folder);
if(!f.isOpen()) f.open(Folder.READ_WRITE);
message = (MimeMessage)f.getMessage(Integer.parseInt(mgsnum));
File tempfile = File.createTempFile("mailOut", null);
FileOutputStream fout = new FileOutputStream (tempfile);
message.writeTo(fout);
fout.flush();
fout.close();
message = new MimeMessage (null, new FileInputStream (tempfile));
content = message.getContent();
if(message.isMimeType("text/*")) {
String c = encoding(String.valueOf(content), "GBK");
mgsBody.addContent(new CDATA(c));
} else if (message.isMimeType("multipart/*")) {
Multipart mp = (Multipart) content;
CDATA cdata = new CDATA("");
mgsBody.addContent(cdata);
dumPart(mp, cdata, type);
//return ;
}
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
code.setText("1");
}catch(IOException e) {
e.printStackTrace();
code.setText("1");
}
data.setAttribute("attcount", String.valueOf(attcount));
data.setAttribute("attnames", attnames);
if("content".equals(type)) writeXMLToClient();
//closeStore();
}
public void getMessageBody(String mgsnum, String folder, String type, String attname) {
setAttname(attname);
getMessageBody(mgsnum, folder, type);
}
public void sendMail(String reveiver, String subject, String body, Set<Attachment> attachments) {
Properties properties = new Properties();
properties.put("mail.transport.protocol", SEND_MAIL_PROTOCOL);
properties.put("mail.smtp.class", "com.sun.mail.smtp.SMTPTransport");
properties.put("mail.smtp.host", SEND_MAIL_SERVER);
properties.put("mail.smtp.port", "25");
properties.put("mail.smtp.auth", "true");
// Session s = Session.getInstance(properties);
// final ActiveUser user = (ActiveUser) session.getAttribute("user");
Session s = Session.getInstance(properties,
new Authenticator(){
public PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication("
raymonbizos@21cn.com", "789456123");
}
});
try {
MimeMessage newMessage = new MimeMessage(s);
InternetAddress from = new InternetAddress("
raymonbizos@21cn.com");
newMessage.setFrom(from);// 設(shè)置發(fā)件人
InternetAddress[] replyto = new InternetAddress[1];
replyto[0] = from;
newMessage.setReplyTo(replyto);
newMessage.setSubject("=?GB2312?B?" + base64Encoder(subject) + "?=");
newMessage.setSentDate(new java.util.Date());
Multipart multipart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
String type = "text/html; charset=\"GB2312\"";
messageBodyPart.setContent(parseBody(body, subject),
type);
multipart.addBodyPart(messageBodyPart);
if(attachments != null && !attachments.isEmpty()) {
for(Attachment att : attachments) {
if(att.getPath() != null && !att.getPath().equals("")) {
MimeBodyPart mbodypart = new MimeBodyPart();
FileProxy fp = new FileProxy();
FileDataSource fds = new FileDataSource(fp.getDirRoot() + "/" + att.getPath());
mbodypart.setDataHandler(new DataHandler(fds));
mbodypart.setFileName(MimeUtility.encodeText(fds.getName(), "GB2312", "B"));
multipart.addBodyPart(mbodypart);
}
}
}
newMessage.setContent(multipart);
InternetAddress[] iadd = new InternetAddress[1];
iadd[0] = new InternetAddress(reveiver);
newMessage.setRecipients(Message.RecipientType.TO, iadd);// 設(shè)置收件人,并設(shè)置其接收類型為TO
try {
transport.connect(SEND_MAIL_SERVER, user.getUserName(), user.getPassword());// 以smtp方式登錄郵箱
} catch (Exception ex) {
ex.printStackTrace();
}
transport.sendMessage(newMessage, newMessage.getAllRecipients());// 發(fā)送郵件,其中第二個(gè)參數(shù)是所有
transport.close();*/
Transport.send(newMessage, newMessage.getAllRecipients());
} catch (Exception ex) {
ex.printStackTrace();
code.setText("1");
}
writeXMLToClient();
}
public void deleteMgses(String mgsnums, String folder) {
ArrayList<Integer> mgs = new ArrayList();
if(mgsnums != null) {
if(mgsnums.indexOf(":") == -1) {
mgs.add(Integer.parseInt(mgsnums));
}else{
String[] temp = mgsnums.split(":");
for(int n = 0; n < temp.length; n++) {
mgs.add(Integer.parseInt(temp[n]));
}
}
}else{
code.setText("1");
}
setFlag(folder, mgs, "delete", true);
//writeXMLToClient();
}
public void moveTo(String mgsids, String fromFolder, String toFolder) {
ArrayList<Integer> mgs = new ArrayList();
try {
if(mgsids != null) {
if(mgsids.indexOf(":") == -1) {
mgs.add(Integer.parseInt(mgsids));
}else{
String[] temp = mgsids.split(":");
for(int n = 0; n < temp.length; n++) {
mgs.add(Integer.parseInt(temp[n]));
log(temp[n]);
}
}
int[] mgses = new int[mgs.size()];
for(int n = 0; n < mgses.length; n++) {
mgses[n] = mgs.get(n);
}
Folder f;
if(!store.isConnected()) store.connect();
f = store.getFolder(fromFolder);
if(f != null && f.exists()) {
if(!f.isOpen()) f.open(Folder.READ_WRITE);
}
Message[] messages = f.getMessages(mgses);
Folder tofolder = store.getFolder(toFolder);
f.copyMessages(messages, tofolder);
f.setFlags(messages, new Flags(Flags.Flag.DELETED), true);
//f.expunge();
//f.close(true);
}else{
code.setText("1");
}
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
code.setText("1");
}
//closeStore();
writeXMLToClient();
}
public void clearFolderMessages(String folder) {
Folder f;
try{
if(!store.isConnected()) store.connect();
f = store.getFolder(folder);
if(f != null && f.exists()) {
if(!f.isOpen()) f.open(Folder.READ_WRITE);
}
Message[] messages = f.getMessages();
if(messages != null) {
f.setFlags(messages, new Flags(Flags.Flag.DELETED), true);
}
//f.close(true);
}catch(Exception e) {
e.printStackTrace();
code.setText("1");
}
//closeStore();
writeXMLToClient();
}
public void transferSend(String to, int mgsnum, String folder, String body, Set<Attachment> attachments, String hasAtt) {
Properties properties = new Properties();
properties.put("mail.transport.protocol", SEND_MAIL_PROTOCOL);
properties.put("mail.smtp.class", "com.sun.mail.smtp.SMTPTransport");
properties.put("mail.smtp.host", SEND_MAIL_SERVER);
properties.put("mail.smtp.port", "25");
properties.put("mail.smtp.auth", "true");
Session s = Session.getInstance(properties,
new Authenticator(){
public PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication("
raymonbizos@21cn.com", "789456123");
}
});
try{
Folder f;
if(!store.isConnected()) store.connect();
f = store.getFolder(folder);
if(f != null && f.exists()) {
if(!f.isOpen()) f.open(Folder.READ_WRITE);
Message mgs = (MimeMessage) f.getMessage(mgsnum);
File tempfile = File.createTempFile("mailOut", null);
FileOutputStream fout = new FileOutputStream (tempfile);
mgs.writeTo(fout);
fout.flush();
fout.close();
MimeMessage mmgs = new MimeMessage (s, new FileInputStream (tempfile));
mmgs.setFrom(new InternetAddress("
raymonbizos@21cn.com"));
InternetAddress[] iadd = new InternetAddress[1];
iadd[0] = new InternetAddress(to);
mmgs.setRecipients(Message.RecipientType.TO, iadd);// 設(shè)置收件人,并設(shè)置其接收類型為TO
Transport.send(mmgs, mmgs.getAllRecipients());
}
}catch(MessagingException e){
e.printStackTrace();
code.setText("1");
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
writeXMLToClient();
}
public void setStore(Store store) {
this.store = store;
}
public Store getStore() {
return this.store;
}
public void setSession(HttpSession session) {
this.session = session;
}
public HttpSession getSession() {
return this.session;
}
private String getPostfix(String value) {
int pos = value.lastIndexOf(".");
return value.substring(pos);
}
public void setFlag(String folder, ArrayList<Integer> mgsids, String flag, boolean isOutPrintXML) {
Hashtable<String, Flags.Flag> flags = new Hashtable();
flags.put("seen", Flags.Flag.SEEN);
flags.put("delete", Flags.Flag.DELETED);
flags.put("ansered", Flags.Flag.ANSWERED);
Folder f = null;
try {
f = store.getFolder(folder);
if(f != null && f.exists()) {
if(!f.isOpen()) f.open(Folder.READ_WRITE);
Message mgs = null;
for(int n = 0; n < mgsids.size(); n++) {
mgs = f.getMessage(mgsids.get(n));
if(mgs != null) mgs.setFlag(flags.get(flag), true);
}
//f.close(false);
//f.setFlags(mgsids, new Flags(Flags.Flag.DELETED), true);
}
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
code.setText("1");
}
if(isOutPrintXML) writeXMLToClient();
}
private Message[] getMgses(String folder) {
Folder f = null;
Message[] mgs = null;
try {
if(!store.isConnected()) store.connect();
f = store.getFolder(folder);
if(f != null && f.exists()) {
if(!f.isOpen()) f.open(Folder.READ_WRITE);
mgs = f.getMessages();
}
//f.close(false);
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
code.setText("1");
}
//closeStore();
return mgs;
}
private static String parseBody(String value, String subject) {
return buildHTML(value, subject);
/*if(value == null || value.trim().equals("")) return value;
if(!isHTML(value)) return base64Encoder(value);
return base64Encoder(buildHTML(value, subject));*/
}
private static boolean isHTML(String value) {
return true;
/*Pattern pattern = Pattern.compile("(<+/>)", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
Matcher m = pattern.matcher(parse(value));
if (m.groupCount() > 1) {
return true;
}
return false;*/
}
private void setAttname(String attname) {
this.attname = attname;
}
private static String buildHTML(String value, String subject) {
StringBuffer sb = new StringBuffer();
sb.append("<HTML>\n");
sb.append("<HEAD>\n");
sb.append("<TITLE>\n");
sb.append(subject + "\n");
sb.append("</TITLE>\n");
sb.append("</HEAD>\n");
sb.append("<BODY>\n");
sb.append("<H1>" + subject + "</H1>" + "\n");
sb.append(value);
sb.append("</BODY>\n");
sb.append("</HTML>\n");
return sb.toString();
}
private String getMessagState(Message mgs) {
Flags flags = null;
String rvalue = "/mail/images/new.gif";
try {
flags = mgs.getFlags();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Flags.Flag[] sf = flags.getSystemFlags();
for(int n = 0; n < sf.length; n++) {
if(sf[n] == Flags.Flag.ANSWERED) {
rvalue = "/mail/images/ansered.gif";
break;
}
if(sf[n] == Flags.Flag.SEEN) {
rvalue = "/mail/images/seen.gif";
break;
}
}
return rvalue;
}
private String transition(String value) {
if(value == null || value.trim() == "") return value;
String temp = value.toLowerCase();
temp = (String) foldersType.get(temp);
if(temp != null) return temp;
return value;
}
private void saveFile(InputStream in, String fileName) {
try {
FileProxy fp = new FileProxy();
String savetoPath = fp.getDirRoot() + "/temp";
File file = new File(savetoPath);
if(!file.isDirectory()) file.mkdirs();
FileOutputStream fout = new FileOutputStream(savetoPath + "/" + fileName);
int r = 0;
while((r = in.read()) != -1) {
fout.write(r);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void closeStore() {
try {
store.close();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String DateFormat(Date value) {
DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
if(value == null) return "";
return fmt.format(value);
}
private void dumPart(Multipart p, CDATA cdata, String type) {
Object content = null;
try {
int numParts = p.getCount();
for(int i = 0; i < numParts; i++) {
Part messagePart = p.getBodyPart(i);
content = messagePart.getContent();
if(messagePart.isMimeType("multipart/*")) {
Multipart mp = (Multipart) content;
dumPart(mp, cdata, type);
}else {
if(messagePart.isMimeType("text/*")){
//文本
if(messagePart.getFileName() == null){
String c = (String) messagePart.getContent();
if(messagePart.isMimeType("text/plain")) {
cdata.append(c);
}
if(messagePart.isMimeType("text/html")){
cdata.append(c);
bodyType = "text/html";
}
}else{
//文本附件
String filename = MimeUtility.decodeText(messagePart.getFileName());
if(attcount == 0) {
attnames += filename;
}else{
attnames += ":" + filename;
}
attcount++; //附件數(shù)量
if("attachment".equals(type)) getAttachment(messagePart);
}
}else{
//二進(jìn)制文件
String disp = messagePart.getDisposition();
String contentId = ((MimePart)messagePart).getContentID();
if(disp != null && disp.equalsIgnoreCase(Part.ATTACHMENT)){
//二進(jìn)制附件
String filename = MimeUtility.decodeText(messagePart.getFileName());
if(attcount == 0) {
attnames += filename;
}else{
attnames += ":" + filename;
}
attcount++;//附件數(shù)量
if("attachment".equals(type)) getAttachment(messagePart);
}else if(contentId != null){
//***********************************************************************
//在此得到超文本正文中的圖片
hasCID = true;
contentId = contentId.replace("<", "");
contentId = contentId.replace(">", "");
String filename = MimeUtility.decodeText(messagePart.getFileName());
if(filename != null){
if(!isFileExists(contentId)) {
saveFile(messagePart.getInputStream(), contentId + getPostfix(filename));
}
cidmaps.put(contentId, "/file/FileService?actionType=download&filePath=temp/" + contentId + getPostfix(filename));
//saveFile(part.getInputStream(),filename);//保存圖片,
//同時(shí)還要保存圖片id,即contentId,以便于用圖片路徑替換正文中的圖片id
//具體存儲(chǔ)看你的數(shù)據(jù)結(jié)構(gòu)或這數(shù)據(jù)庫了,我這力沒有相關(guān)實(shí)現(xiàn)
}
}
}
/*InputStream ipstm = messagePart.getInputStream();
BufferedReader bufreader = new BufferedReader(new InputStreamReader(ipstm));
String thisLine = bufreader.readLine();
while (thisLine != null){
thisLine = new String(thisLine.getBytes("ISO-8859-1"), "GBK");
System.out.println("=====thisLine: "+thisLine);
thisLine = bufreader.readLine();
} */
//return "";
}
}
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//return "";
}
private boolean isFileExists(String fileName) {
FileProxy fp = new FileProxy();
File file = new File(fp.getDirRoot() + "/temp/" + fileName);
if(file.exists()) return true;
return false;
}
private void getAttachment(Part messagePart) {
try{
String filename = MimeUtility.decodeText(messagePart.getFileName());
if(filename.equals(this.attname)) {
response.setCharacterEncoding("ISO-8859-1");
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
InputStream in = messagePart.getInputStream();
int r;
OutputStream out = response.getOutputStream();
while((r = in.read()) != -1) {
out.write(r);
}
in.close();
out.flush();
out.close();
}
//String contentType = messagePart.getContentType();
}catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void log(String value) {
System.out.println(" | MY-INF: " + value + " |");
}
private static String base64Encoder(String value) {
if(value == null || value.trim() == "") return value;
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(value.getBytes());
}
private String getCharset(Message mgs) {
String charset = "null";
Pattern encodeStringPattern = Pattern.compile("=\\?(.+)\\?(B|Q)\\?(.+)\\?=", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
String[] CHARTSET_HEADER = new String[] { "Subject", "From", "To", "Cc", "Delivered-To" };
Enumeration headerInf = null;
MimeMessage tempmgs = (MimeMessage) mgs;
MimeMessage newmgs = null;
try {
newmgs = new MimeMessage(tempmgs);
} catch (MessagingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
headerInf = newmgs.getMatchingHeaders(CHARTSET_HEADER);
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (headerInf.hasMoreElements()) {
Header h = (Header)headerInf.nextElement();
Matcher m = encodeStringPattern.matcher(parse(h.getValue()));
if (m.find()) {
charset = m.group(1);
break;
}
}
return charset;
}
private String getFrom(Address[] address) {
if(address == null) return "未知";
String adr = "";
for(int n = 0; n < address.length; n++)
adr += address[n].toString();
try {
return MimeUtility.decodeText(encoding(adr, "GBK"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "未知";
}
private String parse(String value) {
/*
* Parse Subject like : =?gb2312?B?z8LU2FZnb7/Nu6e2y6Oss8nB+qGi1tzQx7PboaK6w8Czzuu088asoaI3MA==?=
* =?gb2312?B?uPbN+MLntefK08a1tcDD4rfRv7SjoQ==?=
*/
if(value == null) return value;
if (!value.startsWith("=?")) // not an encoded word
return value;
int start = 2; int pos;
if ((pos = value.indexOf(‘?‘, start)) == -1)
return value;
String charset = value.substring(start, pos);
String temp = value.substring(pos);
start = pos + 1;
if ((pos = value.indexOf(‘?‘, start)) == -1)
return value;
//String encoding = value.substring(start, pos);
if(temp.indexOf(charset) != -1 && value.indexOf("?=") != pos) {
pos = value.indexOf("?=");
return value.substring(0, pos + 2);
}
return value;
}
private String encoding(String value, String charset) {
if(value == null || value.trim().length() == 0) return value;
try {
String rvalue = new String(value.getBytes("ISO-8859-1"), charset);
return rvalue;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return value;
}
private void writeXMLToClient() {
try {
response.setContentType("text/xml");
if(hasCID) {
replaceCID();
}
Format format = Format.getCompactFormat();
format.setEncoding("UTF-8");
format.setIndent(" ");
XMLOutputter XMLOut = new XMLOutputter(format);
XMLOut.output(doc, response.getWriter());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void replaceCID() {
Element root = doc.getRootElement();
Element datael = root.getChild("Data");
Element cel = null;
if(datael != null) {
cel = datael.getChild("mgsBody");
CDATA ct = (CDATA) cel.getContent(0);
String content = ct.getText();
if(content != null && content.trim() != "" && "text/html".equals(bodyType)) {
Set<String> keys = cidmaps.keySet();
for(String key : keys) {
content = content.replace("cid:" + key, cidmaps.get(key));
}
}
ct.setText(content);
}
}
}