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

JavaBeans 专栏收录该内容
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:
icecloud@sina.com</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,这样可以继续浏览下级目录的内容

  • 0
    点赞
  • 1
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

打赏
文章很值,打赏犒劳作者一下
相关推荐
<p style="text-align:left;"> <span> </span> </p> <p class="ql-long-24357476" style="font-size:11pt;color:#494949;"> <span style="font-family:"color:#E53333;font-size:14px;background-color:#FFFFFF;line-height:24px;"><span style="line-height:24px;">限时福利1:</span></span><span style="font-family:"color:#3A4151;font-size:14px;background-color:#FFFFFF;">购课进答疑群专享柳峰(刘运强)老师答疑服务。</span> </p> <p> <br /> </p> <p class="ql-long-24357476"> <strong><span style="color:#337FE5;font-size:14px;">为什么说每一个程序员都应该学习MySQL?</span></strong> </p> <p class="ql-long-24357476"> <span style="font-size:14px;">根据《2019-2020年中国开发者调查报告》显示,超83%的开发者都在使用MySQL数据库。</span> </p> <p class="ql-long-24357476"> <img src="https://img-bss.csdn.net/202003301212574051.png" alt="" /> </p> <p class="ql-long-24357476"> <span style="font-size:14px;">使用量大同时,掌握MySQL早已是运维、DBA的必备技能,甚至部分IT开发岗位也要求对数据库使用和原理有深入的了解和掌握。</span><br /> <br /> <span style="font-size:14px;">学习编程,你可能会犹豫选择 C++ 还是 Java;入门数据科学,你可能会纠结于选择 Python 还是 R;但无论如何, MySQL 都是 IT 从业人员不可或缺的技能!</span> </p> <span></span> <p> <br /> </p> <p> <span> </span> </p> <h3 class="ql-long-26664262"> <p style="font-size:12pt;"> <strong class="ql-author-26664262 ql-size-14"><span style="font-size:14px;color:#337FE5;">【课程设计】</span></strong> </p> <p style="font-size:12pt;"> <span style="color:#494949;font-weight:normal;"><br /> </span> </p> <p style="font-size:12pt;"> <span style="color:#494949;font-weight:normal;font-size:14px;">在本课程中,刘运强老师会结合自己十多年来对MySQL的心得体会,通过课程给你分享一条高效的MySQL入门捷径,让学员少走弯路,彻底搞懂MySQL。</span> </p> <p style="font-size:12pt;"> <span style="color:#494949;font-weight:normal;"><br /> </span> </p> <p style="font-size:12pt;"> <span style="font-weight:normal;font-size:14px;">本课程包含3大模块:</span><span style="font-weight:normal;font-size:14px;"> </span> </p> </h3> <p class="ql-long-26664262" style="font-size:11pt;color:#494949;"> <strong class="ql-author-26664262"><span style="font-size:14px;">一、基础篇:</span></strong> </p> <p class="ql-long-26664262" style="font-size:11pt;color:#494949;"> <span class="ql-author-26664262" style="font-size:14px;">主要以最新的MySQL8.0安装为例帮助学员解决安装与配置MySQL的问题,并对MySQL8.0的新特性做一定介绍,为后续的课程展开做好环境部署。</span> </p> <p class="ql-long-26664262" style="font-size:11pt;color:#494949;"> <span class="ql-author-26664262" style="font-size:14px;"><br /> </span> </p> <p class="ql-long-26664262" style="font-size:11pt;color:#494949;"> <strong class="ql-author-26664262"><span style="font-size:14px;">二、SQL语言篇</span></strong><span class="ql-author-26664262" style="font-size:14px;">:</span> </p> <p class="ql-long-26664262" style="font-size:11pt;color:#494949;"> <span class="ql-author-26664262" style="font-size:14px;">本篇主要讲解SQL语言的四大部分数据查询语言DQL,数据操纵语言DML,数据定义语言DDL,数据控制语言DCL,</span><span style="font-size:14px;">学会熟练对库表进行增删改查等必备技能。</span> </p> <p class="ql-long-26664262" style="font-size:11pt;color:#494949;"> <span style="font-size:14px;"><br /> </span> </p> <p class="ql-long-26664262" style="font-size:11pt;color:#494949;"> <strong class="ql-author-26664262"><span style="font-size:14px;">三、MySQL进阶篇</span></strong><span style="font-size:14px;">:</span> </p> <p class="ql-long-26664262" style="font-size:11pt;color:#494949;"> <span style="font-size:14px;">本篇可以帮助学员更加高效的管理线上的MySQL数据库;具备MySQL的日常运维能力,语句调优、备份恢复等思路。</span> </p> <span><span> <p style="font-size:11pt;color:#494949;"> <span style="font-size:14px;"> </span><img src="https://img-bss.csdn.net/202004220208351273.png" alt="" /> </p> </span></span>
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页

打赏

icecloud

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值