分享給設置自定義郵箱發送工資條源碼

分享給設置自定義郵箱發送工資條源碼:

1、SendEmail.java

package com.prochanges.mail;

import java.awt.Container;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.filechooser.FileNameExtensionFilter;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

/**
 * @author CodeCracker
 */
@SuppressWarnings("serial")
public class SendEmail extends JFrame {
	private JTextField filePathTextField;
	private JButton openFileBtn;
	private JButton sendBtn;
	private JFileChooser jfc;
	private JScrollPane scrollPane;
	private JTextArea logTextArea;

	public SendEmail() {
		initComponents();
	}

	private void onClickOpenFileBtn(ActionEvent e) {
		jfc.showDialog(new JLabel(), "選擇文件");
		File file = jfc.getSelectedFile();
		if (null != file) {
			if (file.isDirectory()) {
				showMsg("請選擇文件...");
				// System.out.println("文件夾:" + file.getAbsolutePath());
			} else if (file.isFile()) {
				filePathTextField.setText(file.getAbsolutePath());
				// System.out.println("文件:" + file.getAbsolutePath());
			}

		}
	}

	private String getStringCellValue(HSSFCell cell) {
		String strCell = "";
		switch (cell.getCellType()) {
		case HSSFCell.CELL_TYPE_STRING:
			strCell = cell.getStringCellValue();
			break;
		case HSSFCell.CELL_TYPE_NUMERIC:
			strCell = String.valueOf(cell.getNumericCellValue());
			break;
		case HSSFCell.CELL_TYPE_BOOLEAN:
			strCell = String.valueOf(cell.getBooleanCellValue());
			break;
		case HSSFCell.CELL_TYPE_BLANK:
			strCell = "";
			break;
		default:
			strCell = "";
			break;
		}
		if (strCell.equals("") || strCell == null) {
			return "";
		}
		if (cell == null) {
			return "";
		}
		return strCell;
	}

