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

📄 mailutil.java

📁 PIMailReader 基于RCP eclipse的邮件接收小程序
💻 JAVA
字号:
package net.sf.pim.mail;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.HashMap;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
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");
	}
	
    // 取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
			if (disp != null && disp.equalsIgnoreCase(Part.ATTACHMENT)) {
				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 void copyIntput2Output(InputStream is, OutputStream os) throws IOException {
	    byte[] buffer = new byte[1024];
	    int bytesRead = 0;
	    try {
	        if (is == null || os == null) {
	            throw new IllegalArgumentException("Specified resource does not exist: " + is + "or" + os + ".");
	        }
	        do {
	            bytesRead = is.read(buffer);
	            if (bytesRead > 0) {
	                os.write(buffer, 0, bytesRead);
	            }
	        } while (bytesRead > 0);
	    } finally {
	        if (is != null) {
	            is.close();
	        }
	        if (os != null) {
	            os.close();
	        }
	    }
	}

	//转换地址
	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(";");
				}
		}
		return sb.toString();
	}

	//转换接收时间
	public static String getSentTime(Message msg) throws MessagingException {
		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('<');
			list[i][0]=ss[i].substring(0,start);
			list[i][1]=ss[i].substring(start+1,ss[i].length()-1);
		}
		return list;
	}
	
	//取bodyText
    public static String dumpBodyText(Part p) {
		try {
			if (p.isMimeType("text/plain")) {
				return ((String) p.getContent());
			} else if (p.isMimeType("multipart/*")) {
				Multipart mp = (Multipart) p.getContent();
				int count = mp.getCount();
				for (int i = 0; i < count; i++) {
					return dumpBodyText(mp.getBodyPart(i));
				}
			} else if (p.isMimeType("message/rfc822")) {
				return dumpBodyText((Part) p.getContent());
			}
		} catch (Exception ex) {
			;
		}
		return "";
	}	
}

⌨️ 快捷键说明

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