java swing发送邮件(界面比较丑。。。)

package com.lubansoft.email.swing;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
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.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.text.JTextComponent;

public class EmailClient extends JFrame{
	private static final long serialVersionUID = 1L;
	private String subject ;
	private final String FILE_PATH = "userInfo.properties";
	
	//“今日工作”
	private JLabel label_first;
	private JTextArea area_first;
	private JTextArea area_relative_person_first;
	private JTextArea area_time_cost_first;
	
	private JButton send_default_button;
	private JButton send_specify_button;
	private JButton updateUserInfo_button;
	private JScrollPane scrollPane;
	private Container content;
	private GridBagConstraints gbc_la_lineNo = null;
	private final int ROWS = 3;
	private final int JOB_COLS = 20;
	private final int COLS = 8;
	private String username ;
	private String password;
	private String server_host ;
	private String show_name;
	private String recipient;
	private UserInfoFrame userInfoFrame = null; 
	private SimpleDateFormat format = null;
	private EmailActionListener emailActionListener;
	private Date date;
	private JTextField field_xplanner;
	private int width = 1400;
	private int height = 530;
	private String[] top_titles ;
	private String[] bottom_titles ;
	private JPanel panel ;
	private Map> map= null;
	private List rowComponents = null;
	private int top_row_count = 2;
	private int bottom_row_count = 2;
	private String[] rowNum;
	
