码迷,mamicode.com
首页 > 编程语言 > 详细

java邮件客户端

时间:2014-08-13 12:46:36      阅读:350      评论:0      收藏:0      [点我收藏+]

标签:blog   java   os   io   文件   数据   for   ar   


/***
 *邮件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; // 收件人 private String acctoaddr; // 抄送 private String kind="no"; // 类型 private String sta = "收件箱"; // 状态 private Date senddate = new Date(); // 发送(接收)时间 private String mailbody; // 正文 private List<App_emailfile> app_emailfiles; /** [集合] */ public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getFromaddr() { return fromaddr; } public void setFromaddr(String fromaddr) { this.fromaddr = fromaddr; } public String getToaddr() { return toaddr; } public void setToaddr(String toaddr) { this.toaddr = toaddr; } public String getAcctoaddr() { return acctoaddr; } public void setAcctoaddr(String acctoaddr) { this.acctoaddr = acctoaddr; } public String getKind() { return kind; } public void setKind(String kind) { this.kind = kind; } public String getSta() { return sta; } public void setSta(String sta) { this.sta = sta; } public Date getSenddate() { return senddate; } public void setSenddate(Date senddate) { this.senddate = senddate; } public String getMailbody() { return mailbody; } public void setMailbody(String mailbody) { this.mailbody = mailbody; } public List<App_emailfile> getApp_emailfiles() { return app_emailfiles; } public void setApp_emailfiles(List<App_emailfile> app_emailfiles) { this.app_emailfiles = app_emailfiles; } }

package net.jk.util.email.vo;

/**
 * 
 * 
 * @author ZOUQH
 * 邮件附件实体
 *
 */

public class App_emailfile {

	private App_email app_email;
	private String name;		//名称
	private String url;		//URL
	private String kind;		//类型
	private String sta="启用";		//状态
	
	
	
	
	public App_email getApp_email() {
		return app_email;
	}
	public void setApp_email(App_email app_email) {
		this.app_email = app_email;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public String getKind() {
		return kind;
	}
	public void setKind(String kind) {
		this.kind = kind;
	}
	public String getSta() {
		return sta;
	}
	public void setSta(String sta) {
		this.sta = sta;
	}


}

  检查是否存在新邮件如果存在则收取并且标记已读

package net.jk.util.email;

import java.io.UnsupportedEncodingException;
import java.security.Security;
import java.util.Properties;

import javax.mail.FetchProfile;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;

import com.sun.mail.imap.IMAPFolder;

/***
 * 
 * @author zouqh
 * 
 */
public class CheckNewMail {
	private String imaphost;
	private String username;
	private String password;
	private Session session;
	private Store store;
	private IMAPFolder folder=null;

	public CheckNewMail(String imaphost, String username, String password) {
		this.imaphost = imaphost;
		this.username = username;
		this.password = password;

	}

	private void connect() throws MessagingException {
		Security.addProvider(  new  com.sun.net.ssl.internal.ssl.Provider());
		final  String SSL_FACTORY  =   "javax.net.ssl.SSLSocketFactory" ;
		Properties props = System.getProperties();
		props.setProperty(  "mail.imap.socketFactory.class" , SSL_FACTORY);
		props.setProperty(  "mail.imap.socketFactory.port" ,  "993" );
		props.put("mail.store.protocol", "imap");
		props.put("mail.imap.host", imaphost);
		props.put("mail.imap.ssl.enable", "true");
		//props.setProperty(  "mail.imap.socketFactory.fallbac " ,  "false" );
		props.setProperty(  " mail.imap.port" ,  "993" );
		props.setProperty("mail.imap.auth.login.disable", "true");  
		this.session = Session.getInstance(props,null);
		this.session.setDebug(false);
		this.store = session.getStore("imap");
		this.store.connect(imaphost,username, password);
	}

	public int getNewMailCount() {
		int count = 0;
		 int total = 0;
		try {
			this.connect();
			folder =  (IMAPFolder) store.getFolder("INBOX");
			folder.open(Folder.READ_WRITE);
			 FetchProfile profile = new FetchProfile();
			 profile.add(FetchProfile.Item.ENVELOPE);
			 Message[] messages = folder.getMessages();
			 folder.fetch(messages, profile);
			 System.out.println("收件箱的邮件数:" + messages.length);
			count = folder.getNewMessageCount();
			total = folder.getMessageCount();
            System.out.println("-----------------您的邮箱共有邮件:" + total+" 封--------------");
			
			 System.out.println("\t收件箱的总邮件数:" + messages.length);  
             System.out.println("\t未读邮件数:" + folder.getUnreadMessageCount());  
             System.out.println("\t新邮件数:" + folder.getNewMessageCount());  
             System.out.println("----------------End------------------");
			 for(int i=(total-count);i<total;i++){
				 Message message = messages[i]; 
				 //message.setFlag(Flags.Flag.SEEN, true);
			 }
		} catch (MessagingException e) {
		     try  
	            {  
	                byte[] buf = e.getMessage().getBytes("ISO-8859-1");  
	                System.out.println(new String(buf, "GBK"));  
	            }  
	            catch (UnsupportedEncodingException e1)  
	            {  
	                e1.printStackTrace();  
	            }  
	            throw new RuntimeException("登录失败", e);  
		} finally {
			closeConnect();
		}
		return count;
	}

