2015年4月17日 星期五

java mail

package test;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

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;


public class GamMail {

private static String contentA;
private static String contentB;
private static String contentC;
private static String Listpath;
private static String ContentPath;
public  static String defultData;

public static void main(String[] args)
{
Listpath = args[0];
ContentPath = args[1];
String host = "10.0.0.0.1";
String port = "25";
System.out.println(Listpath+">>"+ContentPath);
Properties props = setProperties(host,port);
Boolean isSuccuss =  sendMail(props);
if(isSuccuss){
System.out.println("寄送成功");
}else{
System.out.println("寄送失敗");
}

}

public static boolean sendMail(Properties props)
{
try
{
//construct a mail session
Session session = Session.getDefaultInstance(props,null);
session.setDebug(false);
MimeMessage msg = new MimeMessage(session);
//讀取資料
System.out.println("讀取資料");
Map> mailAddressMaps = readSenderData();

Set mapkey = mailAddressMaps.keySet();
System.out.println("準備寄送");
for(String key:mapkey){
System.out.println("寄送信件"+key+"類別");
//[0]寄件者名,[1]寄件者MAIL,[2]收件者MAIL,[3]信件主旨,[4]信件類型,[5]替換代碼
defultData = "inputData";
List addresslist = mailAddressMaps.get(key);
for(String[] addressContent:addresslist){
//讀取信件內容
String content = readContentData(key,addressContent[4],defultData);
//設定主旨
msg.setSubject(addressContent[3]);
//設定寄件人
msg.setFrom(new InternetAddress(addressContent[1],addressContent[0]));
//設定送信時間
msg.setSentDate(new Date());
//設定收件人
System.out.println("寄送信件至 :"+addressContent[2]);
InternetAddress[] address = InternetAddress.parse(addressContent[2],false);
msg.setRecipients(Message.RecipientType.TO,address);
//設定信件內容
MimeBodyPart mbp = new MimeBodyPart();
mbp.setContent(content,"text/html; charset=utf8");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(mbp);
msg.setContent(multipart);
Transport.send(msg);
}

}
return true;
}
catch(Exception e){
e.printStackTrace();
return false;
}
}


public static Properties setProperties(String host,String port){
Properties props = new Properties();
props.put("mail.host", host);
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.port", port);
props.put("mail.smtp.auth", false);
return props;
}

public static Map> readSenderData(){
Map> lineMap = new HashMap>();
String str = null;
try {
//分類
List dataListA = new ArrayList();
List dataListB = new ArrayList();
List dataListC = new ArrayList();
// Listpath = "D:/廖哥需求/21.社交工程寄mail/範例名單A.csv";
FileInputStream fr = new FileInputStream(Listpath);
BufferedReader br = new BufferedReader(new InputStreamReader(fr,"Big5"));
int i = 0;
while((str = br.readLine()) != null){
if(i == 0){
i++;
continue;
}
String tempLineData[] = str.split("\\,");//逗號分割
if("A".equals(tempLineData[4])){
dataListA.add(tempLineData);
}else if("B".equals(tempLineData[4])){
dataListB.add(tempLineData);
}else if("C".equals(tempLineData[4])){
dataListC.add(tempLineData);
}
}
if(dataListA.size() > 0)
lineMap.put("A",dataListA);
if(dataListB.size() > 0)
lineMap.put("B",dataListB);
if(dataListC.size() > 0)
lineMap.put("C",dataListC);

} catch (Exception e) {
System.out.println(str);
e.printStackTrace();
}
return lineMap;
}

public static String readContentData(String type,String rePlaceData,String beforeData){
//之前有讀取過,就只要置換超連結內碼
if("A".equals(type) && null != getContentA() && !"".equals(contentA)){
setContentA(getContentA().replaceAll(beforeData, rePlaceData));
defultData = rePlaceData;
return getContentA();
}else if("B".equals(type) && null != getContentB() && !"".equals(contentB)){
setContentB(getContentB().replaceAll(beforeData, rePlaceData));
defultData = rePlaceData;
return getContentB();
}else if("C".equals(type) && null != getContentC() && !"".equals(contentC)){
setContentC(getContentC().replaceAll(beforeData, rePlaceData));
defultData = rePlaceData;
return getContentC();
}
String path = ContentPath+type+".txt";
// path = "D:/廖哥需求/21.社交工程寄mail/"+type+".txt";
StringBuffer contentStr = new StringBuffer();
try {
FileInputStream fr = new FileInputStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(fr,"UTF-8"));
String str = null;
while((str = br.readLine()) != null){
contentStr.append(str);
}
} catch (Exception e) {
e.printStackTrace();
}

String returnData = contentStr.toString().replace(beforeData, rePlaceData);
if("A".equals(type)){
setContentA(returnData);
}else if("B".equals(type)){
setContentB(returnData);
}else{
setContentC(returnData);
}
defultData = rePlaceData;
return returnData;
}

