今天剛寫了幾個代碼,用在正在開發的項目中
雖然是從各處找來的,但是經過我修改完善了一下
1 SendMail -- 用於項目中賀卡的發送
原本來自於 aistill原作的代碼:http://www.csdn.net/Develop/Read_Article.asp?Id=14929
本代碼修改了一些實現。可增加任意附件,可支持HTML
可以不考慮設定標題、內容的是否合理等
本類採用了JavaMail及JAF包,需要從http://java.sun.com另行下載
另外,類中採用了我自己的Logger類,可按照自己情況修改
2 FTPConnection -- 用於項目中下載管理
提供FTP瀏覽,列表等簡單功能,由於B/S架構的限制
無法普及使用。僅適用於管理員單用戶使用
鑑於使用WEB方式訪問FTP並上傳下載的意義不大,僅提供瀏覽功能
目的是,從FTP中得到文件名稱並加入到數據庫提供下載
本類採用了sun提供的FTPClient類實現。該類功能極弱....
在ServU服務器測試通過
改進:如果要讓多人使用,可以考慮將其實例加入Session
============= 代碼:SendMail.java =====================
package nona.util;
/**
* 以下的包需要下載
* JAF 1.0.2
* JavaMail 1.3.1
* http://java.sun.org
*/
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Date;
import javax.activation.*;
import java.io.*;
/**
* 郵件發送類,用於發送郵件及附件
* 支持mime格式及Html,支持多附件
* <p>Title: 冰雲工作室</p>
* <p>Description: 郵件發送</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: [email protected]</p>
* @author 冰雲
* @version 1.0 August.23rd 2003
* @todo 使用者請修改Logger.log爲System.out.println
*/
public class SendMail {
private MimeMessage mimeMsg; //MIME郵件對象
private Session session; //郵件會話對象
private Properties props; //系統屬性
private Multipart mp; //Multipart對象,郵件內容,標題,附件等內容均添加到其中後再生成MimeMessage對象
private String authentication = "false"; //smtp是否需要認證
private String username = ""; //smtp認證用戶名和密碼
private String password = "";
private String from = "";
private String to = "";
private String cc = "";
private String bcc = "";
private String body = "";
private String subject = "";
private String host = "";
private String reply = "";
private String sender = "";
private String date = "";
private boolean textmail = true;
private String mailtype = PLAIN;
private static final String HTML = "text/html;charset=GB2312";
private static final String PLAIN = "text/plain; charset=GB2312";
private ArrayList attachment = new ArrayList();
/**
*
*/
public SendMail() {
this(true);
}
public SendMail(boolean textmail) {
this.textmail = textmail;
this.mailtype = textmail ? PLAIN : HTML;
}
public SendMail(String from, String to, String subject, String body) {
this();
loadDefault();
}
private boolean createMimeMessage() {
try {
// Logger.log(this,"createMimeMessage():準備獲取郵件會話對象!");
session = Session.getDefaultInstance(props, null); //獲得郵件會話對象
}
catch (Exception e) {
Logger.logerr(this, "createMimeMessage():獲取郵件會話對象時發生錯誤!");
Logger.logerr(this, e);
return false;
}
try {
mimeMsg = new MimeMessage(session); //創建MIME郵件對象
mp = new MimeMultipart();
return true;
}
catch (Exception e) {
Logger.logerr(this, "createMimeMessage():創建MIME郵件對象失敗!");
Logger.logerr(this, e);
return false;
}
}
private boolean initMail() {
if (props == null) {
props = System.getProperties(); //獲得系統屬性對象
}
if ("".equals(host)) { // 設置主機
loadDefault();
}
props.put("mail.smtp.host", host); //設置SMTP主機
if (!this.createMimeMessage())
return false;
props.put("mail.smtp.auth", authentication); //設置認證
try {
if (!"".equals(subject)) // 設置標題
mimeMsg.setSubject(subject);
if (!"".equals(from)) //設置發信人
mimeMsg.setFrom(new InternetAddress(from));
if (!"".equals(to)) // 設置收信人
mimeMsg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
if (!"".equals(cc)) // 設置抄送
mimeMsg.setRecipients(Message.RecipientType.CC,
(Address[]) InternetAddress.parse(cc));
if (!"".equals(bcc)) // 設置密件抄送
mimeMsg.setRecipients(Message.RecipientType.BCC,
(Address[]) InternetAddress.parse(bcc));
if (!"".equals(reply)) //設置回覆
mimeMsg.setReplyTo( (Address[]) InternetAddress.parse(reply));
// if (!"".equals(date)) //設置日期
// mimeMsg.setSentDate(new Date(date));
if (!"".equals(body)) { // 設置內容
if (!this.textmail) {
BodyPart bp = new MimeBodyPart();
bp.setContent(body, mailtype);
mp.addBodyPart(bp);
}
else {
mimeMsg.setText(body);
}
}
if (!attachment.isEmpty()) { // 設置附件
for (Iterator it = attachment.iterator(); it.hasNext(); ) {
BodyPart bpr = new MimeBodyPart();
FileDataSource fileds = new FileDataSource( (String) it.next());
bpr.setDataHandler(new DataHandler(fileds));
bpr.setFileName(fileds.getName());
mp.addBodyPart(bpr);
}
}
return true;
}
catch (Exception e) {
Logger.logerr(this, "initMail():設置郵件發生錯誤!");
Logger.logerr(this, e);
return false;
}
}
public boolean Send() {
try {
if (initMail()) {
if (mp.getCount() > 0)
mimeMsg.setContent(mp);
mimeMsg.saveChanges();
Logger.log(this, "正在發送郵件....");
Session mailSession = Session.getInstance(props, null);
Transport transport = mailSession.getTransport("smtp");
transport.connect( (String) props.get("mail.smtp.host"), username,
password);
transport.sendMessage(mimeMsg, mimeMsg.getAllRecipients());
Logger.log(this, "發送郵件成功!");
transport.close();
return true;
}
else {
return false;
}
}
catch (Exception e) {
Logger.logerr(this, "郵件發送失敗!");
Logger.logerr(this, e);
return false;
}
}
private void loadDefault() {
}
public void setCc(String cc) {
this.cc = cc;
}
public void setBcc(String bcc) {
this.bcc = bcc;
}
public void setHost(String host, boolean auth) {
this.host = host;
this.authentication = String.valueOf(auth);
}
public void setHost(String host, boolean auth, String username,
String password) {
setHost(host, auth);
setUsername(username);
setPassword(password);
}
public void setHost(String host, String username, String password) {
setHost(host, true);
setUsername(username);
setPassword(password);
}
public void setHost(String host) {
setHost(host, true);
}
public void setFrom(String from) {
this.from = from;
}
public void setPassword(String password) {
this.password = password;
}
public void setTo(String to) {
this.to = to;
}
public void setUsername(String username) {
this.username = username;
}
public void setAttachment(String filename) {
this.attachment.add(filename);
}
public void setBody(String body) {
this.body = body;
}
public void setSubject(String subject) {
this.subject = subject;
}
public void setReply(String reply) {
this.reply = reply;
}
public void setSender(String sender) {
this.sender = sender;
}
public static void main(String[] argc) {
if (argc.length == 0) {
System.out.println("Useage:SendMail [smtp] [user] [password] [to] [body]");
}
else {
SendMail sm = new SendMail();
sm.setHost(argc[0], argc[1], argc[2]);
sm.setTo(argc[3]);
sm.setBody(argc[4]);
if (sm.Send()) {
System.out.print("Send successful.");
}
else {
System.out.print("Send failed.");
}
}
}
}
================== 代碼:FTPConnection.java ===============
package nona.util;
import sun.net.ftp.*;
import java.io.*;
import java.io.IOException;
import java.util.StringTokenizer;
import sun.net.ftp.*;
import java.util.ArrayList;
/**
* FTP連接代碼,可瀏覽FTP等
* 僅適用於管理員操作,不適合普通用
*
* <p>Title: 冰雲工作室</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: </p>
* @author 冰雲
* @version 1.0 August.23rd 2003
*/
public class FTPConnection {
FtpClient client;
private String host;
private String username;
private String password;
private String path = "/";
private int port = 21;
private static FTPConnection instance;
private FTPConnection() {
}
// 單例類的方法,獲得唯一實例
public static FTPConnection getInstance() {
if (instance == null) {
instance = new FTPConnection();
}
return instance;
}
// 連接FTP,並進入當前的path
public void connect() throws IOException {
if (client == null) {
client = new FtpClient(host, port);
client.login(username, password);
client.binary();
client.cd(path);
}
else {
client.noop();
client.cd(path);
}
}
// 關閉FTP
public void close() throws IOException {
if (client != null) {
client.closeServer();
}
}
// 獲得FTPClient類,可以直接對其操作
public FtpClient getClient() throws IOException {
if (client == null) {
connect();
}
return client;
}
// 返回當前目錄的所有文件及文件夾
public ArrayList getFileList() throws IOException {
BufferedReader dr = new BufferedReader(new InputStreamReader(client.list()));
ArrayList al = new ArrayList();
String s = "";
while ( (s = dr.readLine()) != null) {
al.add(s);
}
return al;
}
// 返回當前目錄的文件名稱
public ArrayList getNameList() throws IOException {
BufferedReader dr = new BufferedReader(new InputStreamReader(client.
nameList(path)));
ArrayList al = new ArrayList();
String s = "";
while ( (s = dr.readLine()) != null) {
al.add(s);
}
return al;
}
// 判斷一行文件信息是否爲目錄
public boolean isDir(String line) {
return ( (String) parseLine(line).get(0)).indexOf("d") != -1;
}
public boolean isFile(String line) {
return!isDir(line);
}
// 處理getFileList取得的行信息
private ArrayList parseLine(String line) {
ArrayList s1 = new ArrayList();
StringTokenizer st = new StringTokenizer(line, " ");
while (st.hasMoreTokens()) {
s1.add(st.nextToken());
}
return s1;
}
public String getFileName(String line) {
return ( (String) parseLine(line).get(8));
}
public String getFileSize(String line) {
return (String) parseLine(line).get(4);
}
public String getFileDate(String line) {
ArrayList a = parseLine(line);
return (String) a.get(5) + " " + (String) a.get(6) + " " + (String) a.get(7);
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPath() {
return path;
}
public void setPath(String path) throws IOException {
if (client == null)
this.path = path;
else {
client.cd(path);
}
}
public void setPort(int port) {
this.port = port;
}
}
============== 使用方法例 ====================
1 SendMail:
<%
SendMail sm = new SendMail();
sm.setHost("smtp.vip.sina.com","user","pass");
sm.setSubject("xxx");
sm.setTo("xx");
....隨便選擇幾個set寫就行...
....很多可以省略
out.println(sm.send()); // true or false
%>
2 FTPConnection:
<%
FTPConnection ftpc = FTPConnection.getInstance();
ftpc.setHost("192.168.10.100");
ftpc.setUsername("admin");
ftpc.setPassword("123");
ftpc.connect();
%>
<table border="1">
<tr>
<td></td>
<td>名稱</td>
<td>大小</td>
<td>創建時間</td>
</tr>
<%
// 遍歷用getFileList取得的當前目錄下的信息,並得到每個文件的一行信息
for(Iterator it = ftpc.getFileList().iterator();it.hasNext();){
String line = (String)it.next(); %>
<tr>
<td><%if (ftpc.isDir(line)) {%>dir<%}else{%>file<%}%></td>
<td><%=ftpc.getFileName(line)%></td>
<td><%=ftpc.getFileSize(line)%></td>
<td><%=ftpc.getFileDate(line)%></td>
</tr>
<%
}
%>
</table>
說明:
1 FTPConnection中,如果文件名含有空格可能會出現錯誤
2 SendMail中,loadDefault()函數未提供實現,可採用自己的properties文件來初始化
3 使用SendMail請修改所有的Logger,這是我自定義的記錄類,忘記刪除了,可考慮用System.out.println代替
4 FTPConnection中,如果用在普通用戶頁面上,請勿採用單例模式而採用普通的類並將其加入Session
5 FTPConnection換頁進入目錄的同時,可修改path,這樣可以繼續瀏覽下級目錄的內容