	// 关闭连接
	public void closeConnect() {
		try {
			if (folder != null)
				folder.close(true);// 关闭连接时是否删除邮件,true删除邮件
		} catch (MessagingException e) {
			e.printStackTrace();
		} finally {
			try {
				if (store != null)
					store.close();// 关闭收件箱连接
			} catch (MessagingException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		CheckNewMail mail = new CheckNewMail("imap.163.com",
				"inewzone@163.com", "218660360****");
//		CheckNewMail mail = new CheckNewMail("imap.qq.com",
//		"329486979@qq.com", "218660360****"");
//		CheckNewMail mail = new CheckNewMail("imap.yeah.net",
//		"inewzou@yeah.net", "218660360****"");
		System.out.println(mail.getNewMailCount());
	}

}

  

 

package net.jk.util.email;

import java.io.File;
import java.security.Security;
import java.util.Properties;

import com.sun.net.ssl.internal.ssl.Provider;

/**
 * 收邮件的基本信息
 */
public class MailReceiverInfo {
	// 邮件服务器的IP、端口和协议
	private String mailServerHost;
	private String mailServerPort = "110";
	private String protocal = "pop3";
	// 登陆邮件服务器的用户名和密码
	private String userName;
	private String password;
	// 保存邮件的路径
	private String attachmentDir = "C:/temp/";
	private String emailDir = "C:/temp/";
	private String emailFileSuffix = ".eml";
	// 是否需要身份验证
	private boolean validate = true;

	private boolean isSSL;
	

	/**
	 * 获得邮件会话属性
	 */
	public Properties getProperties() {
		Properties p = new Properties();
		if (isSSL() == true) {
			Security.addProvider(new Provider());
			final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
			p.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
			p.setProperty("mail.pop3.socketFactory.fallback", "false");
			p.setProperty("mail.pop3.port", this.mailServerPort);
			p.setProperty("mail.pop3.socketFactory.port", this.mailServerPort);
			p.put("mail.pop3.host", this.mailServerHost);
			p.put("mail.pop3.auth", validate ? "true" : "false");
		} else {
			p.put("mail.pop3.host", this.mailServerHost);
			p.put("mail.pop3.port", this.mailServerPort);
			p.put("mail.pop3.auth", validate ? "true" : "false");
		}
		return p;
	}

	public String getProtocal() {
		return protocal;
	}

	public void setProtocal(String protocal) {
		this.protocal = protocal;
	}

	public String getAttachmentDir() {
		return attachmentDir;
	}

	public void setAttachmentDir(String attachmentDir) {
		if (!attachmentDir.endsWith(File.separator)) {
			attachmentDir = attachmentDir + File.separator;
		}
		this.attachmentDir = attachmentDir;
	}

	public String getEmailDir() {
		return emailDir;
	}

	public void setEmailDir(String emailDir) {
		if (!emailDir.endsWith(File.separator)) {
			emailDir = emailDir + File.separator;
		}
		this.emailDir = emailDir;
	}

	public String getEmailFileSuffix() {
		return emailFileSuffix;
	}

	public void setEmailFileSuffix(String emailFileSuffix) {
		if (!emailFileSuffix.startsWith(".")) {
			emailFileSuffix = "." + emailFileSuffix;
		}
		this.emailFileSuffix = emailFileSuffix;
	}

	public String getMailServerHost() {
		return mailServerHost;
	}

	public void setMailServerHost(String mailServerHost) {
		this.mailServerHost = mailServerHost;
	}

	public String getMailServerPort() {
		return mailServerPort;
	}

	public void setMailServerPort(String mailServerPort) {
		this.mailServerPort = mailServerPort;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public boolean isValidate() {
		return validate;
	}

	public void setValidate(boolean validate) {
		this.validate = validate;
	}

	public boolean isSSL() {
		return isSSL;
	}

	public void setSSL(boolean isSSL) {
		this.isSSL = isSSL;
	}

	
}

  

package net.jk.util.email;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.mail.BodyPart;
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.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import net.jk.app.model.App_email;
import net.jk.app.model.App_emailfile;

import org.apache.commons.io.FileUtils;

/**
 * 邮件接收器,目前支持pop3协议。 能够接收文本、HTML和带有附件的邮件
 */
public class MailReceiver {
	// 收邮件的参数配置
	private MailReceiverInfo receiverInfo;
	// 与邮件服务器连接后得到的邮箱
	private Store store;
	// 收件箱
	private Folder folder;
	// 收件箱中的邮件消息
	private Message[] messages;
	// 当前正在处理的邮件消息
	private Message currentMessage;

	private String currentEmailFileName;

	private App_email app_email;

	private App_emailfile app_emailfiles;

	public List<App_email> app_emails = new ArrayList<App_email>();
	
	private static String path;
	
	public MailReceiver(String email, String password, String host,
			String hostport, boolean isSSL, String root) {
		this.receiverInfo = new MailReceiverInfo();
		this.receiverInfo.setUserName(email);
		this.receiverInfo.setPassword(password);
		this.receiverInfo.setMailServerHost(host);
		this.receiverInfo.setMailServerPort(hostport);
		this.receiverInfo.setSSL(isSSL);
		this.receiverInfo.setValidate(true);
		path=root;
		this.receiverInfo.setEmailDir(root + File.separator + email
				+ File.separator);
		this.receiverInfo.setAttachmentDir(root + File.separator + email
				+ File.separator);
	}
	
	
	
	
	public App_email getApp_email() {
		return app_email;
	}

	public void setApp_email(App_email app_email) {
		this.app_email = app_email;
	}


	public void setApp_emailfiles(App_emailfile app_emailfiles) {
		this.app_emailfiles = app_emailfiles;
	}

	
	public App_emailfile getApp_emailfiles() {
		return app_emailfiles;
	}




	public List<App_email> getApp_emails() {
		return app_emails;
	}

	public void setApp_emails(List<App_email> app_emails) {
		this.app_emails = app_emails;
	}




	private int total;

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}






	public MailReceiver(MailReceiverInfo receiverInfo) {
		this.receiverInfo = receiverInfo;
	}

	/**
	 * 收邮件
	 */
	public void receiveAllMail() throws Exception {
		if (this.receiverInfo == null) {
			throw new Exception("必须提供接收邮件的参数!");
		}
		// 连接到服务器
		if (this.connectToServer()) {
			// 打开收件箱
			if (this.openInBoxFolder()) {
				// 获取所有邮件
				this.getAllMail();
				this.closeConnection();
			} else {
				throw new Exception("打开收件箱失败!");
			}
		} else {
			throw new Exception("连接邮件服务器失败!");
		}
	}

	/**
	 * 收邮件
	 */
	public void receiveMail(int count) throws Exception {
		if (this.receiverInfo == null) {
			throw new Exception("必须提供接收邮件的参数!");
		}
		// 连接到服务器
		if (this.connectToServer()) {
			// 打开收件箱
			if (this.openInBoxFolder()) {
				// 获取指定邮件
				this.getMail(count);
				this.closeConnection();
			} else {
				throw new Exception("打开收件箱失败!");
			}
		} else {
			throw new Exception("连接邮件服务器失败!");
		}
	}

	/**
	 * 登陆邮件服务器
	 */
	public boolean connectToServer() {
		// 判断是否需要身份认证
		MyAuthenticator authenticator = null;
		if (this.receiverInfo.isValidate()) {
			// 如果需要身份认证,则创建一个密码验证器
			authenticator = new MyAuthenticator(
					this.receiverInfo.getUserName(),
					this.receiverInfo.getPassword());
		}
		// 创建session
		Session session = Session.getInstance(
				this.receiverInfo.getProperties(), authenticator);
		// session.setDebug(true);
		// 创建store,建立连接
		try {
			this.store = session.getStore(this.receiverInfo.getProtocal());
		} catch (NoSuchProviderException e) {
			System.out.println("连接服务器失败!");
			return false;
		}

		System.out.println("connecting");
		try {
			this.store.connect();
		} catch (MessagingException e) {
			System.out.println("连接服务器失败!");
			return false;
		}
		System.out.println("连接服务器成功");
		return true;
	}

	/**
	 * 打开收件箱
	 */
	private boolean openInBoxFolder() {
		try {
			this.folder = store.getFolder("INBOX");
			// 只读
			folder.open(Folder.READ_ONLY);
			return true;
		} catch (MessagingException e) {
			System.err.println("打开收件箱失败!");
		}
		return false;
	}

	/**
	 * 断开与邮件服务器的连接
	 */
	private boolean closeConnection() {
		try {
			if (this.folder.isOpen()) {
				this.folder.close(true);
			}
			this.store.close();
			System.out.println("成功关闭与邮件服务器的连接!");
			return true;
		} catch (Exception e) {
			System.out.println("关闭和邮件服务器之间连接时出错!");
		}
		return false;
	}

	/**
	 * 获取messages中的所有邮件
	 * 
	 * @throws MessagingException
	 */
	private void getAllMail() throws MessagingException {
		// 从邮件文件夹获取邮件信息
		this.messages = this.folder.getMessages();
		System.out.println("总的邮件数目:" + messages.length);
		System.out.println("新邮件数目:" + this.getNewMessageCount());
		System.out.println("未读邮件数目:" + this.getUnreadMessageCount());
		// 将要下载的邮件的数量。
		int mailArrayLength = this.getMessageCount();
		System.out.println("一共有邮件" + mailArrayLength + "封");
		int errorCounter = 0; // 邮件下载出错计数器
		int successCounter = 0;

		for (int index = 0; index < mailArrayLength; index++) {
			try {
				this.currentMessage = (messages[index]); // 设置当前message
				System.out.println("正在获取第" + index + "封邮件");
				this.showMailBasicInfo();
				getMail(); // 获取当前message
				System.out.println("成功获取第" + index + "封邮件");
				successCounter++;
			} catch (Throwable e) {
				e.printStackTrace();
				errorCounter++;
				System.err.println("下载第" + index + "封邮件时出错");
			}
		}
		System.out.println("------------------");
		System.out.println("成功下载了" + successCounter + "封邮件");
		System.out.println("失败下载了" + errorCounter + "封邮件");
		System.out.println("------------------");
	}

	private void getMail(int count) throws MessagingException {

		this.messages = this.folder.getMessages();
		System.out.println("总的邮件数目:" + messages.length);
		System.out.println("新邮件数目:" + this.getNewMessageCount());
		System.out.println("未读邮件数目:" + this.getUnreadMessageCount());
		int num = this.getMessageCount();
		int len = 0;
		int index = 0;
		int errorCounter = 0; // 邮件下载出错计数器
		int successCounter = 0;
		if (num > count) {
			index = num - count;
			len = num;
		}
		if (num <= count) {
			len = count;
		}
		for (; index < len; index++) {
			try {
				this.currentMessage = (messages[index]); // 设置当前message
				this.currentMessage.setFlag(Flags.Flag.SEEN, true); 
				System.out.println("正在获取第" + index + "封邮件");
				this.showMailBasicInfo();
				getMail(); // 获取当前message
				System.out.println("成功获取第" + index + "封邮件");
				successCounter++;
			} catch (Throwable e) {
				e.printStackTrace();
				errorCounter++;
				System.err.println("下载第" + index + "封邮件时出错");
			}
		}
		System.out.println("成功下载了" + successCounter + "封邮件");
		System.out.println("失败下载了" + errorCounter + "封邮件");
		System.out.println("------------------");

	}

	/**
	 * 显示邮件的基本信息
	 */
	private void showMailBasicInfo() throws Exception {
		showMailBasicInfo(this.currentMessage);
	}

	private void showMailBasicInfo(Message message) throws Exception {
		System.out.println("-------- 邮件ID:" + this.getMessageId()
				+ " ---------");
		System.out.println("From:" + this.getFrom());
		System.out.println("To:" + this.getTOAddress());
		System.out.println("CC:" + this.getCCAddress());
		System.out.println("BCC:" + this.getBCCAddress());
		System.out.println("Subject:" + this.getSubject());
		System.out.println("发送时间::" + this.getSentDate());
		System.out.println("是新邮件?" + this.isNew());
		System.out.println("要求回执?" + this.getReplySign());
		System.out.println("包含附件?" + this.isContainAttach());
		System.out.println("------------------------------");
	}

	/**
	 * 获得邮件的收件人,抄送,和密送的地址和姓名,根据所传递的参数的不同 "to"----收件人 "cc"---抄送人地址 "bcc"---密送人地址
	 */
	private String getTOAddress() throws Exception {
		return getMailAddress("TO", this.currentMessage);
	}

	private String getCCAddress() throws Exception {
		return getMailAddress("CC", this.currentMessage);
	}

	private String getBCCAddress() throws Exception {
		return getMailAddress("BCC", this.currentMessage);
	}

	/**
	 * 获得邮件地址
	 * 
	 * @param type
	 *            类型,如收件人、抄送人、密送人
	 * @param mimeMessage
	 *            邮件消息
	 * @return
	 * @throws Exception
	 */
	private String getMailAddress(String type, Message mimeMessage)
			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("错误的地址类型!!");
		}
		return mailaddr;
	}