public static String getContentA() {
return contentA;
}

public static void setContentA(String contentA) {
GamMail.contentA = contentA;
}

public static String getContentB() {
return contentB;
}

public static void setContentB(String contentB) {
GamMail.contentB = contentB;
}

public static String getContentC() {
return contentC;
}

public static void setContentC(String contentC) {
GamMail.contentC = contentC;
}
}

SWING 抽獎

package test;

import java.awt.Component;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;

public class RaffleDraw {
private static String man;
private static String money;

public static void main(final String[] args) {
        JFrame f = new JFrame();
        f.setSize(600, 300);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setLayout(new GridBagLayout());
        JButton raffleBtn = new JButton("開始抽獎");
JLabel lab = new JLabel("人數");
JLabel lab2 = new JLabel("獎金");
final JTextArea screen = new JTextArea("",32,90);
screen.setEditable(false);
screen.setLineWrap(true);
screen.setAutoscrolls(true);
final JTextField text1 = new JTextField("",20);
final JTextField text2 = new JTextField("",20);
JScrollPane scrollPane = new JScrollPane(screen,
                ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
raffleBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
man = text1.getText();
money = text2.getText();
List winnerList = readFile(man,money,args[0]);
StringBuffer sbf = new StringBuffer();
for(int i=0;i sbf.append((i+1)+"."+winnerList.get(i)+"\r\n");
}
if(winnerList.size() > 0){
screen.setText(sbf.toString());
}
}
        });
int att[][] = {
{0,0,1,1,1,1,GridBagConstraints.BOTH},
{0,1,1,1,1,1,GridBagConstraints.BOTH},
{1,0,1,1,1,1,GridBagConstraints.BOTH},
{1,1,1,1,1,1,GridBagConstraints.BOTH},
{0,3,2,1,1,1,GridBagConstraints.HORIZONTAL},
{0,4,2,2,1,1,GridBagConstraints.BOTH},
};
add(f,lab,att[0]);
add(f,lab2,att[1]);
add(f,text1,att[2]);
add(f,text2,att[3]);
add(f,raffleBtn,att[4]);
add(f,scrollPane,att[5]);
f.pack();
        f.setVisible(true);
    }


public static List readFile(String mans,String money,String path){
int man = 0;
try{
man = Integer.parseInt(mans);
Integer.parseInt(money);
}catch(Exception e){
List exList = new ArrayList();
exList.add("人數及獎金請輸入數字");
return exList;
}
String str = "";
List already = new ArrayList();
List standbyList = new ArrayList();
List winnerList = new ArrayList();
try {
FileInputStream fr = new FileInputStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(fr,"Big5"));
boolean isfirst = true;
String title = "";
while((str = br.readLine()) != null){
if(isfirst){
isfirst = false;
title = str;
continue;
}
String[] tempLine = str.split("\\,");
try{
String s = tempLine[3];
already.add(str);
}catch(Exception e){
standbyList.add(str);
}
}
br.close();
fr.close();
Random rand = new Random();
if(standbyList.size() < man){
winnerList.add("名單人數小於抽獎人,請重新輸入抽獎人數 剩餘未中獎人數為:"+standbyList.size());
}else{
int countMan = man;
for(int i = 1; standbyList.size() >= countMan && i<=man;i++){
String alreadyData = standbyList.remove(rand.nextInt(standbyList.size()));
winnerList.add(alreadyData);
already.add(alreadyData+","+money);
countMan--;
};
FileOutputStream fo = new FileOutputStream(path);
if(!isfirst){
fo.write(title.getBytes());
fo.write("\r\n".getBytes());
}
for(int i =0;i fo.write(already.get(i).getBytes());
fo.write("\r\n".getBytes());
}
for(int i =0;i fo.write(standbyList.get(i).getBytes());
fo.write("\r\n".getBytes());
}
fo.close();
}
return winnerList;
} catch (Exception e) {
e.printStackTrace();
}
return winnerList;
}

private static void add(Container con ,Component com,int att[]){
GridBagConstraints cons = new GridBagConstraints();
cons.gridx = att[0];
cons.gridy = att[1];
cons.gridwidth = att[2];
cons.gridheight = att[3];
cons.weightx = att[4];
cons.weighty = att[5];
cons.fill = att[6];
con.add(com,cons);
}
}