项目中用到的2个工具类代码:FTP与SendMail

类别:Java 点击:0 评论:0 推荐:

今天刚写了几个代码,用在正在开发的项目中
虽然是从各处找来的,但是经过我修改完善了一下

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,这样可以继续浏览下级目录的内容

本文地址:http://com.8s8s.com/it/it17280.htm