	private Properties loadFile(String path) {
		Properties prop = null;
		try {
			BufferedInputStream inBuff = new BufferedInputStream(new FileInputStream(path));
			prop = new Properties();
			if (path.endsWith(".xml"))
				prop.loadFromXML(inBuff);
			else
				prop.load(inBuff);
			inBuff.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return prop;
	}

	private MimeMessage createSimpleMail(Session session, String subject, String from, String to, String content) throws Exception {
		// 創建郵件對象
		MimeMessage message = new MimeMessage(session);
		// 指明郵件的發件人
		message.setFrom(new InternetAddress(from));
		// 指明郵件的收件人,現在發件人和收件人是一樣的,那就是自己給自己發
		message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
		// 郵件的標題
		message.setSubject(subject);
		// 郵件的文本內容
		message.setContent(content, "text/html;charset=UTF-8");
		// 返回創建好的郵件對象
		return message;
	}

	private boolean sendMsg(Transport ts, MimeMessage message) {
		try {
			ts.sendMessage(message, message.getAllRecipients());
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	private void onClickSendBtn(ActionEvent e) {
		HSSFWorkbook wb = null;
		try {
			wb = new HSSFWorkbook(new FileInputStream(filePathTextField.getText()));
			HSSFSheet sheet = wb.getSheetAt(0);
			int rowCt = sheet.getLastRowNum();
			if (rowCt > 1) {
				int colCt = sheet.getRow(rowCt - 1).getLastCellNum();
				String subject = sheet.getRow(0).getCell(0).getStringCellValue();
				StringBuffer sbHtml = new StringBuffer(
						"<style type='text/css'>table.gridtable{font-family:verdana,arial,sans-serif;font-size:12px;color:#333333;border-width:1px;border-color:#666666;border-collapse:collapse}table.gridtable th{border-width:1px;padding:8px;border-style:solid;border-color:#666666;background-color:#dedede}table.gridtable td{border-width:1px;padding:8px;border-style:solid;border-color:#666666;background-color:#ffffff}</style>");
				sbHtml.append("<br><table class='gridtable'><tr><th align='center' colspan=");
				sbHtml.append(colCt);
				sbHtml.append("><b><font size=4>");
				sbHtml.append(subject);
				sbHtml.append("</font></b></th></tr>");
				sbHtml.append("<tr>");
				for (int j = 0; j < colCt; j++) {
					String columName = sheet.getRow(1).getCell(j).getStringCellValue();
					sbHtml.append("<th>");
					sbHtml.append(columName);
					sbHtml.append("</th>");
				}
				sbHtml.append("</tr>");
				Properties config = loadFile("config.xml");
				String host = config.getProperty("host");
				String from = config.getProperty("from");
				String username = config.getProperty("username");
				String password = config.getProperty("password");
				int emailIdx = Integer.valueOf(config.getProperty("emailIdx"));
				int showIdx = Integer.valueOf(config.getProperty("showIdx"));
				Properties prop = new Properties();
				prop.setProperty("mail.host", host);
				prop.setProperty("mail.transport.protocol", "smtp");
				prop.setProperty("mail.smtp.auth", "true");
				// 使用JavaMail發送郵件的5個步驟
				// 1、創建session
				Session session = Session.getInstance(prop);
				// 開啓Session的debug模式,這樣就可以查看到程序發送Email的運行狀態
				//session.setDebug(true);
				// 2、通過session得到transport對象
				Transport ts = session.getTransport();
				// 3、使用郵箱的用戶名和密碼連上郵件服務器,發送郵件時,發件人需要提交郵箱的用戶名和密碼給smtp服務器,用戶名和密碼都通過驗證之後才能夠正常發送郵件給收件人。
				ts.connect(host, username, password);
				// 4、創建郵件
				for (int i = 2; i <= rowCt; i++) {
					StringBuffer content = new StringBuffer(sbHtml.toString());
					content.append("<tr>");
					for (int j = 0; j < colCt; j++) {
						String columName = getStringCellValue(sheet.getRow(i).getCell(j));
						content.append("<td>");
						content.append(columName);
						content.append("</td>");
					}
					content.append("</tr>");
					content.append("</table> ");
					String to = getStringCellValue(sheet.getRow(i).getCell(emailIdx)).trim();
					// logTextArea.setText(logTextArea.getText()+"正在發送郵件...."+to+"\n");
					MimeMessage message = new MimeMessage(session);
					// 指明郵件的發件人
					message.setFrom(new InternetAddress(from));
					// 指明郵件的收件人,現在發件人和收件人是一樣的,那就是自己給自己發
					message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
					// 郵件的標題
					message.setSubject(subject);
					// 郵件的文本內容
					Multipart mp = new MimeMultipart();
					BodyPart bp = new MimeBodyPart();
					bp.setContent("" + content, "text/html;charset=GBK");
					mp.addBodyPart(bp);
					message.setContent(mp);
					String bfb = (i + 1 - 2) + "/" + (rowCt - 1);
					boolean isSuc = sendMsg(ts, message);
					String logMsg = "";
					if (isSuc) {
						logMsg = getStringCellValue(sheet.getRow(i).getCell(showIdx)) + "\t工資條已經發送成功!【" + bfb + "】\n";
					} else {
						logMsg = getStringCellValue(sheet.getRow(i).getCell(showIdx)) + "\t工資條已經發送失敗!【" + bfb + "】\n";
					}
					logTextArea.setText(logTextArea.getText() + logMsg);
				}
				ts.close();
			} else {
				showMsg("沒有讀到數據!!!");
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}

	}

	private void showMsg(String msg) {
		JOptionPane.showMessageDialog(null, msg, "溫馨提示", JOptionPane.PLAIN_MESSAGE);
	}

	private void initComponents() {
		filePathTextField = new JTextField();
		openFileBtn = new JButton();
		sendBtn = new JButton();
		jfc = new JFileChooser();
		scrollPane = new JScrollPane();
		logTextArea = new JTextArea();
		jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
		jfc.setAcceptAllFileFilterUsed(false);
		FileNameExtensionFilter filter = new FileNameExtensionFilter("Excel 97-2003 工作簿(*.xls)", "xls");
		jfc.setFileFilter(filter);
		filePathTextField.setEnabled(false);
		logTextArea.setEditable(false);
		// jfc.addChoosableFileFilter();
		// ======== this ========
		Container contentPane = getContentPane();
		contentPane.setLayout(null);
		contentPane.add(filePathTextField);
		filePathTextField.setBounds(25, 25, 277, 23);
		// --scrollPane
		{
			scrollPane.setViewportView(logTextArea);
		}
		contentPane.add(scrollPane);
		scrollPane.setBounds(25, 65, 435, 200);
		// ---- button1 ----
		openFileBtn.setText("選擇文件");
		contentPane.add(openFileBtn);
		openFileBtn.setBounds(new Rectangle(new Point(307, 22), openFileBtn.getPreferredSize()));
		openFileBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				onClickOpenFileBtn(e);
			}
		});
		sendBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (filePathTextField.getText().toString().equals("")) {
					showMsg("請選擇Excel文件");
					return ;
				}
				File temp=new File(filePathTextField.getText().toString());
				if (!temp.isFile()) {
					showMsg("你選擇的不是個文件");
					return ;
				}
				if (!temp.exists()) {
					showMsg("你選擇文件不存在");
					return ;
				}
				sendBtn.setEnabled(false);
				logTextArea.setText("");
				onClickSendBtn(e);
				sendBtn.setEnabled(true);
			}
		});
		// ---- button2 ----
		sendBtn.setText("發送");
		contentPane.add(sendBtn);
		sendBtn.setBounds(new Rectangle(new Point(400, 22), sendBtn.getPreferredSize()));

		{
			Dimension preferredSize = new Dimension();
			for (int i = 0; i < contentPane.getComponentCount(); i++) {
				Rectangle bounds = contentPane.getComponent(i).getBounds();
				preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
				preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
			}
			Insets insets = contentPane.getInsets();
			preferredSize.width += insets.right;
			preferredSize.height += insets.bottom;
			contentPane.setMinimumSize(preferredSize);
			contentPane.setPreferredSize(preferredSize);
		}
		pack();
		setTitle("郵件發送");
		setResizable(false);
		setLocationRelativeTo(getOwner());
	}
}


2、Entrance.java

package com.prochanges.mail;

public class Entrance {
	public static void main(String[] args) {
		SendEmail ssForm = new SendEmail();
		ssForm.setVisible(true);
		ssForm.setSize(490, 320);
	}
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章