	/**
	 * 
	 * 

Discription:EmailClient类的构造方法

* @coustructor 方法. */ public EmailClient(){ this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setTitle("工作日志邮件"); content = this.getContentPane(); initComponent(content); this.pack(); setPositionCenter(); this.setVisible(true); } 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); } private void initComponent(Container content) { panel = new JPanel(); content.setLayout(new BorderLayout()); GridBagLayout gridBagLayout = new GridBagLayout(); panel.setLayout(gridBagLayout); add(panel, BorderLayout.CENTER); /** * 通过循环来添加所有的组件 */ top_titles = new String[]{"今日工作:","系统化工作:"}; rowNum = new String[]{"一","二","三","四","五","六"}; for(int i=0;iDiscription:每次添加一行元素

* @author: * @param titles标签内容 * @param panel要添加的容器 * @param row添加到哪一行 * @update:[日期YYYY-MM-DD] [更改人姓名] * @return void */ public void addCellComponent(Container panel,String sequence,String[] titles,int row){ rowComponents = new ArrayList(); label_first = new JLabel(sequence); gbc_la_lineNo = new GridBagConstraints(); gbc_la_lineNo.anchor = GridBagConstraints.EAST; gbc_la_lineNo.insets = new Insets(0, 5, 5, 5); gbc_la_lineNo.gridx = 0; gbc_la_lineNo.gridy = row; panel.add(label_first, gbc_la_lineNo); JLabel index = new JLabel(titles[0]); gbc_la_lineNo = new GridBagConstraints(); gbc_la_lineNo.anchor = GridBagConstraints.EAST; gbc_la_lineNo.insets = new Insets(0, 5, 5, 5); gbc_la_lineNo.gridx = 1; gbc_la_lineNo.gridy = row; panel.add(index, gbc_la_lineNo); area_first = new JTextArea(); GridBagConstraints constraints = new GridBagConstraints(); constraints.anchor = GridBagConstraints.WEST; constraints.insets = new Insets(0, 5, 5, 5); constraints.gridx = 2; constraints.gridy = row; area_first.setColumns(JOB_COLS); area_first.setRows(ROWS); area_first.setLineWrap(true); scrollPane = new JScrollPane(area_first); panel.add(scrollPane, constraints); rowComponents.add(area_first); label_first = new JLabel("相关人:"); gbc_la_lineNo = new GridBagConstraints(); gbc_la_lineNo.anchor = GridBagConstraints.WEST; gbc_la_lineNo.insets = new Insets(0, 5, 5, 5); gbc_la_lineNo.gridx = 3; gbc_la_lineNo.gridy = row; panel.add(label_first, gbc_la_lineNo); area_relative_person_first = new JTextArea(ROWS,COLS); constraints = new GridBagConstraints(); constraints.anchor = GridBagConstraints.WEST; constraints.insets = new Insets(0, 5, 5, 5); constraints.gridx = 4; constraints.gridy = row; scrollPane = new JScrollPane(area_relative_person_first); panel.add(scrollPane, constraints); rowComponents.add(area_relative_person_first); label_first = new JLabel("用时:"); gbc_la_lineNo = new GridBagConstraints(); gbc_la_lineNo.anchor = GridBagConstraints.WEST; gbc_la_lineNo.insets = new Insets(0, 5, 5, 5); gbc_la_lineNo.gridx = 5; gbc_la_lineNo.gridy = row; panel.add(label_first, gbc_la_lineNo); area_time_cost_first = new JTextArea(ROWS,COLS); constraints = new GridBagConstraints(); constraints.anchor = GridBagConstraints.WEST; constraints.insets = new Insets(0, 5, 5, 5); constraints.gridx = 6; constraints.gridy = row; scrollPane = new JScrollPane(area_time_cost_first); panel.add(scrollPane, constraints); rowComponents.add(area_time_cost_first); //右边的部分 index = new JLabel(titles[1]); gbc_la_lineNo = new GridBagConstraints(); gbc_la_lineNo.anchor = GridBagConstraints.EAST; gbc_la_lineNo.insets = new Insets(0, 5, 5, 5); gbc_la_lineNo.gridx = 7; gbc_la_lineNo.gridy = row; panel.add(index, gbc_la_lineNo); area_first = new JTextArea(); constraints = new GridBagConstraints(); constraints.anchor = GridBagConstraints.WEST; constraints.insets = new Insets(0, 5, 5, 5); constraints.gridx = 8; constraints.gridy = row; area_first.setColumns(JOB_COLS); area_first.setRows(ROWS); area_first.setLineWrap(true); scrollPane = new JScrollPane(area_first); panel.add(scrollPane, constraints); rowComponents.add(area_first); label_first = new JLabel("相关人:"); gbc_la_lineNo = new GridBagConstraints(); gbc_la_lineNo.anchor = GridBagConstraints.WEST; gbc_la_lineNo.insets = new Insets(0, 5, 5, 5); gbc_la_lineNo.gridx = 9; gbc_la_lineNo.gridy = row; panel.add(label_first, gbc_la_lineNo); area_relative_person_first = new JTextArea(ROWS,COLS); constraints = new GridBagConstraints(); constraints.anchor = GridBagConstraints.WEST; constraints.insets = new Insets(0, 5, 5, 5); constraints.gridx = 10; constraints.gridy = row; scrollPane = new JScrollPane(area_relative_person_first); panel.add(scrollPane, constraints); rowComponents.add(area_relative_person_first); label_first = new JLabel("用时:"); gbc_la_lineNo = new GridBagConstraints(); gbc_la_lineNo.anchor = GridBagConstraints.WEST; gbc_la_lineNo.insets = new Insets(0, 5, 5, 5); gbc_la_lineNo.gridx = 11; gbc_la_lineNo.gridy = row; panel.add(label_first, gbc_la_lineNo); area_time_cost_first = new JTextArea(ROWS,COLS); constraints = new GridBagConstraints(); constraints.anchor = GridBagConstraints.WEST; constraints.insets = new Insets(0, 5, 5, 5); constraints.gridx = 12; constraints.gridy = row; scrollPane = new JScrollPane(area_time_cost_first); panel.add(scrollPane, constraints); rowComponents.add(area_time_cost_first); if(map == null){ map = new HashMap>(); } map.put(row, rowComponents); } /** * 加载用户信息配置文件 */ 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"); server_host = properties.getProperty("server_host"); show_name = properties.getProperty("show_name"); subject = properties.getProperty("subject"); recipient = properties.getProperty("recipient"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * * Created on 2013-4-23 *

Discription:往subject后面自动添加日期

* @author: * @update:[日期YYYY-MM-DD] [更改人姓名] * @return String */ public String getSubject(String subject,Date date){ subject += "("; format = new SimpleDateFormat("yyyy-MM-dd"); subject += format.format(date == null ? new Date() : date); Calendar calendar = Calendar.getInstance(); if(date != null){ calendar.setTime(date); } int week = calendar.get(Calendar.DAY_OF_WEEK)-1; switch(week){ case 1: subject+="星期一";break; case 2: subject+="星期二";break; case 3: subject+="星期三";break; case 4: subject+="星期四";break; case 5: subject+="星期五";break; case 6: subject+="星期六";break; case 0: subject+="星期日";break; } subject += ")"; return subject; } public static void main(String[] args) { new EmailClient(); } class EmailActionListener implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { try { if("send_email".equals(e.getActionCommand())){ sendEmail("default"); }else if("updateUserInfo".equals(e.getActionCommand())){ EmailClient.this.setVisible(false); getUserInfoFrame().setVisible(true); getUserInfoFrame().initTextValue(); return ; }else if("top_add".equals(e.getActionCommand())){ if(top_row_count >=6){ return; } addCellComponent(panel, rowNum[top_row_count], top_titles, top_row_count+1); height += 30; EmailClient.this.setSize(width,height); setPositionCenter(); EmailClient.this.validate(); top_row_count++; } else if("bottom_add".equals(e.getActionCommand())){ if(bottom_row_count >=6){ return; } addCellComponent(panel, rowNum[bottom_row_count], bottom_titles, bottom_row_count+7); EmailClient.this.setSize(EmailClient.this.getWidth(), EmailClient.this.getHeight()+30); EmailClient.this.validate(); bottom_row_count++; } } catch (Exception e1) { e1.printStackTrace(); } } } /** * * Created on 2013-4-22 *

Discription:点击邮件时调用的方法

* @author: * @update:[日期YYYY-MM-DD] [更改人姓名] * @return void */ public void sendEmail(String dateType) throws Exception{ boolean userInfo_ok = false; loadUserInfo(); if(username != null && !"".equals(username.trim())){ if(password != null && !"".equals(password.trim())){ if(server_host != null && !"".equals(server_host.trim())){ if(subject != null && !"".equals(subject.trim())){ if(recipient != null && !"".equals(recipient.trim())){ userInfo_ok = true; if(show_name == null || "".equals(show_name.trim())){ show_name = username; } } } } } } if(!userInfo_ok){ JOptionPane.showMessageDialog(null, "您的邮箱信息不完整,请先填写邮箱信息", null, JOptionPane.INFORMATION_MESSAGE); this.setVisible(false); getUserInfoFrame().setVisible(true); getUserInfoFrame().initTextValue(); return ; } Properties props = new Properties(); props.setProperty("mail.smtp.auth", "true"); props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.host", server_host); Session session = Session.getInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username,password); } } ); session.setDebug(true); MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress("\"" + MimeUtility.encodeText(show_name) + "\" <" + username + ">")); subject = getSubject(subject,date); msg.setSubject(subject); msg.setRecipients(RecipientType.TO, InternetAddress.parse(recipient)); msg.setContent(getHTMLPart(), "text/html;charset=utf-8"); // Transport.send(msg); //发送邮件 msg.saveChanges(); OutputStream ips = new FileOutputStream("e:/demo3.eml");//保存到本地,查看显示效果 msg.writeTo(ips); ips.close(); JOptionPane.showMessageDialog(null, "邮件发送成功", null, JOptionPane.INFORMATION_MESSAGE); System.exit(0); } /** * * Created on 2013-4-19 *

Discription:将用户的输入信息插入到html表格中,并返回该html文件的字符串表示

* @author: * @update:[日期YYYY-MM-DD] [更改人姓名] * @return String */ public String getHTMLPart(){ String[][] content = new String[12][6]; for(int i=0;i<12;i++){ Arrays.fill(content[i], " "); } Component component = null; int index = -1; for(Map.Entry> row: map.entrySet()){ rowComponents = row.getValue(); index = row.getKey(); for(int i = 0;iDiscription:获得userinfoframe对象

* @author: * @update:[日期YYYY-MM-DD] [更改人姓名] * @return UserInfoFrame */ public UserInfoFrame getUserInfoFrame(){ if(userInfoFrame == null){ userInfoFrame = new UserInfoFrame(); return userInfoFrame; }else{ return userInfoFrame; } } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } /** * *

类名称:UserInfoFrame

*

类描述: 邮箱信息frame

*

创建人: *

创建时间:2013-4-22 下午01:47:57

*

修改人:Administrator

*

修改时间:2013-4-22 下午01:47:57

*

修改备注:

*

@version

* */ 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_host = new JLabel(" 邮箱服务器:"); private JLabel label_show_name = new JLabel(" 邮箱昵称:"); private JLabel label_subject= new JLabel(" 邮件主题: "); private JLabel label_recipient= new JLabel(" 收件人邮箱:"); private JTextField field_recipient = new JTextField(20); private JTextField field_subject = new JTextField(20); private JTextField field_username = new JTextField(20); private JTextField field_password = new JTextField(20); private JTextField field_server_host = new JTextField(20); private JTextField field_show_name = 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(7, 1)); jPanel = new JPanel(flow); jPanel.add(label_subject); jPanel.add(field_subject); content.add(jPanel); jPanel = new JPanel(flow); jPanel.add(label_username); jPanel.add(field_username); content.add(jPanel); jPanel = new JPanel(flow); jPanel.add(label_recipient); jPanel.add(field_recipient); 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_host); jPanel.add(field_server_host); content.add(jPanel); jPanel = new JPanel(flow); jPanel.add(label_show_name); jPanel.add(field_show_name); 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_subject.setText(subject); field_username.setText(username); field_password.setText(password); field_server_host.setText(server_host); field_show_name.setText(show_name); field_recipient.setText(recipient); } 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(); server_host = field_server_host.getText().trim(); show_name = field_show_name.getText().trim(); subject = field_subject.getText().trim(); recipient = field_recipient.getText().trim(); if("".equals(show_name)){ show_name = username; } if("".equals(username) || "".equals(password) || "".equals(server_host) || "".equals(subject) || "".equals(recipient)){ JOptionPane.showMessageDialog(null, "请将信息填写完整", "", JOptionPane.ERROR_MESSAGE); }else{ saveUserInfo(); JOptionPane.showMessageDialog(null, "保存成功", null, JOptionPane.INFORMATION_MESSAGE); UserInfoFrame.this.setVisible(false); EmailClient.this.setVisible(true); } }else if("reset".equals(e.getActionCommand())){ reset(); }else if("goEmail".equals(e.getActionCommand())){ UserInfoFrame.this.setVisible(false); EmailClient.this.setVisible(true); } } catch (Exception e1) { e1.printStackTrace(); } } /** * * Created on 2013-4-22 *

Discription:保存用户信息

* @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("server_host", "".equals(server_host.trim()) ? properties.getProperty("server_host") : server_host); properties.setProperty("show_name", "".equals(show_name.trim()) ? properties.getProperty("show_name") : show_name); properties.setProperty("subject", "".equals(subject.trim()) ? properties.getProperty("subject") : subject); properties.setProperty("recipient", "".equals(recipient.trim()) ? properties.getProperty("recipient") : recipient); 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_subject.setText(""); field_username.setText(""); field_password.setText(""); field_server_host.setText(""); field_show_name.setText(""); field_recipient.setText(""); } } } }

 

另外一个类:

package com.lubansoft.email.swing;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class EmailUtils {


	
	public static String getHtmlPart(String[][] content,String xplanner){
		String html = "" + 
"" + 
  "" + 
    "Email.html" + 
    "" + 
    "" + 
    "" + 
    "" + 
  "" + 
  "" + 
  "编辑Xplanner : " + xplanner +
    "" + makeHTML(content)+
    "
" + "" + ""; File file = null; FileOutputStream out = null; ByteArrayInputStream in = null; try { file = new File("e:email.html"); if(!file.exists()){ file.createNewFile(); } out = new FileOutputStream(file); in = new ByteArrayInputStream(html.getBytes("utf-8")); byte[] b = new byte[1024]; int i = -1; while((i = in.read(b)) != -1){ out.write(b, 0, i); } out.flush(); } catch (Exception e) { e.printStackTrace(); }finally{ try { in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } return html; } /** * * Created on 2013-4-25 *

Discription:将数组转化为html代码

* @author: * @update:[日期YYYY-MM-DD] [更改人姓名] * @return String */ public static String makeHTML(String[][] content){ String result = ""; int length = content.length; for(int i=0;i序号" + "今日工作" + "相关人" + "用时" + "序号" + "系统化工作(流程、新技术、学习)" + "相关人" + "用时" + "" ; }else if(i == 6){ result += "" + "序号" + "配合事项" + "相关人" + "用时" + "序号" + "明日计划" + "相关人" + "用时" + ""; } result += "" ; if(i<6){ result += ""+(i+1)+"" ; }else{ result += ""+(i-5)+"" ; } result += "" + content[i][0] + "" + "" + content[i][1] + "" + "" + content[i][2] + "" ; if(i<6){ result += ""+(i+1)+"" ; }else{ result += ""+(i-5)+"" ; } result += "" + content[i][3] + "" + "" + content[i][4] + "" + "" + content[i][5] + "" + ""; } return result; } }

 

你可能感兴趣的:(java基础)