package com.nelson.util;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Properties;
import javax.mail.Session;
import javax.mail.Message;
import javax.mail.Transport;
import javax.mail.PasswordAuthentication;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import javax.mail.util.ByteArrayDataSource;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
/**
* 此類別提供寄件之功能.
* <p>
* 文件建立日期:2009/10/09
* @author Nelson Chen
*/
public class SendMail {
private String from = null;
private String to = null;
private List<String> cc = new ArrayList<String>();
private List<String> bcc = new ArrayList<String>();
private String smtphost = null;
private int port = 25;
private boolean auth = false;
/**
* Constructor of SendMail
*/
public SendMail(){
}
/**
* Constructor of SendMail
* @param from 寄件者
* @param to 收件者
* @param cc 附本
* @param bcc 密件附本
* @param smtphost smtp伺服器主機
* @param port smtp伺服器連結埠
* @param auth smtp伺服器是否需要驗證
*/
public SendMail(String from,String to,List<String> cc,List<String> bcc,String smtphost,int port,boolean auth){
this.from = from;
this.to = to;
this.cc = cc;
this.bcc = bcc;
this.smtphost = smtphost;
this.port = port;
this.auth = auth;
}
/**
* 此method為簡易的寄件功能
* @param user 寄件者帳號,smtp主機伺服器驗證使用。
* @param password 寄件者密碼,smtp主機伺服器驗證使用。
* @param subject 寄件主旨
* @param content 寄件內容
* @param debug 是否偵錯
* @param HTML 寄件內容格式為text/html
*/
public void SimpleSend(final String user,final String password,String subject,String content,boolean debug,String HTML){
Properties props = System.getProperties();
props.put("mail.smtp.host",smtphost);
props.put("mail.smtp.port",port);
props.put("mail.smtp.quitwait", "false");
if(auth){
props.put("mail.smtp.socketFactory.port", port);
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
}
//採用認證,因為使用外部主機
props.put("mail.smtp.auth",auth);
Session session = null;
if(auth){
//建立Session,並傳入認證之帳號、密碼
session = Session.getDefaultInstance(props,
new javax.mail.Authenticator(){
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(user,password);
}
});
}else{
session = Session.getInstance(props);
}
session.setDebug(debug);
//建立Message
Message msg = new MimeMessage(session);
try{
//設定送件者
msg.setFrom(new InternetAddress(from,from.substring(1,from.indexOf('@')),"Big5"));
//設定郵件主旨
msg.setSubject(new String(subject.getBytes("Big5")));
//設定郵件寄件時間
msg.setSentDate(new Date());
//設定收件者
if(to==null || to.equals("")){
}else{
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to,to.substring(1,to.indexOf('@')),"Big5"));
}
//設定收件者附本
int i=0;
int iSize = cc.size();
Iterator<String> it = cc.iterator();
InternetAddress[] iaddress = new InternetAddress[iSize];
String itvalue = null;
while(it.hasNext()){
itvalue = (String)it.next();
iaddress[i] = new InternetAddress(itvalue,itvalue.substring(1,itvalue.indexOf('@')),"Big5");
i++;
}
msg.setRecipients(Message.RecipientType.CC,iaddress);
//設定收件者密件附本
i=0;
iSize = bcc.size();
it = bcc.iterator();
iaddress = new InternetAddress[iSize];
while(it.hasNext()){
itvalue = (String)it.next();
iaddress[i] = new InternetAddress(itvalue,itvalue.substring(1,itvalue.indexOf('@')),"Big5");
i++;
}
msg.setRecipients(Message.RecipientType.BCC,iaddress);
//設定寄件內容
if(content==null || content.equals("")){
}else{
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText(new String(content.getBytes("Big5")));
MimeMultipart mp1 = new MimeMultipart();
mp1.addBodyPart(mbp1);
msg.setContent(mp1);
}
//設定寄件內容為HTML格式
if(HTML==null || HTML.equals("")){
}else{
msg.setDataHandler(new DataHandler(new ByteArrayDataSource(HTML,"text/html")));
}
Transport ts = session.getTransport("smtp");
if(auth){
//大部份外部主機需帳號認證
ts.connect(user,password);
}else{
ts.connect();
}
msg.saveChanges();
Transport.send(msg);
System.out.println("寄件成功!!");
}catch(Exception e){
e.printStackTrace();
System.out.println(e.getMessage());
}
}
/**
* 此method為寄件功能及可夾附件檔案
* @param user 寄件者帳號,smtp主機伺服器驗證使用。
* @param password 寄件者密碼,smtp主機伺服器驗證使用。
* @param subject 寄件主旨
* @param content 寄件內容
* @param fileName 附件檔案
* @param debug 是否偵錯
*/
public void SendFile(final String user,final String password,String subject,String content,List<String> fileName,boolean debug){
Properties props = System.getProperties();
props.put("mail.smtp.host",smtphost);
props.put("mail.smtp.port",port);
props.put("mail.smtp.quitwait", "false");
if(auth){
props.put("mail.smtp.socketFactory.port", port);
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
}
//採用認證,因為使用外部主機
props.put("mail.smtp.auth",auth);
Session session = null;
if(auth){
//建立Session,並傳入認證之帳號、密碼
session = Session.getDefaultInstance(props,
new javax.mail.Authenticator(){
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(user,password);
}
});
}else{
session = Session.getInstance(props);
}
session.setDebug(debug);
//建立Message
MimeMessage msg = new MimeMessage(session);
try{
//設定送件者
msg.setFrom(new InternetAddress(from,from.substring(1,from.indexOf('@')),"Big5"));
//設定郵件主旨
msg.setSubject(new String(subject.getBytes("Big5")));
//設定郵件寄件時間
msg.setSentDate(new Date());
//設定收件者
if(to==null || to.equals("")){
}else{
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to,to.substring(1,to.indexOf('@')),"Big5"));
}
//設定收件者附本
int i=0;
int iSize = cc.size();
Iterator<String> it = cc.iterator();
InternetAddress[] iaddress = new InternetAddress[iSize];
String itvalue = null;
while(it.hasNext()){
itvalue = (String)it.next();
iaddress[i] = new InternetAddress(itvalue,itvalue.substring(1,itvalue.indexOf('@')),"Big5");
i++;
}
msg.setRecipients(Message.RecipientType.CC,iaddress);
//設定收件者密件附本
i=0;
iSize = bcc.size();
it = bcc.iterator();
iaddress = new InternetAddress[iSize];
while(it.hasNext()){
itvalue = (String)it.next();
iaddress[i] = new InternetAddress(itvalue,itvalue.substring(1,itvalue.indexOf('@')),"Big5");
Properties props = System.getProperties();
props.put("mail.smtp.host",smtphost);
props.put("mail.smtp.port",port);
props.put("mail.smtp.quitwait", "false");
if(auth){
props.put("mail.smtp.socketFactory.port", port);
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
}
//採用認證,因為使用外部主機
props.put("mail.smtp.auth",auth);
Session session = null;
if(auth){
//建立Session,並傳入認證之帳號、密碼
session = Session.getDefaultInstance(props,
new javax.mail.Authenticator(){
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(user,password);
}
});
}else{
session = Session.getInstance(props);
}
session.setDebug(debug);
//建立Message
MimeMessage msg = new MimeMessage(session);
try{
//設定送件者
msg.setFrom(new InternetAddress(from,from.substring(1,from.indexOf('@')),"Big5"));
//設定郵件主旨
msg.setSubject(new String(subject.getBytes("Big5")));
//設定郵件寄件時間
msg.setSentDate(new Date());
//設定收件者
if(to==null || to.equals("")){
}else{
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to,to.substring(1,to.indexOf('@')),"Big5"));
}
//設定收件者附本
int i=0;
int iSize = cc.size();
Iterator<String> it = cc.iterator();
InternetAddress[] iaddress = new InternetAddress[iSize];
String itvalue = null;
while(it.hasNext()){
itvalue = (String)it.next();
iaddress[i] = new InternetAddress(itvalue,itvalue.substring(1,itvalue.indexOf('@')),"Big5");
i++;
}
msg.setRecipients(Message.RecipientType.CC,iaddress);
//設定收件者密件附本
i=0;
iSize = bcc.size();
it = bcc.iterator();
iaddress = new InternetAddress[iSize];
while(it.hasNext()){
itvalue = (String)it.next();
iaddress[i] = new InternetAddress(itvalue,itvalue.substring(1,itvalue.indexOf('@')),"Big5");
i++;
}
msg.setRecipients(Message.RecipientType.BCC,iaddress);
//設定寄件內容
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText(new String(content.getBytes("Big5")));
MimeMultipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
//設定夾檔附件
if(fileName==null){
}else{
it = fileName.iterator();
String file = null;
while(it.hasNext()){
file = (String)it.next();
System.out.println("fileName:"+file);
FileDataSource fds = new FileDataSource(file);
MimeBodyPart mbp2 = new MimeBodyPart();
mbp2.setDataHandler(new DataHandler(fds));
//解決夾檔之檔名中文亂碼問題
//MimeUtility.encodeWord(fds.getName())
mbp2.setFileName(MimeUtility.encodeWord(fds.getName(),"Big5",null));
mp.addBodyPart(mbp2);
}
}
msg.setContent(mp);
Transport ts = session.getTransport("smtp");
if(auth){
//大部份外部主機需帳號認證
ts.connect(user,password);
}else{
ts.connect();
}
msg.saveChanges();
Transport.send(msg);
System.out.println("寄件成功!!");
}catch(Exception e){
e.printStackTrace();
System.out.println(e.getMessage());
}
}
/**
* 驗證SendMail功能是否正確
*/
public static void main(String[] args){
List<String> fileName = new ArrayList<String>();
fileName.add("d:\\MyData\\壽生經.doc");
fileName.add("d:\\MyData\\壽生經疏文.doc");
String user = null; String password = "aaaaaa";
String subject = "=====使用Java實作smtp寄件功能!!=====";
String content = "=====使用Java實作smtp寄件功能!!=====";
String HTML="<HTML><HEAD><TITLE>"+subject+"</TITLE></HEAD><BODY><A HREF=\"http://fubonshop.com/momo_a/click.aspx?rl=http%3A%2F%2Fwww%2Emomoshop%2Ecom%2Etw%2Factivity%2Fedm%2Ejsp%3Fpn%3D090928182508%26ctype%3DE%26cid%3D0928me%26oid%3D13%26sdiv%3Dedm01&project_no=2173&user_no=78081&Link_no=2798&Trace_No=4\">看不到本封電報或遺失圖檔,請按此>>></A><BR><H1>"+subject+"</H1><HR><A HREF=\"http://tw.rd.yahoo.com/referurl/hp/1024/me/news/*http://tw.news.yahoo.com/\">Yahoo新聞</A><IMG SRC=\"http://l.yimg.com/f/a/tw/sophia/694404_sw1_mail_100809_1007give_170x120_1.gif\"></BODY></HTML>";
boolean debug = true;
SendMail sm = new SendMail(); sm.from = "aaaaaa@gmail.com";
sm.to = "aaaaaa@gmail.com";
sm.cc.add("aaaaaa@yahoo.com.tw");
sm.cc.add("aaaaaa@pchome.com.tw");
sm.bcc.add("aaaaaa@kbronet.com.tw");
sm.smtphost = "smtp.gmail.com";
sm.port = 465;
sm.auth = true;
user = sm.from;
sm.SimpleSend(user, password, subject, content, debug, HTML);
content = "=====使用Java實作smtp寄件功能!!=====";
sm.SendFile(user, password, subject, content, fileName, debug);
sm = null;
}
}
}
msg.setRecipients(Message.RecipientType.BCC,iaddress);
//設定寄件內容
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText(new String(content.getBytes("Big5")));
MimeMultipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
//設定夾檔附件
if(fileName==null){
}else{
it = fileName.iterator();
String file = null;
while(it.hasNext()){
file = (String)it.next();
System.out.println("fileName:"+file);
FileDataSource fds = new FileDataSource(file);
MimeBodyPart mbp2 = new MimeBodyPart();
mbp2.setDataHandler(new DataHandler(fds));
//解決夾檔之檔名中文亂碼問題
//MimeUtility.encodeWord(fds.getName())
mbp2.setFileName(MimeUtility.encodeWord(fds.getName(),"Big5",null));
mp.addBodyPart(mbp2);
}
}
msg.setContent(mp);
Transport ts = session.getTransport("smtp");
if(auth){
//大部份外部主機需帳號認證
ts.connect(user,password);
}else{
ts.connect();
}
msg.saveChanges();
Transport.send(msg);
System.out.println("寄件成功!!");
}catch(Exception e){
e.printStackTrace();
System.out.println(e.getMessage());
}
}
/**
* 驗證SendMail功能是否正確
*/
public static void main(String[] args){
List<String> fileName = new ArrayList<String>();
fileName.add("d:\\MyData\\壽生經.doc");
fileName.add("d:\\MyData\\壽生經疏文.doc");
String user = null; String password = "aaaaaa";
String subject = "=====使用Java實作smtp寄件功能!!=====";
String content = "=====使用Java實作smtp寄件功能!!=====";
String HTML="<HTML><HEAD><TITLE>"+subject+"</TITLE></HEAD><BODY><A HREF=\"http://fubonshop.com/momo_a/click.aspx?rl=http%3A%2F%2Fwww%2Emomoshop%2Ecom%2Etw%2Factivity%2Fedm%2Ejsp%3Fpn%3D090928182508%26ctype%3DE%26cid%3D0928me%26oid%3D13%26sdiv%3Dedm01&project_no=2173&user_no=78081&Link_no=2798&Trace_No=4\">看不到本封電報或遺失圖檔,請按此>>></A><BR><H1>"+subject+"</H1><HR><A HREF=\"http://tw.rd.yahoo.com/referurl/hp/1024/me/news/*http://tw.news.yahoo.com/\">Yahoo新聞</A><IMG SRC=\"http://l.yimg.com/f/a/tw/sophia/694404_sw1_mail_100809_1007give_170x120_1.gif\"></BODY></HTML>";
boolean debug = true;
SendMail sm = new SendMail(); sm.from = "aaaaaa@gmail.com";
sm.to = "aaaaaa@gmail.com";
sm.cc.add("aaaaaa@yahoo.com.tw");
sm.cc.add("aaaaaa@pchome.com.tw");
sm.bcc.add("aaaaaa@kbronet.com.tw");
sm.smtphost = "smtp.gmail.com";
sm.port = 465;
sm.auth = true;
user = sm.from;
sm.SimpleSend(user, password, subject, content, debug, HTML);
content = "=====使用Java實作smtp寄件功能!!=====";
sm.SendFile(user, password, subject, content, fileName, debug);
sm = null;
}
}
沒有留言:
張貼留言