	/**
	 * 获得发件人的地址和姓名
	 * 
	 * @throws Exception
	 */
	private String getFrom() throws Exception {
		return getFrom(this.currentMessage);
	}

	private String getFrom(Message mimeMessage) 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;
	}

	/**
	 * 获取messages中message的数量
	 * 
	 * @return
	 */
	private int getMessageCount() {
		return this.messages.length;
	}

	/**
	 * 获得收件箱中新邮件的数量
	 * 
	 * @return
	 * @throws MessagingException
	 */
	private int getNewMessageCount() throws MessagingException {
		return this.folder.getNewMessageCount();
	}

	/**
	 * 获得收件箱中未读邮件的数量
	 * 
	 * @return
	 * @throws MessagingException
	 */
	private int getUnreadMessageCount() throws MessagingException {
		return this.folder.getUnreadMessageCount();
	}

	/**
	 * 获得邮件主题
	 */
	private String getSubject() throws MessagingException {
		return getSubject(this.currentMessage);
	}

	private String getSubject(Message mimeMessage) throws MessagingException {
		String subject = "";
		String tempStr = "";
		tempStr = mimeMessage.getSubject();
		tempStr = MessyCodeCheck.toGb2312(tempStr);
		try {
			// 将邮件主题解码
			subject = MimeUtility.decodeText(tempStr);
			if (subject == null) {
				subject = "";
			}
		} catch (Exception exce) {
		}
		return subject;
	}

