⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mailutil.java

📁 mywork是rcp开发的很好的例子
💻 JAVA
字号:
package net.sf.pim.mail;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.URLName;
import javax.mail.internet.MimeUtility;

import net.sf.util.StringUtil;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.program.Program;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;

/**
 * 读取邮件的静态方法
 * @author levin
 */
public class MailUtil {
	static{
		System.setProperty("mail.mime.decodefilename","true");
		System.setProperty("mail.mime.encodeeol.strict", "true");
	}
	
    // 取part的文件名
    static int attnum = 1;

	//取message中的附件,保存在hashMap中
	public static void dumpPart(Part p, HashMap<String, Part> attachments)
			throws Exception {
		if (!p.isMimeType("multipart/*")) {
			String disp = p.getDisposition();
			// Content-Disposition of attachment or sometime inline 
			if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE)) ) {
				String fl = MailUtil.getFileName(p);
				String fn = new File(fl).getName();
	
				// store the attachment and an image content id too
				attachments.put(fn, p);
				return;
			}
		} else if (p.isMimeType("multipart/*")) {
			// Here it's a Multipart so we recurse into the content Parts calling dumpPart for each.
			Multipart mp = (Multipart) p.getContent();
			int count = mp.getCount();
			for (int i = 0; i < count; i++) {
				dumpPart(mp.getBodyPart(i), attachments);
			}
		} else if (p.isMimeType("message/rfc822")) {
			// drill down to the part in the rfc822 message
			dumpPart((Part) p.getContent(), attachments);
		}
	}

	public static String getFileName(Part p) throws Exception {
	    String filename = p.getFileName();
	    if (filename == null || filename.trim().equals("")) {
	        // if there isn't one, make one up!  attnum stores a count for
	        // making unique attachment names.  It is static to make sure it
	        // remains unique while mousetrap is running.  Using attnum prevents
	        // naming conflicts between filenames.
	        filename = "Attachment" + (attnum++) + ".att";
	    }
	    else {
	        try {
	            filename = new File(filename).getName();
	
	            // We have to remove illegal filename chars for windows to
	            // save the files correctly (e.g. when the user presses
	            // Save All Attachments).
	            String illegalChars[] =
	                {"\\\\", "\\/", "\\:", "\\*", "\\?", "\\\"", "\\<", "\\>", "\\|", "\\n", "\\r", "\\t"};
	            for(int i=0; i<illegalChars.length; i++) {
	                filename = filename.replaceAll(illegalChars[i], "_");
	            }
	        }
	        catch(Exception ex) {
	            filename = "Attachment" + (++attnum) + ".att";
	        }
	    }
	    return filename;
	}

	//转换地址
	public static String getAddress(Address[] adds) {
		StringBuffer sb=new StringBuffer();
		if (adds != null && adds.length != 0) {
			for(int i=0;i<adds.length;i++)
				try {
					sb.append(/*MimeUtility.decodeWord(*/adds[i].toString()).append(";");
				} catch (Exception e) {
					sb.append(adds[i].toString()).append(";");
				}
		}
		if(sb.length() >1 && sb.charAt(sb.length() -1) == ';')
			sb.deleteCharAt(sb.length()-1);
		return guessGBK(sb.toString());
	}

	//转换发送时间
	public static String getSentTime(Message msg) throws MessagingException {
		//20070802 修订sentdate为null时substring(4)的bug
		if(msg.getSentDate()==null)
			return "....";
		return new SimpleDateFormat("yyyyMMdd kk:mm").format(msg.getSentDate());
	}

	//取某类文件的图标
	public static Image getImage(String fileName){
		String fileType=getTail(fileName,'.');
		Image image = null;
		Program p = Program.findProgram ("."+fileType);
		if (p != null) {
			ImageData data = p.getImageData ();
			if (data != null) {
				image = new Image (Display.getDefault(), data);
			}
		}
		return image;
	}
	
	//取某个字串的后半截,如文件扩展名等
	public static String getTail(String full,char delim){
		if(full.lastIndexOf(delim) == -1)
			return null;
		return full.substring(full.lastIndexOf(delim)+1);
	}

	//重新计算一个控件的大小
	public static void resetSize(Control control){
		control.setSize(control.computeSize(SWT.DEFAULT, SWT.DEFAULT));
	}

	//转换邮件字符串至数组
	public static String[][] spliteAddress(String s) {
		String[] ss=StringUtil.toArray(s, ";");
		String[][] list=new String[ss.length][2];
		for(int i=0;i<ss.length;i++){
			int start=ss[i].indexOf('<');
			if(start != -1){
				list[i][0]=trimQuota(ss[i].substring(0,start));
				list[i][1]=ss[i].substring(start+1,ss[i].length()-1);
			}else{
				start = ss[i].indexOf('@');
				if(start != -1){
					list[i][0]=ss[i].substring(0,start);
					list[i][1]=ss[i];
					}
				else{
					list[i][0]=ss[i];
					list[i][1]=ss[i];
				}
			}
		}
		return list;
	}
	
	//取bodyText
    public static String dumpBodyText(Part p) {
    	StringBuffer text=new StringBuffer();
    	_dumpHtml(p,text,new StringBuffer());
    	return text.toString();
	}
    
    //取bodyhtml
    public static String dumpBodyHtml(Part p) {
    	StringBuffer text=new StringBuffer();
    	StringBuffer html=new StringBuffer();
    	_dumpHtml(p,text,html);
    	//没取着html就取text
    	if(StringUtil.isNull(html))
    		return "<pre>"+text.toString()+"</pre>";
    	else if(!html.toString().startsWith("<html"))
    		return "<html>"+html.toString()+"</html>";
    	else
    		return html.toString();
	}

    private static void _dumpHtml(Part p,StringBuffer textBuffer,StringBuffer htmlBuffer){
		try {
			Object content = p.getContent();
			if (p.isMimeType("text/plain")) {
				textBuffer.append(content);
			}else if (p.isMimeType("text/html")) {
					htmlBuffer.append(content);
			} else if (p.isMimeType("multipart/*")) {
				Multipart mp = (Multipart) content;
				int count = mp.getCount();
				for (int i = 0; i < count; i++) {
					_dumpHtml(mp.getBodyPart(i),textBuffer,htmlBuffer);
				}
			} else if (p.isMimeType("message/rfc822")) {
				_dumpHtml((Part) content,textBuffer,htmlBuffer);
			}
		} catch (Exception ex) {
			;
		}
    }
    
    //去掉首尾双引号
	public static String trimQuota(String from) {
		if(from.length() >0 && from.charAt(0) == '"')
			from=from.substring(1).trim();
		
		if(from.length() >0 && from.charAt(from.length() -1) == '"')
			from=from.substring(0,from.length()-1).trim();
		return from;
	}
	
	//解析urlname后面的参数
	public static Map<String, String> parseParameters(URLName urlname) {
		Map<String, String> options = new HashMap<String,String>();
		String optstr = urlname.getFile();
		if (optstr != null) {
			final int startpos = optstr.indexOf('?');
			if (startpos != -1 && startpos < optstr.length() - 1) {
				optstr = optstr.substring(startpos + 1);
				StringTokenizer st = new StringTokenizer(optstr, "&");
				while (st.hasMoreTokens()) {
					String pair = st.nextToken();
					int eqpos = pair.indexOf('=');
					String lvalue = (eqpos != -1) ? pair.substring(0, eqpos) : null;
					String rvalue = (eqpos != -1 && eqpos < pair.length() - 1) ? pair.substring(eqpos + 1) : null;
					if (lvalue != null) {
						options.put(lvalue, rvalue);
					}
				}
			}
		}
		return options;
	}

	public static String getSubject(Message msg) throws MessagingException {
		String s= msg.getSubject() == null ?"":msg.getHeader("Subject")[0];
		return guessGBK(s);
	}

	//处理为汉字,且未编码的不标准邮件
	public static String guessGBK(String s) {
		if(s==null)return "";
		//20080815 有编码的不处理
		if(s.indexOf("=?") > -1){
			try {
				return MimeUtility.decodeText(s);
			} catch (UnsupportedEncodingException e) {
				;
			}
		}
		ByteBuffer bf = Charset.forName("ISO8859-1").encode(s);
		return Charset.forName("GBK").decode(bf).toString();
	}	
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -