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

关于JavaMail的实现方式

时间:2016-01-29 11:47:17      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:

首先导入javamail的jar包

		<!-- java mail -->
		<dependency>
			<groupId>javax.mail</groupId>
			<artifactId>mail</artifactId>
			<version>1.5.0-b01</version>
        </dependency>
	    <!--  java mail end -->

 

 java具体实现代码

package com.sharp.slc.common;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.IMAPStore;




public class ReadMail {
	private MimeMessage mimeMessage = null;
	private StringBuffer bodyText = new StringBuffer(); // 存放邮件内容的StringBuffer对象
	private String dateFormat = "yy-MM-dd HH:mm"; // 默认的日前显示格式
	private static String host = AgentConfig.getJavamailValue("host");
	private static String userName = AgentConfig.getJavamailValue("userName");
	private static String passWord = AgentConfig.getJavamailValue("passWord");
	private static IMAPFolder folder;
	private static IMAPStore store;
	
	
	/**
	 * 构造函数,初始化一个MimeMessage对象
	 */
	public ReadMail() {
	}

	public ReadMail(MimeMessage mimeMessage) {
		this.mimeMessage = mimeMessage;
	}

	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;     
	  }     
	  
	  /**   
	   * 获得邮件的收件人,抄送,和密送的地址和姓名,根据所传递的参数的不同 "to"----收件人 "cc"---抄送人地址 "bcc"---密送人地址   
	   */    
	  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) {
			exce.printStackTrace();
		}
		return subject;
	}

	/**
	 * * 获得邮件发送日期
	 */
	public String getSentDate() throws Exception {
		Date sentDate = mimeMessage.getSentDate();
		SimpleDateFormat format = new SimpleDateFormat(dateFormat);
		String strSentDate = format.format(sentDate);
		return strSentDate;
	}

	/**
	 * * 获得邮件正文内容
	 */
	public String getBodyText() {
		return bodyText.toString();
	}
	
	/**
	 * * 解析邮件,把得到的邮件内容保存到一个StringBuffer对象中,解析邮件 *
	 * 主要是根据MimeType类型的不同执行不同的操作,一步一步的解析
	 */
	public void getMailContent(Part part) throws Exception {
		String contentType = part.getContentType();
		int nameIndex = contentType.indexOf("name");
		boolean conName = false;
		if (nameIndex != -1) {
			conName = true;
		}
		if (part.isMimeType("text/plain") && conName == false) {
			// text/plain 类型
			bodyText.append((String) part.getContent());
		} else if (part.isMimeType("multipart/*")) {
			// 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")) {
			// message/rfc822
			getMailContent((Part) part.getContent());
		}
	}

	/**
	 * * 设置日期显示格式
	 */
	public void setDateFormat(String format) throws Exception {
		this.dateFormat = format;
	}

  /**   
   * 【判断此邮件是否已读,如果未读返回返回false,反之返回true】   
   */
	public boolean isNew() throws MessagingException {     
	      boolean isnew = false;     
	      Flags flags = ((Message) 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;     
	  }     
	
    /**
     * get all email message
     * @param subjectType
     * @return
     * @throws Exception
     */
	public static Message[] getMsg() throws Exception {
		Properties props = new Properties();
		props.setProperty("mail.store.protocol", "imap");
		props.setProperty("mail.imap.host", host);
		props.setProperty("mail.imap.port", "143");
		Session session = Session.getInstance(props);
		store = (IMAPStore)session.getStore("imap"); // 使用imap会话机制,连接服务器
		store.connect(userName, passWord);
		folder = (IMAPFolder) store.getFolder("INBOX"); // 收件箱
		folder.open(Folder.READ_WRITE);
		Message[] messages = folder.getMessages();
		System.out.println("邮件数量: " + messages.length);
		return messages;
	}
	
	/**
	 * close current folder
	 */
	public static void closeFolder(){
		try {
			if(folder != null) {
			folder.close(true);
			}
			if(store!=null) {
			store.close();
			}
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}

}

 

关于JavaMail的实现方式

标签:

原文地址:http://www.cnblogs.com/codeydt/p/5168020.html

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