	/**
	 * 获得邮件发送日期
	 */
	private Date getSentDate() throws Exception {
		return getSentDate(this.currentMessage);
	}

	private Date getSentDate(Message mimeMessage) throws Exception {
		return mimeMessage.getSentDate();
	}

	/**
	 * 判断此邮件是否需要回执,如果需要回执返回"true",否则返回"false"
	 */
	private boolean getReplySign() throws MessagingException {
		return getReplySign(this.currentMessage);
	}

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

	/**
	 * 获得此邮件的Message-ID
	 */
	private String getMessageId() throws MessagingException {
		return getMessageId(this.currentMessage);
	}

	private String getMessageId(Message mimeMessage) throws MessagingException {
		return ((MimeMessage) mimeMessage).getMessageID();
	}

	/**
	 * 判断此邮件是否已读,如果未读返回返回false,反之返回true
	 */
	private boolean isNew() throws MessagingException {
		return isNew(this.currentMessage);
	}

	private boolean isNew(Message mimeMessage) throws MessagingException {
		boolean isnew = false;
		Flags flags = mimeMessage.getFlags();
		Flags.Flag[] flag = flags.getSystemFlags();
		for (int i = 0; i < flag.length; i++) {
			if (flag[i] == Flags.Flag.SEEN) {
				isnew = true;
				break;
			}
		}
		return isnew;
	}

