自己写的java邮件客户端

网上类似的java客户端很多,因为javamail的API的确是挺好用的。我也参考了其中一个人的代码 省了不少事,这篇博客主要是自己留个纪念,因为这个项目更多的是自己一些特殊的需求,别人应该不需要用到。

package receiveMail;

import java.io.*;
import java.text.*;
import java.util.*;
import java.util.zip.ZipException;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.Message.RecipientType;
import javax.mail.internet.*;

import sun.misc.BASE64Encoder;

public class PraseMimeMessage {
	private MimeMessage mimeMessage = null;
	private String saveAttachPath = "";
	private StringBuffer bodytext = new StringBuffer();
	// StringBuffer
	private String dateformat = "yy-MM-dd HH:mm";

	private File storefile;
	private String storedir = null;
	private Process ps = null;   //invokeBatStorePdb
	//long chunk;

	public Process getPs() {
		return ps;
	}

	//private Multipart multipart = new MimeMultipart();  //forwardmail()
	CompressZIP bean = CompressZIP.getInstance();

	private int hasPdb, hasRar,hasZip;

	public int getHasRar() {
		return hasRar;
	}

	public void setHasRar(int hasRar) {
		this.hasRar = hasRar;
	}

	public int getHasZip() {
		return hasZip;
	}

	public void setHasZip(int hasZip) {
		this.hasZip = hasZip;
	}

	public int getHasPdb() {
		return hasPdb;
	}

	public void setHasPdb(int hasPdb) {
		this.hasPdb = hasPdb;
	}

	/**
	 *
	 */
	public PraseMimeMessage() {
	}

	public PraseMimeMessage(MimeMessage mimeMessage) {
		this.mimeMessage = mimeMessage;
		// System.out.println("create a PraseMimeMessage object........");
	}

	public void setMimeMessage(MimeMessage mimeMessage) {
		this.mimeMessage = mimeMessage;
	}

	/**
	 *
	 */
	public String getFrom() throws Exception {
		InternetAddress address[] = (InternetAddress[]) mimeMessage.getFrom();
		String from = address[0].getAddress();
		if (from == null)
			from = "";
		String personal = address[0].getPersonal();
		if (personal == null)
			personal = "";
		String fromaddr = personal + "<" + from + ">";
		return fromaddr;
	}

