分享给设置自定义邮箱发送工资条源码

来源:互联网 发布:百度网络推广做什么的 编辑:程序博客网 时间:2024/04/27 17:53

分享给设置自定义邮箱发送工资条源码:

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);elseprop.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、创建sessionSession 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);}}



0 0