	/**
	 * 判断此邮件是否包含附件
	 */
	private boolean isContainAttach() throws Exception {
		return isContainAttach(this.currentMessage);
	}

	private boolean isContainAttach(Part part) throws Exception {
		boolean attachflag = false;
		int k = 0;
		if (part.isMimeType("multipart/*")) {
			// 如果邮件体包含多部分
			Multipart mp = (Multipart) part.getContent();
			// 遍历每部分

			for (int i = 0; i < mp.getCount(); i++) {

				// 获得每部分的主体
				BodyPart bodyPart = mp.getBodyPart(i);
				String disposition = bodyPart.getDisposition();
				if ((disposition != null)
						&& ((disposition.equals(Part.ATTACHMENT)) || (disposition
								.equals(Part.INLINE)))) {
					k++;
					attachflag = true;
				} else if (bodyPart.isMimeType("multipart/mixed")) {
					k++;
					attachflag = isContainAttach((Part) bodyPart);
				} else {
					String contype = bodyPart.getContentType();
					if (contype.toLowerCase().indexOf("application") != -1) {
						attachflag = true;
						k++;
					}
					if (contype.toLowerCase().indexOf("name") != -1) {
						attachflag = true;
						k++;
					}
				}

			}
		} else if (part.isMimeType("message/rfc822")) {

			attachflag = isContainAttach((Part) part.getContent());
		}

		if (attachflag) {
			System.out
					.println("hello==================================part.isMimeType"
							+ k + attachflag);
		}

		return attachflag;
	}

	/**
	 * 获得当前邮件
	 */
	private void getMail() throws Exception {
		try {
			List<App_emailfile> emailfiles = new ArrayList<App_emailfile>();
			App_email emailcontent = new App_email();
			emailcontent.setApp_emailfiles(this.getEmailFiles(emailfiles,
					this.currentMessage,emailcontent));
			// this.saveMessageAsFile(currentMessage);
			this.parseMessage(currentMessage, emailcontent);

		} catch (IOException e) {
			throw new IOException("保存邮件出错,检查保存路径");
		} catch (MessagingException e) {
			throw new MessagingException("邮件转换出错");
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("未知错误");
		}
	}