	public String getMailAddress(String type) throws Exception {
		String mailaddr = "";
		String addtype = type.toUpperCase();
		InternetAddress[] address = null;
		if (addtype.equals("TO") || addtype.equals("CC") || addtype.equals("BCC")) {
			if (addtype.equals("TO")) {
				address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.TO);
			} else if (addtype.equals("CC")) {
				address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.CC);
			} else {
				address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.BCC);
			}
			if (address != null) {
				for (int i = 0; i < address.length; i++) {
					String email = address[i].getAddress();
					if (email == null)
						email = "";
					else {
						email = MimeUtility.decodeText(email);
					}
					String personal = address[i].getPersonal();
					if (personal == null)
						personal = "";
					else {
						personal = MimeUtility.decodeText(personal);
					}
					String compositeto = personal + "<" + email + ">";
					mailaddr += "," + compositeto;
				}
				mailaddr = mailaddr.substring(1);
			}
		} else {
			throw new Exception("Error emailaddr type!");
		}
		return mailaddr;
	}

	/**
	 *
	 */

	public String getSubject() throws MessagingException {
		String subject = "";
		try {
			subject = MimeUtility.decodeText(mimeMessage.getSubject());
			if (subject == null)
				subject = "";
		} catch (Exception exce) {
		}
		return subject;
	}

	/**
	 *
	 */

	public String getSentDate() throws Exception {
		Date sentdate = mimeMessage.getSentDate();
		SimpleDateFormat format = new SimpleDateFormat(dateformat);
		return format.format(sentdate);
	}

	public String getBodyText() {
		//System.out.println(bodytext.toString());
		return bodytext.toString();
	}

	public void getMailContent(Part part) throws Exception {
		String contenttype = part.getContentType();
		int nameindex = contenttype.indexOf("name");
		boolean conname = false;
		if (nameindex != -1)
			conname = true;
		//System.out.println("CONTENTTYPE: " + contenttype);
		if (part.isMimeType("text/plain") && !conname) {
			bodytext.append((String) part.getContent());
		} else if (part.isMimeType("text/html") && !conname) {
			//bodytext.append((String) part.getContent());
		} else if (part.isMimeType("multipart/*")) {
			Multipart multipart = (Multipart) part.getContent();
			int counts = multipart.getCount();
			for (int i = 0; i < counts; i++) {
				getMailContent(multipart.getBodyPart(i));
			}
		} else if (part.isMimeType("message/rfc822")) {
			getMailContent((Part) part.getContent());
		} else {
		}
	}

	/**
	 *
	 */
	public boolean getReplySign() throws MessagingException {
		boolean replysign = false;
		String needreply[] = mimeMessage.getHeader("Disposition-Notification-To");
		if (needreply != null) {
			replysign = true;
		}
		return replysign;
	}

	/**
	 *
	 */
	public String getMessageId() throws MessagingException {
		return mimeMessage.getMessageID();
	}

	/**
	 *
	 */
	public boolean isNew() throws MessagingException {
		boolean isnew = false;
		Flags flags = ((Message) mimeMessage).getFlags();
		Flags.Flag[] flag = flags.getSystemFlags();
		System.out.println("flags's length: " + flag.length);
		for (int i = 0; i < flag.length; i++) {
			if (flag[i] == Flags.Flag.SEEN) {
				isnew = true;
				System.out.println("seen Message.......");
				break;
			}
		}
		return isnew;
	}

	/**
	 *
	 */
	public boolean isContainAttach(Part part) throws Exception {
		boolean attachflag = false;
		// String contentType = part.getContentType();
		if (part.isMimeType("multipart/*")) {
			Multipart mp = (Multipart) part.getContent();
			for (int i = 0; i < mp.getCount(); i++) {
				BodyPart mpart = mp.getBodyPart(i);
				String disposition = mpart.getDisposition();
				if ((disposition != null)
						&& ((disposition.equals(Part.ATTACHMENT)) || (disposition.equals(Part.INLINE))))
					attachflag = true;
				else if (mpart.isMimeType("multipart/*")) {
					attachflag = isContainAttach((Part) mpart);
				} else {
					String contype = mpart.getContentType();
					if (contype.toLowerCase().indexOf("application") != -1)
						attachflag = true;
					if (contype.toLowerCase().indexOf("name") != -1)
						attachflag = true;
				}
			}
		} else if (part.isMimeType("message/rfc822")) {
			attachflag = isContainAttach((Part) part.getContent());
		}
		return attachflag;
	}

	/**
	 *
	 */

	public void saveAttachMent(Part part,PraseMimeMessage pmessage , String senderFrom) throws Exception {
		String fileName = "";
		//String savaPath = "";  //附件保存路径 增加以附件大小为名的文件夹(后期可能用uuid)
		//int chunk = 0;
		String uuid = "";
		if (part.isMimeType("multipart/*")) {
			Multipart mp = (Multipart) part.getContent();
			for (int i = 0; i < mp.getCount(); i++) {
				BodyPart mpart = mp.getBodyPart(i);
				String disposition = mpart.getDisposition();
				if ((disposition != null)
						&& ((disposition.equals(Part.ATTACHMENT)) || (disposition.equals(Part.INLINE)))) {
					fileName = mpart.getFileName();
					System.out.println("mpart.getFileName():" + fileName);
					//chunk = mpart.getSize();//获取邮件附件大小?  不知道对不对 可能不准确 (Return the number of lines in the content of this part.)
					//System.out.println("邮件附件大小: " + chunk);
					uuid = UUID.randomUUID().toString();
					if (fileName.toLowerCase().indexOf("gb2312") != -1) {
						fileName = MimeUtility.decodeText(fileName);
						System.out.println("decodeText fileName:" + fileName);
					}
					if (fileName.toLowerCase().indexOf("utf") != -1) {
						fileName = MimeUtility.decodeText(fileName);
						System.out.println("decodeText fileName:" + fileName);
					}
					int j = fileName.toLowerCase().indexOf("utf");
					System.out.println("indexOf utf" + j);

					//saveFile(fileName, mpart.getInputStream());   //fileName为附件名 如1.rar
					long start = System.currentTimeMillis();
					//saveFile(chunk,fileName, mpart.getInputStream());
					saveFile(uuid,fileName, mpart.getInputStream(), senderFrom);
					long end = System.currentTimeMillis();
					System.out.println("Save Last Time" + (end - start));

					unCompress(fileName,storefile, storedir);
					//
					if(fileName.endsWith(".rar")|| fileName.endsWith(".zip")){
						storefile.delete();
					}

					//createAttach(fileName, pmessage); //...
				} else if (mpart.isMimeType("multipart/*")) {
					saveAttachMent(mpart,pmessage,senderFrom);
				} else {
					fileName = mpart.getFileName();
					if ((fileName != null) && (fileName.toLowerCase().indexOf("GB2312") != -1)) {
						fileName = MimeUtility.decodeText(fileName);

						//saveFile(chunk,fileName, mpart.getInputStream());//
						saveFile(uuid,fileName, mpart.getInputStream(),senderFrom);
						unCompress(fileName, storefile, storedir);
						System.out.println("ELSE multipart/*");
						//createAttach(fileName,pmessage); //...
					}
				}
			}
		} else if (part.isMimeType("message/rfc822")) {
			saveAttachMent((Part) part.getContent(),pmessage,senderFrom);
		}
	}

	//
	public void invokeBatStorePdb(String senderFrom) {
		System.out.println("invokeBatStorePdb");
		Runtime rt = Runtime.getRuntime();
		 //System.out.println("DL:" +storedir + storefile.toString());
		//String command = "cmd.exe /C start /b C:\\symstore.bat c:\\tmp\\symbols"; // c:\\tmp\\symbols   storedir
		String command = "cmd.exe /C start /b C:\\symstore-del.bat c:\\tmp\\symbols" + "\\" + senderFrom;
		if(senderFrom.isEmpty() || senderFrom.equals("")){
			command = "cmd.exe /C start /b C:\\symstore-del.bat c:\\tmp\\symbols";
			System.out.println("senderFrom为空");
		}
		//Process ps = null;
		try {
			ps = rt.exec(command);
			// final BufferedReader normalReader = new BufferedReader(new
			// InputStreamReader(ps.getInputStream()));
			// final BufferedReader errorReader = new BufferedReader(new
			// InputStreamReader(ps.getErrorStream()));

			final InputStream normalStream = ps.getInputStream();
			final InputStream errorStream = ps.getErrorStream();

			new Thread() {
				public void run() {
					BufferedReader br1 = new BufferedReader(new InputStreamReader(normalStream));
					try {
						String line1 = null;
						while ((line1 = br1.readLine()) != null) {
							if (line1 != null) {
							}
						}
					} catch (IOException e) {
						e.printStackTrace();
					} finally {
						try {
							normalStream.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}.start();
			new Thread() {
				public void run() {
					BufferedReader br2 = new BufferedReader(new InputStreamReader(errorStream));
					try {
						String line2 = null;
						while ((line2 = br2.readLine()) != null) {
							if (line2 != null) {
							}
						}
					} catch (IOException e) {
						e.printStackTrace();
					} finally {
						try {
							errorStream.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}.start();

			try {
				if(ps.waitFor() !=0){
					System.err.println("exit value = " + ps.exitValue());
				}
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			ps.destroy();
			//System.out.println("");
		} catch (Exception e) {
			try {
				ps.getErrorStream().close();
				ps.getInputStream().close();
				ps.getOutputStream().close();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

		}
	}

	//
	public  void clearDir(File file) {
        if (file.isDirectory()) {
            for (File f : file.listFiles()) {
                clearDir(f);
                //if(!(f.getPath().endsWith(".pdb")))
                f.delete();
            }
        }
        	if(!file.getPath().endsWith(".pdb"))
        		//file.delete();
        		file.getAbsoluteFile().delete();
        	//System.out.println("file delete" + file.getAbsoluteFile().delete());
        	//log.debug();
    } 

	/**
	 *
	 */

	public void setAttachPath(String attachpath) {
		this.saveAttachPath = attachpath;
	}

	/**
	 *
	 */

	public void setDateFormat(String format) throws Exception {
		this.dateformat = format;
	}

	/**
	 *
	 */

	public String getAttachPath() {
		return saveAttachPath;
	}

	/**
	 * ?
	 */

	private void saveFile( String uuid,String fileName, InputStream in, String senderFrom) throws Exception {  //chunk为附件大小int chunk,
		String osName = System.getProperty("os.name");
		// String storedir = getAttachPath();
		storedir = getAttachPath();
		String separator = "";
		if (osName == null)
			osName = "";
		if (osName.toLowerCase().indexOf("win") != -1) {
			separator = "\\";
			if (storedir == null || storedir.equals(""))
				storedir = "c:\\tmp";
		} else {
			separator = "/";
			storedir = "/tmp";
		}

		int index1;
		String rarName = null;
		String sendPerson = senderFrom;
		if ((index1 = fileName.lastIndexOf(".")) != -1) {// 获取压缩包xxx.rar的文件名xxx
			rarName = fileName.substring(0, index1);
		}
		//storedir = storedir + separator + rarName + separator + String.valueOf(chunk);  //c:\\tmp\\symbols\\1\1170232
		storedir = storedir + separator + sendPerson + separator +rarName + separator + uuid; //c:\\tmp\\symbols\\zhangsan\\1\\1170232
		//storedir = storedir + separator + rarName + separator + uuid;
		// File storefile = new File(storedir + separator + fileName);
		storefile = new File(storedir + separator + fileName);  //c:\\tmp\\symbols\\1\1170232\\1.rar
		if (!storefile.exists()) {
			if (!storefile.getParentFile().exists()) {//
				storefile.getParentFile().mkdirs();
			}
			System.out.println("storefile out: " + storefile);
			storefile.createNewFile();
		}
		System.out.println("storefile's path: " + storefile.toString());
		// for(int i=0;storefile.exists();i++){
		// storefile = new File(storedir+separator+fileName+i);
		// }
		BufferedOutputStream bos = null;
		BufferedInputStream bis = null;
		try {
			bos = new BufferedOutputStream(new FileOutputStream(storefile));
			bis = new BufferedInputStream(in);
			int c;
			while ((c = bis.read()) != -1) {
				bos.write(c);
				bos.flush();
			}
		} catch (Exception exception) {
			exception.printStackTrace();
			throw new Exception("exception");
		} finally {
			bos.close();
			bis.close();
		}
	}

	/*
	 * private void createAttach(String fileName,PraseMimeMessage pmessage)
	 * throws MessagingException { // BodyPart bp1 = new MimeBodyPart(); //
	 * bp1.setText(pmessage.getBodyText()); // System.out.println("DL" +
	 * pmessage.getBodyText());
	 *
	 * //hasPdb = 0; //Multipart multipart = new MimeMultipart(); String suffix
	 * = ".pdb"; if(fileName.endsWith(suffix)){ System.out.println("DL" +
	 * "PDB Attach"); ++hasPdb; return; } String suffixR = ".rar"; String
	 * suffixZ = ".zip"; if(fileName.endsWith(suffixR) ||
	 * fileName.endsWith(suffixZ)){ System.out.println("DL" + "Rar||Zip Attach"
	 * ); return; } BodyPart bp2 = new MimeBodyPart(); DataSource dataSource =
	 * new FileDataSource(storefile); //System.out.println("DL" +storefile);
	 * DataHandler dataHandler = new DataHandler(dataSource);
	 * bp2.setDataHandler(dataHandler); bp2.setFileName(fileName);
	 *
	 * //multipart = new MimeMultipart(); //multipart.addBodyPart(bp1);
	 * multipart.addBodyPart(bp2); }
	 */
	private void unCompress(String fileName, File storefile, String storedir) {
		String suffixR = ".rar";
		String suffixZ = ".zip";
		int countRar = 0;
		int countZip = 0;
		if (fileName.endsWith(suffixR)) {
			System.out.println("rar:" + fileName);
			setHasRar(++countRar);
			// bean.unRarFile(fileName,storefile.toString(), storedir); //解压rar
			try {
				bean.unRarOrZipFile(storefile.toString(), storedir);// 既可以解压rar
																	// 也可以解压zip
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} // 解压rar
			setHasRar(--countRar);

		} else if ((fileName.endsWith(suffixZ))) {
			System.out.println("zip:" + fileName);
			try {
				// bean.unzip(storefile.toString(), storedir); //解压zip
				bean.unRarOrZipFile(storefile.toString(), storedir);
			} catch (ZipException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			++countZip;
			setHasZip(countZip);
		} else {
			System.out.println("non-compress:" + fileName);
			return;
		}
	}

	private void addBodyPart(String RARPath, String FileName, Multipart multipart) {
		BASE64Encoder enc = new BASE64Encoder();
		BodyPart bp2 = new MimeBodyPart();
		DataSource dataSource = new FileDataSource(RARPath);
		DataHandler dataHandler = new DataHandler(dataSource);
		// dataHandler.getName()
		try {
			bp2.setDataHandler(dataHandler);
			String s = enc.encode((dataSource.getName()).getBytes());
			// System.out.println("encode:" + s);
			bp2.setFileName("=?UTF-8?B?" + s + "?=");
			// bp2.setFileName(FileName);
			// bp2.setFileName(dataSource.getName());

			multipart.addBodyPart(bp2);
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// public void createRarAttach(File srcDir, String drczip) {
	public void createRarAttach(File file, Multipart multipart) { // file
																	// c:\\tmp\\symbols
		// reStoredir = C:\tmp\symbols\pdb2\4609110
		// String FileName = file.getName();
		String FileName = "";
		String RARPath = "";
		String f3Path = "";
		try {
			for (File f : file.listFiles()) {// c:\\tmp\\symbols目录下所有文件夹和文件(第一级目录
												// 不递归)
				// C:\tmp\symbols\ zhangsan\ pdb2\4609110\xxxx

				/*
				 * 假设附件名为pdb2.rar
				 *
				 * file  c:\\tmp\\symbols
				 * f C:\tmp\symbols\\zhangsan
				 * f1 C:\tmp\symbols\\zhangsan\pdb2
				 * f2 C:\tmp\symbols\\zhangsan\pdb2\4609110				 * f3 C:\tmp\symbols\\zhangsan\pdb2\4609110\pdb2
				 * */

				System.out.println("file.listFiles() :" + f.getName());
				f3Path = "";
				// 因为在之前invokepdb时 上传的同时把pdb删除了
				// 但是这个file还是能探测到pdb,这里不做处理,算是跳过bug吧
				if (f.getName().endsWith(".pdb"))
					continue;
				if (f.isDirectory()) {// C:\tmp\symbols\\zhangsan    \pdb2 \4609110\pdb2\\...

					for (File f1 : f.listFiles()) {// C:\tmp\symbols\\zhangsan    \pdb2// 自注:因为邮件只能发压缩包和文件 如果为目录,说明是解压过后的文件夹
					for (File f2 : f1.listFiles()) {// f.listFiles() // C:\tmp\symbols\pdb2\4609110
						if (f2.isDirectory()) { // C:\tmp\symbols\pdb2\4609110							String[] files = f2.list();
							if (files.length == 0) { // 排除情况3
								System.out.println("目录 " + f2.getPath() + " 为空!" + "情况3");
								break;
							}
							for (File f3 : f2.listFiles()) // 情况1C:\tmp\symbols\pdb2\4609110\pdb2
															// 情况2或C:\tmp\symbols\pdb2\4609110\1.txt
															// 情况3或C:\tmp\symbols\pdb2\4609110\空(原来是pdb被上传了)
							{
								if (f3.isDirectory()) {
									RARPath = f3.getAbsolutePath() + ".rar";
									f3Path = f3.getAbsolutePath();
									System.out.println("情况1RARPath:" + RARPath);
									for(File f4 : f3.listFiles())
										System.out.println(f4);
									bean.RarFile(RARPath, f3Path);    //压缩
									FileName = f1.getName() + ".rar";
									addBodyPart(RARPath, FileName, multipart);
								} else if (f3.isFile()) {// 排除情况2
									String Name = f3.getName();
									System.out.println("情况2:" + Name);
									if (Name.endsWith(".pdb"))
										continue;
									addBodyPart(f3.getAbsolutePath(), Name, multipart);
								}
							}
						}
					}
					//
					// bean.RarFile(RARPath, f3Path);
					// FileName = f.getName() + ".rar";
					// //System.out.println("createRarAttachName:" + FileName);
					// addBodyPart(RARPath, FileName, multipart);
					}
				} else if (f.getName().endsWith(".tar") == false && f.getName().endsWith(".zip") == false) {
					FileName = f.getName();
					System.out.println("createRarAttachName:" + FileName);
					addBodyPart(f.getAbsolutePath(), FileName, multipart);
				} else {
					System.out.println("ElsehName:" + FileName);
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// BodyPart bp2 = new MimeBodyPart();
		// DataSource dataSource = new FileDataSource(RARPath);
		// // System.out.println("DL" +storefile);
		// DataHandler dataHandler = new DataHandler(dataSource);
		// bp2.setDataHandler(dataHandler);
		// bp2.setFileName(RARPath);
		// multipart.addBodyPart(bp2);

	}

	public void forwardmail(PraseMimeMessage pmessage, Message message, Multipart multipart) throws Exception {

//		Transport transport = MyDataGenerator.session.getTransport("25");
//
//		transport.connect(MyDataGenerator.mailConfig.getProperty("smtp.hikvision.com.cn"),
//				MyDataGenerator.mailConfig.getProperty("authUser"),
//				MyDataGenerator.mailConfig.getProperty("authPassword"));
		System.out.println("forwardmail");
		Properties prop2 = new Properties();
		//prop2.put("mail.smtp.host", "smtp.hikvision.com.cn");
		prop2.setProperty("mail.store.protocol", "smtp");
		prop2.setProperty("mail.smtp.host", "smtp.hikvision.com.cn");
		prop2.setProperty("mail.smtp.port", "25");
		prop2.put("mail.smtp.auth", "true");
	        Session session2 = Session.getInstance(prop2, new Authenticator(){
	            protected PasswordAuthentication getPasswordAuthentication() {
	                return new PasswordAuthentication("你的邮箱的用户名 别直接拷", "<pre name="code" class="java">你的邮箱的密码 别直接拷

"); }});//Session session2 = Session.getDefaultInstance(prop2, null);BodyPart bp1 = new MimeBodyPart();pmessage.getMailContent(message);bp1.setText(pmessage.getBodyText());try{multipart.addBodyPart(bp1);}catch(IllegalWriteException
e){e.printStackTrace();}catch(MessagingException e){e.printStackTrace();}catch(Exception e){e.printStackTrace();}//System.out.println("DL" + pmessage.getBodyText());Message forward = new MimeMessage(session2);forward.setSubject(pmessage.getSubject());forward.setFrom(new
InternetAddress(pmessage.getFrom()));forward.addRecipient(Message.RecipientType.TO, new InternetAddress(pmessage.getMailAddress("to")));//System.out.println("DL"+ pmessage.getSubject() + pmessage.getFrom()+ pmessage.getMailAddress("to"));forward.setContent(multipart);
// ...forward.saveChanges();try {Transport.send(forward);multipart = null;} catch(SendFailedException e){e.printStackTrace();}catch (MessagingException e) {e.printStackTrace();}}public void replyMail(PraseMimeMessage pmm, Message message) throws Exception
{ System.out.println("replyMail");Properties prop3 = new Properties();//prop2.put("mail.smtp.host", "smtp.hikvision.com.cn");prop3.setProperty("mail.store.protocol", "smtp"); prop3.setProperty("mail.smtp.host", "smtp.hikvision.com.cn"); prop3.setProperty("mail.smtp.port",
"25");prop3.put("mail.smtp.auth", "true"); Session session3 = Session.getInstance(prop3, new Authenticator(){ protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("

你的邮箱的用户名 别直接拷

", "

你的邮箱的密码 别直接拷

"); }});// MimeMessage
reply;// try {// reply = (MimeMessage)message.reply(true);// try {// reply.setFrom(new InternetAddress(pmm.getFrom()));// reply.setText("Thanks, Your Email has bean processed.");// Transport.send(reply);// } catch (Exception e) {// // TODO Auto-generated catch
block// e.printStackTrace();// }// } catch (MessagingException e) {// // TODO Auto-generated catch block// e.printStackTrace();// } String sendFrom = MyDataGenerator.mailConfig.getProperty("authUser") + "@hikvision.com.cn"; MimeMessage msg = (MimeMessage)
message.reply(false); msg.setFrom(new InternetAddress(sendFrom)); msg.setRecipients(RecipientType.TO, pmm.getFrom()); Multipart mp = new MimeMultipart(); MimeBodyPart mbp = new MimeBodyPart(); mbp.setContent("<meta http-equiv=Content-Type content=text/html;
charset=GBK>"+ "您好,您的邮件已经收到,谢谢!", "text/html;charset=gb2312"); mp.addBodyPart(mbp); msg.setContent(mp); msg.setSentDate(new Date()); msg.saveChanges(); Transport trans = session3.getTransport("smtp"); //trans.connect("smtp.hikvision.com.cn", "dingliang", "Dl123456");
trans.connect(MyDataGenerator.mailConfig.getProperty("server"),MyDataGenerator.mailConfig.getProperty("authUser"),MyDataGenerator.mailConfig.getProperty("authPassword")); trans.sendMessage(msg, msg.getAllRecipients()); trans.close(); } /** * PraseMimeMessage
*/// public static void main(String args[]) throws Exception {// public void Mymain() throws Exception {// String host = "10.1.11.124";// String username = "*******";// String password = "*******";// Properties props = new Properties();// Session session =
Session.getDefaultInstance(props, null);// Store store = session.getStore("pop3");// store.connect(host, username, password);// Folder folder = store.getFolder("INBOX");// folder.open(Folder.READ_ONLY);// Message message[] = folder.getMessages();// System.out.println("Messages‘s
length: " + message.length);// PraseMimeMessage pmm = null;// for (int i = 0; i < message.length; i++) {// pmm = new PraseMimeMessage((MimeMessage) message[i]);// System.out.println("Message " + i + " subject: " + pmm.getSubject());// //System.out.println("Message
" + i + " sentdate: " + pmm.getSentDate());// //System.out.println("Message " + i + " replysign: " +// pmm.getReplySign());// //System.out.println("Message " + i + " hasRead: " + pmm.isNew());// System.out.println("Message " + i + " containAttachment: " +//
pmm.isContainAttach((Part) message[i]));// System.out.println("Message " + i + " form: " + pmm.getFrom());// System.out.println("Message " + i + " to: " + pmm.getMailAddress("to"));// //System.out.println("Message " + i + " cc: " +// pmm.getMailAddress("cc"));//
//System.out.println("Message " + i + " bcc: " +// pmm.getMailAddress("bcc"));// //pmm.setDateFormat("yy??MM??dd?? HH:mm");// //System.out.println("Message " + i + " sentdate: " + pmm.getSentDate());// //System.out.println("Message " + i + " Message-ID: "
+// pmm.getMessageId());// //pmm.getMailContent((Part) message[i]);// //System.out.println("Message " + i + " bodycontent: \r\n" +// pmm.getBodyText());//// File file = new File("c:\\tmp\\symbols");// if (!file.exists()) {// file.mkdirs();// }// pmm.setAttachPath(file.toString());//
pmm.saveAttachMent((Part) message[i]);// pmm.invokeBatStorePdb((Part) message[i]);// }// }}


package receiveMail;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class MyDataGenerator extends SchedThread {
	static Store store;
	static Folder folder;
	static Session session;
	static String host, username, password;
	static Properties mailConfig;

	private static ThreadPool<MailHandler> threadPool; //= new DefaultThreadPool<MailHandler>(11);
	private static ArrayBlockingQueue<Message> MailQueue; //= new ArrayBlockingQueue<Message>(100, false);

	public MyDataGenerator(){
		threadPool = new DefaultThreadPool<MailHandler>(11);
		MailQueue = new ArrayBlockingQueue<Message>(100, false);

	}

	protected void executeWork() throws Exception {
		System.out.println("Execute work ...");
		System.out.println("currentThread Name: "+ Thread.currentThread().getName());
		// String host = "10.1.11.124";
		// String username = "dingliang";
		// String password = "Dl123456";
		// Properties props = new Properties();
		// Session session = Session.getDefaultInstance(props, null);
		// Store store = session.getStore("pop3");

		store = session.getStore("pop3");
		// store.connect(host, username, password);
		// System.out.println(mailConfig.getProperty("server")
		// +mailConfig.getProperty("authUser") +
		// mailConfig.getProperty("authPassword"));
		store.connect(mailConfig.getProperty("server"), mailConfig.getProperty("authUser"),
				mailConfig.getProperty("authPassword"));
		// Connection conn = pool.getConnection();
		Folder folder = store.getFolder("INBOX");
		// folder.open(Folder.READ_ONLY);
		folder.open(Folder.READ_WRITE);
		Message message[] = folder.getMessages();
		System.out.println("Messages's length: " + message.length);
		PraseMimeMessage pmm = null;
		for (int i = 0; i < message.length; i++) {
			pmm = new PraseMimeMessage((MimeMessage) message[i]);
			System.out.println("Message " + i+" subject: " + pmm.getSubject());
			System.out.println("Message " + i+ "  containAttachment: " + pmm.isContainAttach((Part) message[i]));
			System.out.println("Message " + i+ " form: " + pmm.getFrom());
			System.out.println("Message " + i + " to: " + pmm.getMailAddress("to"));
			MailQueue.offer(message[i]);
			System.out.println("message" + i + "offer");
//			for(Message m : MailQueue)
//				System.out.println(m);
			//processMail();
			message[i].setFlag(Flags.Flag.DELETED, true);
		}
		try {
//			for(Message m : MailQueue)
//				System.out.println(m);
			folder.close(true);
			store.close();
			System.out.println("folder.close");
		} catch (MessagingException e) {
			System.out.println("delete problem");
		}
		//store.close();

	}

	protected void executeWork2() throws Exception {
		System.out.println("processMailing ......" );
		processMail();
	}
	protected long getNextTime() {
		return System.currentTimeMillis() + 10000L;
	}
	protected long getNextProcessTime() {
		return System.currentTimeMillis() + 5000L;
	}

	private static Properties getProp() throws IOException {
		//
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		InputStream inputStream = classLoader.getResourceAsStream("mailConfig.properties");
		Properties prop = new Properties();
		prop.load(inputStream);
		return prop;

	}
	private static void processMail(){
		//while(true){
			try {
				Message message = MailQueue.poll(2, TimeUnit.SECONDS);
				System.out.println("poll message: "+message);
				if(message == null)
					return;
				PraseMimeMessage pmm = new PraseMimeMessage((MimeMessage) message);
				threadPool.execute(new MailHandler(message, pmm));
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	//}

	public static void main(String argv[]) {
		try {
			mailConfig = getProp();// mailConfig.properties
		} catch (IOException e) {
			e.printStackTrace();
		}
		Properties props = new Properties();
		session = Session.getDefaultInstance(props, null);

		// pool = ConnectionPool.getInstance();

		MyDataGenerator generator = new MyDataGenerator();

		generator.start();

//		while(true){
//			processMail();
//		}

	}
}
package receiveMail;

import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;

/**
 * 基于Java线程实现后台定时监控
 */
public abstract class SchedThread {
	protected static final long NEVER = Long.MAX_VALUE;
	// 定义一个线程锁,保证当前只有一个工作在操作中
	private final Object lock = new Object();
	// 定义一个Thread变量
	private Thread thread, thread2;  //jia
	// 控制线程循环的开关
	private boolean active = true;
	// 定义一个毫秒级的时间变量,指示何时执行下一个操作
	private long nextTime;

	/**
	 * 定义个一个抽象的方法用来获取下一个执行操作的时间,可使用NEVER
	 */
	protected abstract long getNextTime();
	protected abstract long getNextProcessTime();
	/**
	 * 定义一个抽象的方法,让子类来定义具体的工作过程
	 * @throws NoSuchProviderException
	 */
	//protected abstract void executeWork();
	protected abstract void executeWork() throws Exception;
	protected abstract void executeWork2() throws Exception;

	protected String getName() {
		return getClass().getName();
	}

	/**
	 * 启动线程
	 */
	public void start() {
		thread = new Thread(new Runnable() {//用来取邮件 并offer到阻塞队列中
			public void run() {
				runInternal();
			}
		}, getName());
		System.out.println("offer Thread start: "+ thread.getName());
		thread.start();

		thread2 = new Thread(new Runnable() {  //用来processMail  jia
			public void run() {
				runInternal2();
			}
		}, getName());
		System.out.println("process Thread start: "+ thread2.getName());
		thread2.start();

	}

	/**
	 * 强迫停止线程,跳出for循环
	 */
	public void stop() throws InterruptedException {
		synchronized (lock) {
			active = false;
			lock.notify();
		}
		thread.join();
	}

	/**
	 * 此方法可以在任何时候激活当前线程,让线程进入工作执行环节
	 */
	public void workAdded(long time) {
		synchronized (lock) {
			if (time < nextTime) {
				// 立刻激活线程工作继续运行
				lock.notify();
			}
		}
	}
	private void runInternal2() {  //1
		for(;;){
			// 执行具体的工作
			try {
				synchronized (lock) {
					nextTime = getNextProcessTime();  //2
					// 获得时间区间,即要等待的时间段
					long interval = nextTime - System.currentTimeMillis();
					if (interval > 0) {
						try {
							lock.wait(interval);
						} catch (InterruptedException e) {
							// 忽略此Exception
						}
					}
					// 如果active为false,强制中断
					if (!active) {
						break;
					}
				}
				executeWork2();  //3
			} catch (Exception e) {
				e.printStackTrace();
				try {
					Thread.sleep(10000);
				} catch (InterruptedException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				e.printStackTrace();
			}
		}

	}
	/**
	 * 线程监测控制逻辑部分
	 */
	private void runInternal() { //1
		// 无限循环
		for (;;) {
			// 该过程忽略了所有的Exception,以保证线程不会因此而中断
			try {
				synchronized (lock) {
					nextTime = getNextTime();  //2
					// 获得时间区间,即要等待的时间段
					long interval = nextTime - System.currentTimeMillis();
					if (interval > 0) {
						try {
							lock.wait(interval);
						} catch (InterruptedException e) {
							// 忽略此Exception
						}
					}
					// 如果active为false,强制中断
					if (!active) {
						break;
					}
				}
				// 执行具体的工作
				executeWork();//3
			} catch (Throwable t) {
				try {
					System.out.println("Throwable t");
					t.printStackTrace();
					Thread.sleep(10000);
					try {
						if(MyDataGenerator.folder !=null){
							MyDataGenerator.folder.close(true);
						}
						MyDataGenerator.store.close();
					} catch (MessagingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} catch (InterruptedException ie) {
					// 忽略此Exception
					System.out.println("InterruptedException ie");
				}
			}
		}
	}
}
package receiveMail;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.zip.ZipException;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;

import com.github.junrar.Archive;
import com.github.junrar.rarfile.FileHeader;
import com.sun.org.apache.xerces.internal.util.SynchronizedSymbolTable;   

public class CompressZIP {
    private static CompressZIP instance = new CompressZIP();
    private static int count = 0;

    public static int getCount() {
		return count;
	}

	public static void setCount(int count) {
		CompressZIP.count = count;
	}

	private CompressZIP() {
    }   

    public static CompressZIP getInstance() {
        return instance;
    }   

    public synchronized void zip(String inputFilename, String zipFilename)
            throws IOException {
        zip(new File(inputFilename), zipFilename);
    }   

    public synchronized void zip(File inputFile, String zipFilename) throws IOException {
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
                zipFilename));   

        try {
            zip(inputFile, out, "");
        } catch (IOException e) {
            throw e;
        } finally {
            out.close();
        }
    }
   //???zip
    private synchronized void zip(File inputFile, ZipOutputStream out, String base)
            throws IOException {
        if (inputFile.isDirectory()) {
            File[] inputFiles = inputFile.listFiles();
            out.putNextEntry(new ZipEntry(base + "/"));
            base = base.length() == 0 ? "" : base + "/";
            for (int i = 0; i < inputFiles.length; i++) {
                zip(inputFiles[i], out, base + inputFiles[i].getName());
            }   

        } else {
            if (base.length() > 0) {
                out.putNextEntry(new ZipEntry(base));
            } else {
                out.putNextEntry(new ZipEntry(inputFile.getName()));
            }   

            FileInputStream in = new FileInputStream(inputFile);
            try {
                int c;
                byte[] by = new byte[BUFFEREDSIZE];
                while ((c = in.read(by)) != -1) {
                    out.write(by, 0, c);
                }
            } catch (IOException e) {
                throw e;
            } finally {
                in.close();
            }
        }
    }   

    //???zip
    public synchronized void unzip(String zipFilename, String outputDirectory) throws ZipException, IOException
             {   //throws IOException
    	 if (!zipFilename.toLowerCase().endsWith(".zip")) {
    	        System.out.println("rar");
    	        return;
    	    }
        File outFile = new File(outputDirectory);
        if (!outFile.exists()) {
            outFile.mkdirs();
        }
        ZipFile zipFile = null;
        try{
        	  zipFile = new ZipFile(zipFilename,"UTF-8");    //??Q???āy?a
            }catch(IOException e){
            	e.printStackTrace();
            }
       // ZipFile zipFile = new ZipFile(zipFilename,"gbk");
        Enumeration en = zipFile.getEntries();
        ZipEntry zipEntry = null;
        while (en.hasMoreElements()) {
            zipEntry = (ZipEntry) en.nextElement();
            if (zipEntry.isDirectory()) {
                // mkdir directory
                String dirName = zipEntry.getName();
                dirName = dirName.substring(0, dirName.length() - 1);   

                File f = new File(outFile.getPath() + File.separator + dirName);
                f.mkdirs();   

            } else {
                // unzip file
                File f = new File(outFile.getPath() + File.separator
                        + zipEntry.getName());
                try{
                	if(f.getParent()!=null && !new File(f.getParent()).exists()){  //createNewFile
                	    new File(f.getParent()).mkdirs();
                	}
                	f.createNewFile(); 

                }catch(IOException e){
                	e.printStackTrace();
                }
                InputStream in = zipFile.getInputStream(zipEntry);
                FileOutputStream out = new FileOutputStream(f);
                try {
                    int c;
                    byte[] by = new byte[BUFFEREDSIZE];
                    while ((c = in.read(by)) != -1) {
                        out.write(by, 0, c);
                    }
                    // out.flush();
                } catch (IOException e) {
                    throw e;
                } finally {
                    out.close();
                    in.close();
                    System.out.println("unzip stream close");
                }
            }
        }
        zipFile.close();  //!!不然.zip文件一直是占用状态 删不掉
        System.out.println("zipFile.close();");
    }
    //rar
	public synchronized void RarFile( String RARRealpath, String fileName) throws IOException {
		//String command = "cmd.exe /C start /b C:\\symstore-del.bat c:\\tmp\\symbols";
		//String RARCMD = "C:\\Program Files\\WinRAR\\Rar.exe a -r -ep1";
		String RARCMD = "C:\\Progra~1\\WinRAR\\Rar.exe a -r -x*.pdb -ep1";
		// RARFile("d:\\download.rar","d:\\?????2");
		if (fileName == null) {
			return;
		}
		fileName = fileName.trim();

		if (fileName.equals("")) {
			return;
		}
		//String command = "cmd.exe /C"+ " start /b C:\\rar.bat" + RARRealpath + fileName;
		//String command1 = "Rar.exe a -r -ep1 c:\\bbb.rar c:\\bb";
		String command = RARCMD + " " + RARRealpath + " " + fileName;   //??????û??????? rar.exe??в??  ???rar.exe???c://windows·????
		System.out.println("rar command: "+command);
		Runtime rt = Runtime.getRuntime();
		Process p = null;
		try {
			p = rt.exec(command);

		BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream(), "UTF-8")); // gbk
		String line;
		while ((line = br.readLine()) != null) {
			// System.out.println(line);
		}

		br = new BufferedReader(new InputStreamReader(p.getErrorStream(), "UTF-8")); // gbk
		while ((line = br.readLine()) != null) {
			// System.err.println(line);
		}
		//
		try {
			if(p.waitFor() !=0){
				System.err.println("exit value = " + p.exitValue());
			}
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

			p.destroy();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			p.getErrorStream().close();
			p.getInputStream().close();
			p.getOutputStream().close();
			e.printStackTrace();
		}

	}
	//用winrar.exe解压 可以解压rar或者zip 要把winrar.exe放到c:\Windows下(注:unrar只能解压.rar)
	public synchronized void unRarOrZipFile( String RARRealpath, String fileName) throws IOException{  //fileName 即是storedir
		//unrar x C:\\pdb.rar C:\\temp\\symbol
		String subFileName = fileName;
		//String RARCMD = "winrar.exe x -o+";   //unrar.exe x
		String RARCMD = "C:\\Progra~1\\WinRAR\\winrar.exe x -o+";
		if (fileName == null) {
			return;
		}
		fileName = fileName.trim();

		if (fileName.equals("")) {
			return;
		}
		if(RARRealpath.endsWith(".rar") || RARRealpath.endsWith(".zip") ){
			String rarName = new File(RARRealpath).getName();
			int index = rarName.lastIndexOf(".");
			subFileName  = rarName.substring(0, index);

		}
		String cmdfileName;
		if(count++ == 0){   //每封邮件只执行一次 加一层文件夹 防止一个压缩包下都是文件 而不是一个文件夹
			 cmdfileName = fileName + File.separator + subFileName;
			 System.out.println("count1: " + count);
		}
		else{
			 cmdfileName = fileName;
			 System.out.println("count2: " + count);
		}

		System.out.println("unFile cmdfileName: " + cmdfileName);

		File dstDiretory = new File(cmdfileName);
		//String command = RARCMD + " " + RARRealpath + " " + fileName;
		String command = RARCMD + " " + RARRealpath + " " + cmdfileName;

		if (!dstDiretory.exists()) {
			dstDiretory.mkdirs();
		}
		Runtime rt = Runtime.getRuntime();
		Process p = null;
		try {
			p = rt.exec(command);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream(), "UTF-8")); // gbk
		String line;
		while ((line = br.readLine()) != null) {
			// System.out.println(line);
		}

		br = new BufferedReader(new InputStreamReader(p.getErrorStream(), "UTF-8")); // gbk
		while ((line = br.readLine()) != null) {
			// System.err.println(line);
		}
		//
		try {
			if(p.waitFor() !=0)
				System.err.println("exit value = " + p.exitValue());			

		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		p.destroy();
	}
	//解压rar
	public synchronized void unRarFile2(String fileName, String srcRarPath, String dstDirectoryPath) {
		// 外部调用 如bbb.rar c:\\tmp\\symbols\\bbb.rar c:\\tmp\\symbols或c:\\tmp
		if (!srcRarPath.toLowerCase().endsWith(".rar")) {
			System.out.println("rar");
			return;
		}

		int index1;
		String rarName = null;
		if ((index1 = fileName.lastIndexOf(".")) != -1) {// 获取压缩包xxx.rar的文件名xxx
			rarName = fileName.substring(0, index1);
		}

		 //File dstDiretory = new File(dstDirectoryPath);
		File dstDiretory = new File(dstDirectoryPath + File.separator + rarName); // c:\\tmp\\symbols\\bbb
		if (!dstDiretory.exists()) {
			dstDiretory.mkdirs();
		}
		Archive a = null;
		try {
			a = new Archive(new File(srcRarPath));
			if (a != null) {
				a.getMainHeader().print(); //
				FileHeader fh = a.nextFileHeader();
				while (fh != null) {
					String entrypath = "";
					if (fh.isUnicode()) { // jiejue zhongwenluanma [email protected][email protected]!
						entrypath = fh.getFileNameW().trim();
						System.out.println("entrypath1: " + entrypath);
					} else {
						entrypath = fh.getFileNameString().trim();
						System.out.println("entrypath2: " + entrypath);
					}

					int index;
					if ((index = entrypath.indexOf("\\")) != -1) {
						String entrypathName = entrypath.substring(0, index);
						if (rarName.equals(entrypathName)) {
							//System.out.println("rarName + entrypathName: " + rarName + " " + entrypathName);
							entrypath = entrypath.substring(index+1);
							//System.out.println("entrypath: " + entrypath);
						}
					}
					if (fh.isDirectory()) {
						//File fol = new File(dstDirectoryPath + File.separator + entrypath);
						 File fol = new File(dstDiretory.toString() + File.separator+ entrypath);
						fol.mkdirs();
					} else {
						//File out = new File(dstDirectoryPath + File.separator + entrypath);
						 File out = new File(dstDiretory.toString() + File.separator+ entrypath);
						try {//
							if (!out.exists()) {
								if (!out.getParentFile().exists()) {//
									out.getParentFile().mkdirs();
								}
								//System.out.println("out: " + out);
								out.createNewFile();
							}
							FileOutputStream os = new FileOutputStream(out);
							a.extractFile(fh, os);
							os.close();
						} catch (Exception ex) {
							ex.printStackTrace();
						}
					}
					fh = a.nextFileHeader();
				}
				a.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

    private static final int BUFFEREDSIZE = 1024;   

    public static void main(String[] args) {
    	CompressZIP bean = new CompressZIP();
//        try {
//            //bean.zip("c:/mysymbol-(3)", "c:/b.zip");
//
//              try {
//				bean.unzip("c:\\tmp\\symbols\\b.zip", "c:\\tmp\\symbols");
//			} catch (ZipException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
        	try {
				//bean.unRarFile("C:\\pdb2.rar", "C:\\temp");
        		bean.unRarOrZipFile("C:\\pdb2.rar", "C:\\temp");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
//        	new File("c:\\bbb.rar").delete();
//        	try {
//				bean.RarFile( "c:\\bbb.rar", "c:\\bbb");
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}   //·

//
//        	//bean.RarFile("c:\\bbb.rar", "c:\\mysymbol-(4)");   //
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
       // bean.unRarFile("temp.txt","c:\\bbb.rar", "c:\\a");
    }
}
package receiveMail;

import java.io.File;

import javax.mail.Flags;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class MailHandler implements Runnable {

	Message message;
	PraseMimeMessage pmm;
	//int messageID;
	public MailHandler(Message message,PraseMimeMessage pmm ){
		this.message = message;
		this.pmm = pmm;
	}

	@Override
	public void run() {
		Thread current = Thread.currentThread();
		System.out.println("Thread Name: " + current.getName());
//		try {
//			System.out.println("isContainAttach: " + pmm.isContainAttach((Part) message));
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}

		long start = System.currentTimeMillis();
		CompressZIP.setCount(0);// 在解压时unRarOrZipFile时, 只在count==0时执行一次
								// 创建与.rar同名的文件夹 然后count++

		Multipart multipart = new MimeMultipart(); // 每一封邮件一份 用来存放附件
													// createRarAttach()
													// forwardmail()
		// pmm.clearDir(new File("c:\\tmp\\symbols"));

		pmm = new PraseMimeMessage((MimeMessage) message);
		try {
			boolean IsHasAttach = pmm.isContainAttach((Part) message);
			if (IsHasAttach) { //如果有附件

				File file = new File("c:\\tmp\\symbols");
				if (!file.exists()) {
					file.mkdirs();
				}
				pmm.setHasPdb(0);
				String senderFrom = pmm.getFrom();
				int beginIndex, endIndex;
				if ((beginIndex = senderFrom.indexOf("<")) != -1 && (endIndex = senderFrom.indexOf("@")) != -1) {
					senderFrom = senderFrom.substring(beginIndex + 1, endIndex);
					System.out.println(" senderFrom: " + senderFrom);
				}
				pmm.setAttachPath(file.toString());
				pmm.saveAttachMent((Part) message, pmm, senderFrom); // 包括保存附件到本地																		// 和 解压
				pmm.invokeBatStorePdb(senderFrom);
				pmm.createRarAttach(file, multipart);
				if (pmm.getMailAddress("to") != null && !pmm.getMailAddress("to").isEmpty()) {
					pmm.forwardmail(pmm, message, multipart);
				}
				//message.setFlag(Flags.Flag.DELETED, true); //
				System.out.println("Flag.DELETED");
				pmm.clearDir(new File("c:\\tmp\\symbols"));
				pmm.replyMail(pmm, message); // 回复邮件
					} //如果有附件
				//pmm.replyMail(pmm, message); // 回复邮件
			}catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
			long end = System.currentTimeMillis();
			System.out.println("last time of one email is : " + (end - start));	

	}

}
package receiveMail;

/**
 * 6-19
 */
public interface ThreadPool<Job extends Runnable> {
    // ??????Job?????Job??????Runnable
    void execute(Job job);

    // ???????
    void shutdown();

    // ????????????
    void addWorkers(int num);

    // ????????????
    void removeWorker(int num);

    // ?õ?????????е?????????
    int getJobSize();
}
package receiveMail;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 6-20
 */
public class DefaultThreadPool<Job extends Runnable> implements ThreadPool<Job> {
    // ?????????????
    private static final int      MAX_WORKER_NUMBERS     = 10;
    // ????????????
    private static final int      DEFAULT_WORKER_NUMBERS = 5;
    // ??????С??????
    private static final int      MIN_WORKER_NUMBERS     = 1;
    // ????????????б????????????????
    private final LinkedList<Job> jobs                   = new LinkedList<Job>();
    // ???????б?
    private final List<Worker>    workers                = Collections.synchronizedList(new ArrayList<Worker>());
    // ??????????????
    private int                   workerNum              = DEFAULT_WORKER_NUMBERS;
    // ?????????
    private AtomicLong            threadNum              = new AtomicLong();

    public DefaultThreadPool() {
        initializeWokers(DEFAULT_WORKER_NUMBERS);
    }

    public DefaultThreadPool(int num) {
        workerNum = num > MAX_WORKER_NUMBERS ? MAX_WORKER_NUMBERS : num < MIN_WORKER_NUMBERS ? MIN_WORKER_NUMBERS : num;
        initializeWokers(workerNum);
    }

    public void execute(Job job) {
        if (job != null) {
            // ????????????????????
            synchronized (jobs) {
                jobs.addLast(job);
                jobs.notify();
            }
        }
    }

    public void shutdown() {
        for (Worker worker : workers) {
            worker.shutdown();
        }
    }

    public void addWorkers(int num) {
        synchronized (jobs) {
            // ??????????Worker???????????????
            if (num + this.workerNum > MAX_WORKER_NUMBERS) {
                num = MAX_WORKER_NUMBERS - this.workerNum;
            }
            initializeWokers(num);
            this.workerNum += num;
        }
    }

    public void removeWorker(int num) {
        synchronized (jobs) {
            if (num >= this.workerNum) {
                throw new IllegalArgumentException("beyond workNum");
            }
            // ???????????????Worker
            int count = 0;
            while (count < num) {
                workers.get(count).shutdown();
                count++;
            }
            this.workerNum -= count;
        }
    }

    public int getJobSize() {
        return jobs.size();
    }

    // ?????????????
    private void initializeWokers(int num) {
        for (int i = 0; i < num; i++) {
            Worker worker = new Worker();
            workers.add(worker);
            Thread thread = new Thread(worker, "ThreadPool-Worker-" + threadNum.incrementAndGet());
            thread.start();
        }
    }

    // ???????????????????
    class Worker implements Runnable {
        // ?????
        private volatile boolean running = true;

        public void run() {
            while (running) {
                Job job = null;
                synchronized (jobs) {
                    // ??????????б????????ô??wait
                    while (jobs.isEmpty()) {
                        try {
                            jobs.wait();
                        } catch (InterruptedException ex) {
                            // ?????????WorkerThread???ж??????????
                            Thread.currentThread().interrupt();
                            return;
                        }
                    }
                    // ??????Job
                    job = jobs.removeFirst();
                }
                if (job != null) {
                    try {
                        job.run();
                    } catch (Exception ex) {
                        // ????Job????е?Exception
                    }
                }
            }
        }

        public void shutdown() {
            running = false;
        }
    }
}
//mailConfig.properties
server = *****
authUser = *****
authPassword = *****
时间: 2024-10-14 12:27:11

自己写的java邮件客户端的相关文章

java邮件客户端

/*** *邮件VO **/package net.jk.util.email.vo; import java.util.Date; import java.util.List; import net.jk.app.model.App_emailfile; public class App_email { private String title; // 主题 private String fromaddr; // 发件人 private String toaddr; // 收件人 privat

基于JAVA的邮件客户端的设计和实现

获取项目源文件,技术交流与指导联系Q:1225467431 摘  要 Java是Sun Microsystem公司推出的新一代面向对象和面向网络的程序设计语言,特别适合于Internet/Intranet上的应用软件开发,因此也把Java语言称为新一代网络程序设计语言.Java语言将面向对象.多线程.安全和网络等特征集于一身,为软件开发人员提供了很好的程序设计环境,当今企业级计算和应用中相当成熟和稳定的平台,在这个领域中不可否认地占据着领导地位.JBuilder是Borland公司推出的Java

Java邮件发送与屏幕截屏

前几天七夕情人节孤独寂寞的程序猿闲来没事,花了一两个小时写了个小Demo主要实现Java的Mail发送功能和桌面截屏功能. 首先让我们先看看Java sendMail邮件发送和桌面屏幕截屏功能是怎么实现的基础知识. 一.Java  SendMail邮件发送 首先让我们来看看邮件发送的原理图: JavaMail 是一套sun 提供开发邮件收发程序API,JavaMail编写程序就是邮件客户端程序(和outlook.foxmail功能类似) * JavaMail开发需要类库 javamail API

JavaMail(JAVA邮件服务) API详解

一.JavaMail API简介JavaMail API是读取.撰写.发送电子信息的可选包.我们可用它来建立如Eudora.Foxmail.MS Outlook Express一般的邮件用户代理程序(Mail User Agent,简称MUA).而不是像sendmail或者其它的邮件传输代理(Mail Transfer Agent,简称MTA)程序那样可以传送.递送.转发邮件.从另外一个角度来看,我们这些电子邮件用户日常用MUA程序来读写邮件,而MUA依赖着MTA处理邮件的递送.在清楚了到MUA

java实现客户端向服务器发送文件的操作

服务器源代码: import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.ServerSocket;

Java邮件服务学习之一:邮件服务概述

java可以提供邮件服务:一般理解的邮件服务就是可以发送和接收邮件的客户端,但是使用java编写邮件服务端: 一.邮件客户端: web应用根据依赖的API,常用的有两种: 第一种:J2EE中提供的java mail API(javax.mail.*) Javamail API是一个用于阅读.编写和发送电子消息的可选包(标准扩展),可以用来建立基于标准的电子邮件客户机,它支持各种因特网邮件协议,包括:SMTP.POP.IMAP.MIME.NNTP.S/MIME及其它协议. 第二种:spring 对

mailto实现将用户在网页中输入的内容传递到本地邮件客户端

背景: 想在自己的网站中有这样一个设计: 用户点击提交按钮之后,就会打开本地邮件客户端,并自动将他在输入框中输入的内容作为邮件的内容,像下面这样: mailto可以帮助实现这个功能. 简介: mailto是一种电子邮件协议,通过该协议可以创建一个指向电子邮件地址的超级链接,通过该链接可以在Internet中发送电子邮件.就像在地址栏输入一个网址会打开一个网页一样,输入mailto:[email protected],就会打开本地邮件客户端,并将邮件发送给[email protected]. 在H

JAVA邮件发送的简单实现

JAVA邮件发送的简单实现 JAVA邮件发送的简单实现 JAVA MAIL是利用现有的邮件账户发送邮件的工具,比如说,我在网易注册一个邮箱账户,通过JAVA Mail的操控,我可以不亲自登录网易邮箱,让程序自动的使用网易邮箱发送邮件.这一机制被广泛的用在注册激活和垃圾邮件的发送等方面. JavaMail可以到http://www.oracle.com/technetwork/java/javamail/index-138643.html进行下载,并将mail.jar添加到classpath即可.

基于JavaMail的Java邮件发送:简单邮件发送

http://blog.csdn.net/xietansheng/article/details/51673073 http://www.cnblogs.com/codeplus/archive/2011/10/30/2229391.html http://blog.csdn.net/ghsau/article/details/17839983 ******************** 电子邮件的应用非常广泛,例如在某网站注册了一个账户,自动发送一封欢迎邮件,通过邮件找回密码,自动批量发送活动信