cvmachine.com - 申博开户网

查找: 您的方位主页 > 网络频道 > 阅览资讯:项目中用到的2个东西类代码:FTP与SendMail

项目中用到的2个东西类代码:FTP与SendMail

2019-03-30 08:25:12 来历:www.cvmachine.com 【

今日刚写了几个代码,用在正在开发的项目中
虽然是从遍地找来的,可是通过我修正完善了一下

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,这样能够持续阅览下级目录的内容

 
 

本文地址:http://www.cvmachine.com/a/question/99914.html
Tags: 东西 2个 目中
修改:申博开户网
关于咱们 | 联络咱们 | 友情链接 | 网站地图 | Sitemap | App | 回来顶部