swing 接收邮件

package com.IEthing.util;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeMessage;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLFrameHyperlinkEvent;

public class EmailReader extends JFrame implements HyperlinkListener{
	private static final long serialVersionUID = 1L;
	private Container content;
	private int width = 1100;
	private int height = 800;
	private EmailReaderActionListener emailReaderActionListener;
	private ReceiveMail receive;
	private JPanel mail_list;//mail list
	private JPanel center;
	private JPanel bottom;
	private JEditorPane editorPane = null;
	private JScrollPane scrollPane = null;
	private List<ReceiveMail> emails = null;
	private JPanel mailHead;
	private JPanel mailBody;
	private int begin_index = 0;
	private boolean previous = false;
	private boolean next = false;
	private int total_page = 1;
	private int current_page = 1;
	private int page_size = 10;
	private String pop3_host;
	private String username;
	private String password;
	private UserInfoFrame userInfoFrame;
	private final String FILE_PATH = "userInfo2.properties";
	
	public EmailReader(){
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setTitle("接收邮件");
		content = this.getContentPane();
		initComponent(content);
		this.pack();
		setPositionCenter();
		this.setVisible(true);
	}
	private void initComponent(Container content) {
		createPanels();
		JButton receiveEmail = new JButton(" 开始接收邮件 ");
		JButton editUserInfo = new JButton(" 修改账户信息 ");
		receiveEmail.setActionCommand("receiveEmail");
		editUserInfo.setActionCommand("editUserInfo");
		emailReaderActionListener = new EmailReaderActionListener();
		receiveEmail.addActionListener(emailReaderActionListener);
		editUserInfo.addActionListener(emailReaderActionListener);
		bottom.add(receiveEmail);
		bottom.add(editUserInfo);
	}
	
	private void createPanels() {
		if(mail_list == null){
			mail_list = new JPanel();
		}
		if(center == null){
			center = new JPanel(new BorderLayout());
		}
		if(mailHead == null){
			mailHead = new JPanel();
		}
		if(mailBody == null){
			mailBody = new JPanel(new BorderLayout());
		}
		if(bottom == null){
			bottom = new JPanel();
		}
		content.setLayout(new BorderLayout());
		JPanel big = new JPanel();
		big.setLayout(new GridLayout(1,2));
		JPanel panel_1 = new JPanel(new BorderLayout());
		JPanel panel_2 = new JPanel(new BorderLayout());
		
		big.add(panel_1);
		big.add(panel_2);
		
		content.add(big,BorderLayout.CENTER);
		content.add(bottom,BorderLayout.SOUTH);
		panel_1.add(mailHead,BorderLayout.NORTH);
		panel_1.add(mailBody,BorderLayout.CENTER);
		
		panel_2.add(mail_list,BorderLayout.NORTH);
	}