	/**
	 * 保存邮件源文件
	 */
	private void saveMessageAsFile(Message message) {
		try {
			// 将邮件的ID中尖括号中的部分做为邮件的文件名
			String oriFileName = null;
			if (this.getMessageId(message) != null) {
				oriFileName = getInfoBetweenBrackets(this.getMessageId(message)
						.toString());
			}
			// 设置文件后缀名。若是附件则设法取得其文件后缀名作为将要保存文件的后缀名,
			// 若是正文部分则用.htm做后缀名
			String emlName = oriFileName;
			String fileNameWidthExtension = this.receiverInfo.getEmailDir()
					+ oriFileName + this.receiverInfo.getEmailFileSuffix();
			File storeFile = new File(fileNameWidthExtension);
			for (int i = 0; storeFile.exists(); i++) {
				emlName = oriFileName + i;
				fileNameWidthExtension = this.receiverInfo.getEmailDir()
						+ emlName + this.receiverInfo.getEmailFileSuffix();
				storeFile = new File(fileNameWidthExtension);
			}
			this.currentEmailFileName = emlName;
			System.out.println("邮件消息的存储路径: " + fileNameWidthExtension);
			File file = null;
			file = new File(this.receiverInfo.getEmailDir());
			// FileUtils.forceMkdir(file);
			file = storeFile;
			// FileUtils.touch(file);
			// 将邮件消息的内容写入ByteArrayOutputStream流中
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			message.writeTo(baos);
			// 读取邮件消息流中的数据
			// StringReader in = new StringReader(baos.toString());
			// 存储到文件
			// saveFile(fileNameWidthExtension, in);
		} catch (MessagingException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/*
	 * 解析邮件
	 */
	private void parseMessage(Message message, App_email emailcontent)
			throws IOException, MessagingException {
		Object content = message.getContent();

		if (content instanceof Multipart) {
			handleMultipart((Multipart) content, emailcontent);
		} else if (content instanceof String) {
			
			if (content != null) {
				emailcontent.setMailbody( content.toString());
				try {
					emailcontent.setSenddate(this.getSentDate());
					emailcontent.setTitle(this.getSubject());
					emailcontent.setFromaddr(this.getFrom());
					emailcontent.setToaddr(this.getTOAddress());
					emailcontent.setAcctoaddr(this.getBCCAddress());
					app_emails.add(emailcontent);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		else {
			handlePart(message, emailcontent);
		}

	}

	/*
	 * 解析Multipart
	 */
	private void handleMultipart(Multipart multipart, App_email emailcontent)
			throws MessagingException, IOException {
		for (int i = 0, n = multipart.getCount(); i < n; i++) {
			handlePart(multipart.getBodyPart(i), emailcontent);
		}
	}

	/*
	 * 解析指定part,从中提取文件
	 */
	private void handlePart(Part part, App_email emailcontent)
			throws MessagingException, IOException {
		String disposition = null;
		String content = null;
		disposition = part.getDisposition();
		// 当前没有附件的情况
		if (disposition == null) {

			Object obj = part.getContent();
			System.out.println("abcdefg======>" + (obj instanceof Multipart));
			if (obj instanceof String) {
				content = (String) obj;

				if (content != null) {
					emailcontent.setMailbody(content);
					try {
						emailcontent.setSenddate(this.getSentDate());
						emailcontent.setTitle(this.getSubject());
						emailcontent.setFromaddr(this.getFrom());
						emailcontent.setToaddr(this.getTOAddress());
						emailcontent.setAcctoaddr(this.getBCCAddress());
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				app_emails.add(emailcontent);
			}

			if (obj instanceof Multipart) {
				this.handleMultipart((Multipart) obj,  emailcontent);
				
			}

		}

		if (!Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
			if (part.getContent().getClass().equals(MimeMultipart.class)) {
				MimeMultipart mimemultipart = (MimeMultipart) part.getContent();
				System.out.println("Number of embedded multiparts "
						+ mimemultipart.getCount());
				for (int k = 0; k < mimemultipart.getCount(); k++) {
					if (mimemultipart.getBodyPart(k).getFileName() != null) {
						System.out.println("     > Creating file with name : "
								+ mimemultipart.getBodyPart(k).getFileName());
						savefile(mimemultipart.getBodyPart(k).getFileName(),
								mimemultipart.getBodyPart(k).getInputStream());
					}
				}
			}
		}

		System.out.println("     > Creating file with name : "
				+ part.getFileName());
		savefile(part.getFileName(), part.getInputStream());
	}

	
	
	public List<App_emailfile> getEmailFiles(List<App_emailfile> emailFiles, Part part,App_email emailcontent) {
		boolean attachflag = false;
		App_emailfile emailfile = null;
		try {
			if (part.isMimeType("multipart/*")) {
				// 如果邮件体包含多部分
				Multipart mp = (Multipart) part.getContent();
				// 遍历每部分

				for (int i = 0; i < mp.getCount(); i++) {

					// 获得每部分的主体
					BodyPart bodyPart = mp.getBodyPart(i);
					String disposition = bodyPart.getDisposition();
					if ((disposition != null)
							&& ((disposition.equals(Part.ATTACHMENT)) || (disposition
									.equals(Part.INLINE)))) {
						emailfile = new App_emailfile();
						emailfile.setName(getFileName(bodyPart));
						
						emailfile.setUrl(path+bodyPart.getFileName());
						System.out.println();
						emailfile
								.setKind(MessyCodeCheck.getExtensionName(path));
						emailfile.setApp_email(emailcontent);
						emailFiles.add(emailfile);

					} else {
						String contype = bodyPart.getContentType();
						if (contype.toLowerCase().indexOf("application") != -1) {
							emailfile = new App_emailfile();
							emailfile.setName(getFileName(bodyPart));
							path = this.receiverInfo.getUserName()
									+ getFileName(bodyPart);
							emailfile.setUrl(path+bodyPart.getFileName());
							emailfile.setKind(MessyCodeCheck
									.getExtensionName(path));
							emailfile.setApp_email(emailcontent);
							emailFiles.add(emailfile);
						}
						if (contype.toLowerCase().indexOf("name") != -1) {
							emailfile = new App_emailfile();
							emailfile.setName(getFileName(bodyPart));
							path = this.receiverInfo.getUserName()
									+ getFileName(bodyPart);
							emailfile.setUrl(path+bodyPart.getFileName());
							emailfile.setKind(MessyCodeCheck
									.getExtensionName(path));
							emailfile.setApp_email(emailcontent);
							emailFiles.add(emailfile);
						}
					}

				}
			} else if (part.isMimeType("message/rfc822")) {

				attachflag = isContainAttach((Part) part.getContent());
			}
		} catch (MessagingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		System.out
				.println("emailFiles.size()==================================>"
						+ emailFiles.size());

		return emailFiles;
	}


	public static void savefile(String FileName, InputStream is)
			throws IOException {
		File f = new File(path+ FileName);
		FileUtils.touch(f);
		FileOutputStream fos = new FileOutputStream(f);
		byte[] buf = new byte[4096];
		int bytesRead;
		while ((bytesRead = is.read(buf)) != -1) {
			fos.write(buf, 0, bytesRead);
		}
		fos.close();

	}

	private String getFileName(Part part) throws MessagingException,
			UnsupportedEncodingException {
		String fileName = part.getFileName();

		String name = null;
		if (fileName != null) {
			fileName = MimeUtility.decodeText(fileName);
			name = fileName;
			int index = fileName.lastIndexOf("/");
			if (index != -1) {
				name = fileName.substring(index + 1);
			}
		}
		return name;
	}

	/**
	 * 保存文件内容
	 * 
	 * @param fileName
	 *            文件名
	 * @param input
	 *            输入流
	 * @throws IOException
	 */
	private void saveFile(String fileName, Reader input) throws IOException {

		// 为了放置文件名重名,在重名的文件名后面天上数字
		File file = new File(fileName);
		// 先取得文件名的后缀
		int lastDot = fileName.lastIndexOf(".");
		String extension = fileName.substring(lastDot);
		fileName = fileName.substring(0, lastDot);
		for (int i = 0; file.exists(); i++) {
			//  如果文件重名,则添加i
			file = new File(fileName + i + extension);
		}
		// 从输入流中读取数据,写入文件输出流
		FileOutputStream fs = new FileOutputStream(file);
		OutputStreamWriter ow = new OutputStreamWriter(fs, "UTF-8");
		// FileWriter fos = new FileWriter(file);
		BufferedWriter bos = new BufferedWriter(ow);
		BufferedReader bis = new BufferedReader(input);
		int aByte;
		while ((aByte = bis.read()) != -1) {
			bos.write(aByte);
		}
		// 关闭流
		bos.flush();
		bos.close();
		bis.close();
	}

	/**
	 * 获得尖括号之间的字符
	 * 
	 * @param str
	 * @return
	 * @throws Exception
	 */
	private String getInfoBetweenBrackets(String str) throws Exception {
		int i, j; // 用于标识字符串中的"<"和">"的位置
		if (str == null) {
			str = "error";
			return str;
		}
		i = str.lastIndexOf("<");
		j = str.lastIndexOf(">");
		if (i != -1 && j != -1) {
			str = str.substring(i + 1, j);
		}
		return str;
	}

	public static void main(String[] args) throws Exception {
		MailReceiverInfo receiverInfo = new MailReceiverInfo();
		receiverInfo.setMailServerHost("pop.163.com");
		receiverInfo.setMailServerPort("995");
		receiverInfo.setValidate(true);
		receiverInfo.setUserName("inewzone@163.com");
		receiverInfo.setPassword("218660360****");
		receiverInfo.setAttachmentDir("E:/temp/mail/yeah");
		receiverInfo.setEmailDir("E:/temp/mail/yeah/emaildir");
		receiverInfo.setSSL(true);
		MailReceiver receiver = new MailReceiver(receiverInfo);

		receiver.receiveAllMail();
		
		System.out.println("receiver.getNewMessageCount()=====>"+receiver.getNewMessageCount());
		List<App_email> contents=new ArrayList<App_email>();
		
		for (App_email a : receiver.getApp_emails()) {
			if(!contents.contains(a)){
				contents.add(a);
			}
		}
		for (App_email a : contents) {
			System.out.println("a.getSubject()" + a.getTitle());
			if (a.getApp_emailfiles() != null) {
				for (App_emailfile b :a.getApp_emailfiles()) {
					System.out.println("b.getName()" + b.getUrl());
				}
			}
		}
	}
}

  发送带附件的邮件

package net.jk.util.email;

import java.security.Security;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

public class SendAttachMail {

	private String SMTPHost = ""; // SMTP服务器
	private String user = ""; // 登录SMTP服务器的帐号
	private String password = ""; // 登录SMTP服务器的密码
	private String from = ""; // 发件人邮箱
	private Address[] to = null; // 收件人邮箱
	private String subject = ""; // 邮件标题
	private String content = ""; // 邮件内容
	private Address[] copy_to = null;// 抄送邮件到
	private Session mailSession = null;
	private Transport transport = null;
	public ArrayList<String> filename = new ArrayList<String>(); // 附件文件名
	private static SendAttachMail sendMail = new SendAttachMail();

	// 无参数构造方法
	private SendAttachMail() {
	}

	public SendAttachMail(String smtphost, String user, String password,
			String from, Address[] to, String subject, String content,
			Address[] copy_to) {
		this.SMTPHost = smtphost;
		this.user = user;
		this.password = password;
		this.from = from;
		this.to = to;
		this.subject = subject;
		this.content = content;
		this.copy_to = copy_to;

	}

	// 返回本类对象的实例
	public static SendAttachMail getSendMailInstantiate() {
		return sendMail;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		try {
			// 解决内容的中文问题
			content = new String(content.getBytes("ISO8859-1"), "gbk");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		this.content = content;
	}

	public ArrayList<String> getFilename() {
		return filename;
	}

	public void setFilename(ArrayList<String> filename) {
		Iterator<String> iterator = filename.iterator();
		ArrayList<String> attachArrayList = new ArrayList<String>();
		while (iterator.hasNext()) {
			String attachment = iterator.next();
			try {
				// 解决文件名的中文问题
				attachment = MimeUtility.decodeText(attachment);
				// 将文件路径中的‘\‘替换成‘/‘
				attachment = attachment.replaceAll("\\\\", "/");
				attachArrayList.add(attachment);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		this.filename = attachArrayList;
	}

	public String getFrom() {
		return from;
	}

	public void setFrom(String from) {
		this.from = from;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getSMTPHost() {
		return SMTPHost;
	}

	public void setSMTPHost(String host) {
		SMTPHost = host;
	}

	public String getSubject() {
		return subject;
	}

	public void setSubject(String subject) {
		try {
			// 解决标题的中文问题
			subject = MimeUtility.encodeText(subject);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		this.subject = subject;
	}

	public Address[] getTo() {
		return to;
	}

	public void setTo(String toto) {
		int i = 0;
		StringTokenizer tokenizer = new StringTokenizer(toto, ";");
		to = new Address[tokenizer.countTokens()];// 动态的决定数组的长度
		while (tokenizer.hasMoreTokens()) {
			String d = tokenizer.nextToken();
			try {
				d = MimeUtility.encodeText(d);
				to[i] = new InternetAddress(d);// 将字符串转换为整型
			} catch (Exception e) {
				e.printStackTrace();
			}
			i++;
		}
	}

	public String getUser() {
		return user;
	}

	public void setUser(String user) {
		this.user = user;
	}

	public Address[] getCopy_to() {
		return copy_to;
	}

	// 设置抄送
	public void setCopy_to(String copyTo) {
		int i = 0;
		StringTokenizer tokenizer = new StringTokenizer(copyTo, ";");
		copy_to = new Address[tokenizer.countTokens()];// 动态的决定数组的长度
		while (tokenizer.hasMoreTokens()) {
			String d = tokenizer.nextToken();
			try {
				d = MimeUtility.encodeText(d);
				copy_to[i] = new InternetAddress(d);// 将字符串转换为整型
			} catch (Exception e) {
				e.printStackTrace();
			}
			i++;
		}
	}

	public void connect() throws Exception {

		Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
		final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
		// 创建一个属性对象
		Properties props = new Properties();
		MyAuthenticator auth = null;
		// 指定SMTP服务器
		props.put("mail.smtp.host", this.SMTPHost);
		// 指定是否需要SMTP验证
		props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
		props.setProperty("mail.smtp.socketFactory.fallback", "false");
		props.setProperty("mail.smtp.port", "465");
		props.setProperty("mail.smtp.socketFactory.port", "465");
		props.put("mail.smtp.auth", "true");
		// 创建一个授权验证对象
		auth = new MyAuthenticator(this.user, this.password);
		// 创建一个Session对象
		mailSession = Session.getDefaultInstance(props, auth);
		// 设置是否调试
		mailSession.setDebug(true);
		if (transport != null)
			transport.close();// 关闭连接
		// 创建一个Transport对象
		transport = mailSession.getTransport("smtp");
		// 连接SMTP服务器
		transport.connect(this.SMTPHost, this.user, this.password);
	}

	// 发送邮件
	public String send() {
		String issend = "";
		try {// 连接smtp服务器
			connect();
			// 创建一个MimeMessage 对象
			MimeMessage message = new MimeMessage(mailSession);

			// 指定发件人邮箱
			message.setFrom(new InternetAddress(from));
			// 指定收件人邮箱
			message.addRecipients(Message.RecipientType.TO, to);
			if (!"".equals(copy_to))
				// 指定抄送人邮箱
				message.addRecipients(Message.RecipientType.CC, copy_to);
			// 指定邮件主题
			message.setSubject(subject);
			// 指定邮件发送日期
			message.setSentDate(new Date());
			// 指定邮件优先级 1:紧急 3:普通 5:缓慢
			message.setHeader("X-Priority", "1");
			message.saveChanges();
			// 判断附件是否为空
			if (!filename.isEmpty()) {
				// 新建一个MimeMultipart对象用来存放多个BodyPart对象
				Multipart container = new MimeMultipart();
				// 新建一个存放信件内容的BodyPart对象
				BodyPart textBodyPart = new MimeBodyPart();
				// 给BodyPart对象设置内容和格式/编码方式
				textBodyPart.setContent(content, "text/html;charset=gbk");
				// 将含有信件内容的BodyPart加入到MimeMultipart对象中
				container.addBodyPart(textBodyPart);
				Iterator<String> fileIterator = filename.iterator();
				while (fileIterator.hasNext()) {// 迭代所有附件
					String attachmentString = fileIterator.next();
					// 新建一个存放信件附件的BodyPart对象
					BodyPart fileBodyPart = new MimeBodyPart();
					// 将本地文件作为附件
					FileDataSource fds = new FileDataSource(attachmentString);
					fileBodyPart.setDataHandler(new DataHandler(fds));
					// 处理邮件中附件文件名的中文问题
					String attachName = fds.getName();
					attachName = MimeUtility.encodeText(attachName);
					// 设定附件文件名
					fileBodyPart.setFileName(attachName);
					// 将附件的BodyPart对象加入到container中
					container.addBodyPart(fileBodyPart);
				}
				// 将container作为消息对象的内容
				message.setContent(container);
			} else {// 没有附件的情况
				message.setContent(content, "text/html;charset=gbk");
			}
			// 发送邮件
			Transport.send(message, message.getAllRecipients());
			if (transport != null)
				transport.close();
		} catch (Exception ex) {
			issend = ex.getMessage();
		}
		return issend;
	}

	public static void main(String args[]) {

		String subject = "主题信息";
		String content = "<html><title>TEST</title><body>这个只是一个测试文件!请注意查收!</body></html>";
		String from = "329486979@qq.com";
		String tto = "inewzou@yeah.net";
		String[] media = tto.split(",");
		List list = new ArrayList();
		for (int i = 0; i < media.length; i++) {
			try {
				list.add(new InternetAddress(media[i]));
			} catch (AddressException e) {
				e.printStackTrace();
			}
		}
		InternetAddress[] address = (InternetAddress[]) list
				.toArray(new InternetAddress[list.size()]);
		Address[] copy_to = address;
		SendAttachMail mail = new SendAttachMail("smtp.qq.com",
				"329486979@qq.com", "2186603606***", from, address, subject,
				content, copy_to);
		//mail.filename.add("E:/files/11.jpg");
		mail.send();
//		try {
//			mail.connect();
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
	}

}

  

  

java邮件客户端,布布扣,bubuko.com

java邮件客户端

标签:blog   java   os   io   文件   数据   for   ar   

原文地址:http://www.cnblogs.com/inewzone/p/3909553.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!