	public class EmailReaderActionListener implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent e) {
			if("receiveEmail".equals(e.getActionCommand().trim())){
				try {
					emails = retrieveEmail();//去邮箱服务器获取邮件
					saveToFile();//保存文件到本地
					receiveEmail();
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}else if("editUserInfo".equals(e.getActionCommand())){
				EmailReader.this.setVisible(false);
				getUserInfoFrame().setVisible(true);
			}
		}
	}
	
	public void saveToFile() throws Exception{
		File temp = null;
		FileOutputStream out = null;
		if(emails == null || emails.size() == 0){
			return ;
		}
		for(int i=0;i<emails.size();i++){
  		  temp = new File("e:/tempHTML/");
  		  if(!temp.exists()){
  			  temp.mkdirs();
  		  }
    	  temp = new File("e:/tempHTML/tempFile_"+i+".html");
    	  if(! temp.exists()){
    		  temp.createNewFile();
    	  }
    	  out = new FileOutputStream(temp);
    	  out.write(((String)emails.get(i).getMimeMessage().getContent()).getBytes("utf-8"));
    	  out.flush();
	  }
  	  if(out != null){
	     out.close();
	  }
	}
	
	//超链监听器,处理对超级链接的点击事件,但对按钮的点击还捕获不到  
	public void hyperlinkUpdate(HyperlinkEvent e)  
	   {  
	      if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED)  
	      {  
	         JEditorPane pane = (JEditorPane) e.getSource();  
	         if (e instanceof HTMLFrameHyperlinkEvent)  
	         {  
	            HTMLFrameHyperlinkEvent evt = (HTMLFrameHyperlinkEvent) e;  
	            HTMLDocument doc = (HTMLDocument) pane.getDocument();  
	            doc.processHTMLFrameHyperlinkEvent(evt);  
	         }  
	         else  
	         {  
	            try  
	            {  
	               pane.setPage(e.getURL());  
	            }  
	            catch (Throwable t)  
	            {  
	               t.printStackTrace();  
	            }  
	         }  
	      }  
	   } 
	
	public void receiveEmail() throws Exception{
	      File temp = null;
	      if(emails != null && emails.size()>0){//如果邮箱中邮件不为空,先将内容(html)存到本地
    		  addMailBody((current_page-1)*page_size);
    		  addMailHeadComponent(emails.get((current_page-1)*page_size));
	      }else{
	    	  temp = new File("e:/tempHTML");
	    	  if(temp.exists()){
	    		  temp.delete();
	    	  }
	    	  current_page = 1;
	    	  total_page = 1;
	    	  mailHead.removeAll();
	    	  mailBody.removeAll();
	      }
	     addMailList(emails);
         this.validate();
	}
	
	public void addMailBody(int i) throws MessagingException, Exception{
		 editorPane = new JEditorPane();  
	     scrollPane = new JScrollPane(editorPane);  
	     mailBody.removeAll();
	     mailBody.add(scrollPane, BorderLayout.CENTER);  
	     editorPane.setContentType("text/html");  
	     editorPane.setEditable(false);  
	     editorPane.addHyperlinkListener(this);  
         editorPane.setPage("file:///e:/tempHTML/tempFile_" + i + ".html"); 
         this.validate();
	}
	
	JLabel mail_item = null;
	JPanel mail_row = null;
	JPanel detail_button_panel = null;
	ReceiveMail mail = null;
	JButton email_detail = null;
	EmailDetailListener detailListener ;
	private void addMailList(List<ReceiveMail> emails) throws MessagingException, Exception {
		mail_list.removeAll();
		this.validate();
		int length = emails == null ? 0 : emails.size();
		mail_list.setLayout(new GridLayout(page_size+2, 1));
		
		FlowLayout flow = new FlowLayout(FlowLayout.LEFT);
		detailListener = new EmailDetailListener();
		mail_row = new JPanel(new GridLayout(1, 4));
		mail_item= new JLabel("收件人");
		mail_row.add(mail_item);
		mail_item= new JLabel("邮件主题");
		mail_row.add(mail_item);
		mail_item= new JLabel("发送时间");
		mail_row.add(mail_item);
		mail_item= new JLabel("操作");
		mail_row.add(mail_item);
		mail_list.add(mail_row);
		for(int i=begin_index;i<length && i<begin_index+page_size;i++){
			mail_row = new JPanel(new GridLayout(1, 4));
			mail = emails.get(i);
			mail_item= new JLabel(mail.getMailAddress("TO"));
			mail_row.add(mail_item);
			mail_item= new JLabel(mail.getSubject());
			mail_row.add(mail_item);
			mail_item= new JLabel(mail.getSentDate());
			mail_row.add(mail_item);
			email_detail = new JButton("查看该邮件");
			email_detail.setActionCommand(""+i);
			email_detail.addActionListener(detailListener);
			detail_button_panel = new JPanel(flow);
			detail_button_panel.add(email_detail);
			mail_row.add(detail_button_panel);
			mail_list.add(mail_row);
		}
		if(emails == null || length == 0){
			mail_row = new JPanel(new GridLayout(1, 8));
			mail_item= new JLabel("当前没有邮件");
			mail_row.add(mail_item);
			mail_list.add(mail_row);
		}
		if(current_page > 1){
			previous = true;
		}else{
			previous = false;
		}
		if(current_page < total_page){ //说明需要分页
			next = true;
		}else{
			next = false;
		}
		if(current_page>total_page){
			current_page = total_page;
		}
		if(current_page < 1){
			current_page = 1;
		}
		JPanel page_panel = new JPanel();
		if(previous){
			page_panel = new JPanel();
			JButton prePage = new JButton("上一页");
			prePage.addActionListener(detailListener);
			prePage.setActionCommand("previous");
			page_panel.add(prePage);
		}
		
		if(next){ //说明需要分页
			JButton nextPage = new JButton("下一页");
			nextPage.addActionListener(detailListener);
			nextPage.setActionCommand("next");
			page_panel.add(nextPage);
		}
		JLabel pageNum_label = new JLabel("共" +  total_page + "页");
		JLabel current_page_label = new JLabel("当前第"+ current_page + "页");
		page_panel.add(pageNum_label);
		page_panel.add(current_page_label);
		mail_list.add(page_panel);
	}
	
	class EmailDetailListener implements ActionListener{
		@Override
		public void actionPerformed(ActionEvent e) {
			try {
				String selected = e.getActionCommand();
				if("previous".equals(selected)){
					begin_index -= page_size;
					current_page -= 1;
					receiveEmail();
					EmailReader.this.validate();
				}else if("next".equals(selected)){
					begin_index += page_size;
					current_page += 1;
					receiveEmail();
					EmailReader.this.validate();
				}else{
					ReceiveMail email = emails.get(Integer.parseInt(selected));
					addMailHeadComponent(email);
					addMailBody(Integer.parseInt(selected));
					EmailReader.this.validate();
				}
			} catch (NumberFormatException e1) {
				e1.printStackTrace();
			} catch (MessagingException e1) {
				e1.printStackTrace();
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
	}
	public void addMailHeadComponent(ReceiveMail mail) throws Exception{
		mailHead.removeAll();
		JLabel from = new JLabel();
		JLabel date = new JLabel();
		JLabel to = new JLabel();
		JLabel subject = new JLabel();
		from.setText("发件人 :"+mail.getFrom());
		date.setText("日期 :"+mail.getSentDate());
		to.setText("收件人 :" + mail.getMailAddress("TO"));
		subject.setText("主题 :" + mail.getSubject());
		mailHead.setLayout(new GridLayout(4, 1));
		JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
		panel.add(from);
		mailHead.add(panel);
		
		panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
		panel.add(date);
		mailHead.add(panel);
		
		panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
		panel.add(to);
		mailHead.add(panel);
		
		panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
		panel.add(subject);
		mailHead.add(panel);	
	}
	
	
	/**
	 * 
	 *  Created on 2013-4-27 
	 * <p>Discription:连接服务器获取邮件</p>
	 * @author:
	 * @update:[日期YYYY-MM-DD] [更改人姓名]
	 * @return List<ReceiveMail>
	 */
	public List<ReceiveMail> retrieveEmail(){
        try {
        	loadUserInfo();
        	boolean b = false;
        	if(pop3_host != null && ! "".equals(pop3_host.trim())){
        		if(username != null && ! "".equals(username.trim())){
        			if(password != null && ! "".equals(password.trim())){
            			b = true;
            		}
        		}
        	}
        	if(!b){
        		JOptionPane.showMessageDialog(null, "您当前邮件内容不完整,请先填写邮件内容!", null,  JOptionPane.WARNING_MESSAGE);
        		this.setVisible(false);
        		getUserInfoFrame().setVisible(true);
        		return null;
        	}
			Properties props = System.getProperties();  
			props.put("mail.smtp.auth", "true");  
			Session session = Session.getDefaultInstance(props, null);  
			session.setDebug(true);
			Store store = session.getStore("pop3");  
			store.connect(pop3_host, username, password);  
			Folder folder = store.getFolder("INBOX");  
			folder.open(Folder.READ_ONLY);  
			Message message[] = folder.getMessages();  
			int length = message.length;
			System.out.println("Messages's length: " + message.length);  
			
			total_page = length%page_size == 0 ? length/page_size : (length/page_size)+1;//总页数
			if(total_page == 0){
				total_page = 1;
				previous = false;
				next = false;
				emails = null;
				return emails;
			}
			
			emails = new ArrayList<ReceiveMail>();
			for (int i = 0; i<length; i++) {  
			    receive = new ReceiveMail((MimeMessage) message[i]);  
			    emails.add(receive);
			}
		} catch (NoSuchProviderException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}   
		return emails;
	}
	
	private void setPositionCenter() {
		Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
		int width = this.width;
		int height = this.height;
		this.setBounds((d.width - width) / 2, (d.height - height) / 2, width, height);
	}
	public static void main(String[] args) {
		new EmailReader();
	}
	public UserInfoFrame getUserInfoFrame(){
		if(userInfoFrame == null){
			userInfoFrame = new UserInfoFrame();
			return userInfoFrame;
		}else{
			return userInfoFrame;
		}
	}
	/**
	 * 加载用户信息配置文件
	 */
	public void loadUserInfo() {
		Properties properties = new Properties();
		FileInputStream in = null;
		File file = null;
		try {
			file = new File(FILE_PATH);
			if(!file.exists()){
				file.createNewFile();
			}
			in = new FileInputStream(file);
			properties.load(in);
			username = properties.getProperty("username");
			password = properties.getProperty("password");
			pop3_host = properties.getProperty("pop3_host");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 
	* <p>类名称:UserInfoFrame  </p>
	* <p>类描述:   邮箱信息frame</p>
	* <p>创建人:
	* <p>创建时间:2013-4-22 下午01:47:57   </p>
	* <p>修改人:Administrator   </p>
	* <p>修改时间:2013-4-22 下午01:47:57   </p>
	* <p>修改备注:   </p>
	*<p> @version    </p>
	*
	 */
	class UserInfoFrame extends JFrame{
		private static final long serialVersionUID = 1L;
		private JLabel label_username = new JLabel("    邮箱账户名:");
		private JLabel label_password = new JLabel("        邮箱密码:");
		private JLabel label_server_pop3_host = new JLabel("邮箱pop3服务器:");
		private JTextField field_username = new JTextField(20);
		private JTextField field_password = new JTextField(20);
		private JTextField field_server_pop3_host = new JTextField(20);
		private JButton confirm = new JButton(" 完 成 ");
		private JButton reset = new JButton(" 清 空 ");
		private JButton goEmail = new JButton(" 写邮件 ");
		JPanel jPanel = null;
		FlowLayout flow = new FlowLayout();

		
		public UserInfoFrame(){
			this.setDefaultCloseOperation(EXIT_ON_CLOSE);
			this.setTitle("邮箱账户信息");
			content = this.getContentPane();
			initUserComponent(content);
			this.pack();
			Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
			int width = 600;
			int height = 330;
			this.setBounds((d.width - width) / 2, (d.height - height) / 2, width, height);
			this.setVisible(true);
		}

		private void initUserComponent(Container content) {
			loadUserInfo(); //加载邮箱信息
			content.setLayout(new GridLayout(4, 1));
			jPanel = new JPanel(flow);
			jPanel.add(label_username);
			jPanel.add(field_username);
			content.add(jPanel);
			jPanel = new JPanel(flow);
			jPanel.add(label_password);
			jPanel.add(field_password);
			content.add(jPanel);
			jPanel = new JPanel(flow);
			jPanel.add(label_server_pop3_host);
			jPanel.add(field_server_pop3_host);
			content.add(jPanel);
			JPanel left = new JPanel();
			left.setLayout(flow);
			left.add(confirm);
			left.add(reset);
			left.add(goEmail);
			confirm.setActionCommand("confirm");
			reset.setActionCommand("reset");
			goEmail.setActionCommand("goEmail");
			goEmail.addActionListener(new EmailActionListener2());
			confirm.addActionListener(new EmailActionListener2());
			reset.addActionListener(new EmailActionListener2());
			content.add(left);
			initTextValue();
		}
		public void initTextValue(){
			field_username.setText(username);
			field_password.setText(password);
			field_server_pop3_host.setText(pop3_host);
		}
		class EmailActionListener2 implements ActionListener{
			@Override
			public void actionPerformed(ActionEvent e) {
				try {
					if("confirm".equals(e.getActionCommand())){
						username = field_username.getText().trim();
						password = field_password.getText().trim();
						pop3_host = field_server_pop3_host.getText().trim();
						if("".equals(username) || "".equals(password) || "".equals(pop3_host)){
							JOptionPane.showMessageDialog(null, "请将信息填写完整", "",  JOptionPane.ERROR_MESSAGE);
						}else{
							saveUserInfo();
							JOptionPane.showMessageDialog(null, "保存成功", null,  JOptionPane.INFORMATION_MESSAGE);
							UserInfoFrame.this.setVisible(false);
							mail_list.removeAll();
							mail_list.add(new JLabel("请点击 '开始接收邮件' "));
							EmailReader.this.validate();
							EmailReader.this.setVisible(true);
						}
					}else if("reset".equals(e.getActionCommand())){
						reset();
					}else if("goEmail".equals(e.getActionCommand())){
						UserInfoFrame.this.setVisible(false);
						EmailReader.this.setVisible(true);
					}
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}

			/**
			 * 
			 *  Created on 2013-4-22 
			 * <p>Discription:保存用户信息</p>
			 * @author:
			 * @update:[日期YYYY-MM-DD] [更改人姓名]
			 * @return void
			 */
			private void saveUserInfo() {
				FileInputStream in = null;
				FileOutputStream out = null;
				Properties properties = null;
				File file = new File(FILE_PATH);
				try {
					if(file.exists()){
						file.delete();
					}
					file.createNewFile();
					in = new FileInputStream(FILE_PATH);
					properties = new Properties();
					properties.load(in);
					properties.setProperty("username", "".equals(username.trim()) ? properties.getProperty("username") : username);
					properties.setProperty("password", "".equals(password.trim()) ? properties.getProperty("password") : password);
					properties.setProperty("pop3_host", "".equals(pop3_host.trim()) ? properties.getProperty("server_host") : pop3_host);
					out = new FileOutputStream(FILE_PATH);
					properties.store(out, "store key value");
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}finally{
					try {
						in.close();
						out.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}

			private void reset() {
				field_username.setText("");
				field_password.setText("");
				field_server_pop3_host.setText("");
			}
		}
	}
}

 

你可能感兴趣的:(java,swing,email)