2 tool classes used in the project: FTP and Sendmail

zhaozj2021-02-11  201

I just wrote a few codes today, although I found it in the project, I have improved it through my revision.

1 Sendmail - The sender of the greeting card for the project is originally here: http://www.9cbs.net/develop/read_article.asp? ID = 14929 This code has modified some implementations. You can increase any attachment, which can support HTML. If you do not consider the set title, whether the content is reasonable, etc., the JavaMail and Jaf package are used, and you need to download additional download from http://java.sun.com, and use my own Logger class, you can modify it according to your situation

2 ftpConnection - Download Management in the project provides simple features such as FTP browsing, lists, due to the limitations of the B / S architecture that cannot be used. Only applicable to administrator single users use the web way to access the FTP and upload the meaning of the download, only the browsing function is to get the file name from the FTP and join the database to provide the Database to provide the FTPCLIENT class with SUN. achieve. This type of function is extremely weak .... In Servu server test, by improvement: If you want to make more people to use, you can consider adding its instance to session.

============= Code: sendmail.java =====================

Package Nona.util; / ** * The following packages need to download * 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. *;

/ ** * Mail send class, used to send mail and attachments * Support MIME format and HTML, support multi-accessories *

Title: Ice Cloud Studio *

Description: Mail Send *

Copyright: Copyright (c) 2003 *

company: Icecloud@sina.com * @Author ice cloud * @version 1.0 August.23rd 2003 * @todo user please modify Logger.log is System.Out.println * / public class sendmail {

Private MimeMessage MimeMsg; // Mime Mail Object Private Session Session; // Mail Session Object Private Properties Props; // System Properties Private Multipart MP; // Multipart Object, Mail Content, Title, Attachment, etc. MIMEMESSAGE object

Private string authentication = "false"; // SMTP Need to authenticate private string username = ""; // SMTP authentication user name and password prince string password = ""; private string from = "; private string to =" "; private String to =" String cc = ""; 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 / place; 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 (); loadingDefault ();

Private boolean createmimeMimeMessage () {// logger.log (this, "createmimeMessage (): Prepare to get mail session object!"); session = session.getDefaultInstance (props, null); // Get mail session object} catch Exception E) {Logger.loGerr (this, "CreateMimeMessage (): An error occurred while getting a mail session object!"); Logger.loGerr (this, e); return false;}

Try {mimsg = new mimeMessage (session); // Create MIME mail object MP = new mimeMultipart (); return true;} catch (Exception E) {logger.loGerr (this, "createmimeMessage (): Create MIME mail object failed! "); Logger.loGerr (this, e); return false;}} private boolean initmail () {if (props == null) {props = system.getproperties (); // Get system properties} if (" " .equals (host)) {// Sets the host loadDefault ();} prOPs.put ("mail.smtp.host", host); // Set SMTP host if (! this.createmimeMessage ()) Return False;

Props.PUT ("mail.smtp.auth", automation; // Setting authentication try {if (! "") // set the title mimemsg.setSubject (Subject); if (! "". Equals ()) // Set the sender mimemsg.setFrom (new internetdress (from)); if (! "". Equals (to)) // Sets the recipient mimemsg.setRecipients (Message.RecipientType.to, InternetAddress.Parse To)); if (! "". Equals (cc)) // Sets CcIMemsg.seTrecipients (message.recipienttype.cc, (address []) InternetdRESS.PARSE (CC)); if (! "". Equals (BCC)) // Set the CcIMSG.SetRecipients (Message.RecipientType.bcc, (address []) InternetdRESS.PARSE (BCC));

If (! "". Equals (reply) // Sets the reply mimsg.setReplyto (Address []) Internetdress.Parse (reply)); // if (! "". Equals (date)) // Setting Date / / Mimemsg.setsentdate (New Date (date));

IF (! ". Equals (body)) {// Setting content if (! this.textmail) {bodypart bp = new mimebodypart (); bp.setcontent (body, mailtype); mp.addbodypart (bp);} else {Mimsg.settext (body);}} if (! Attachment.isempty ()) {// set attachment for (item it = attachment.iterator (); it.hasnext ();) {bodypart BPR = new mimebodypart () FileDataSource fileds = new fileDataSource ((String) IT.Next (); bpr.SetDataHandler (New DataHandler (FileDs.GetName ()); mp.addbodypart (BPR);}}}}}} Return True } Catch (Exception E) {logger.loGerr (this, "initmail (): Setting an error!"); Logger.loGerr (this, e); return false;}}

Public boolean send () {try {if (initmail ()) {if (mp.getcount ()> 0) mimemsg.SetContent (MP); mimemsg.savechange (); logger.log (this, "is sending mail .. .. ");

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, "Send Mail!"); Transport.Close ();

Return true;}}}}} catch (exception e) {logger.loGerr (this, "mail delivery failed!"); logger.loGerr (this, e); return false;}

}

Private void loadingDefault () {

}

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) {setost (host, true); setuserName (username); setPassword (password);}

Public void setHost (String host) {setost (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 = usrname;}

Public void settachment (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.");}}

}

================== Code: 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 connection code, browse FTP, etc. * only for administrator operations, not suitable for ordinary * *

title: ice cloud studio *

Description: *

Copyright: Copyright (c) 2003 *

Company: * @Author ice cloud * @version 1.0 August.23rd 2003 * / public class ftpConnection {ftpclient client; private Private string username; private string password; private string path = "/"; private int port = 21; private static ftpConnection instance;

Private ftpConnection () {} // Single case method, get unique instance

Public static ftpConnection getInstance () {if (instance == null) {instance = new ftpConnection ();} Return Instance;

/ / Connect to FTP and enter the current path

Public void connection {if (client == null) {client = new ftpclient (Host, port); client.login (username, password); client.binary (); client.cd (path);} else {Client.noop (); client.cd (path);}}

// Turn off FTP

Public void close () THROWS IOException {if (client! = null) {client.closserver ();}}

// Get the ftpclient class, you can do public ftpclient getclient () throws ioException {if (client == null) {connection ();} retin client;

/ / Return to all files and folders of the current directory

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;} // Returns the file name of the current directory

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;}

/ / Judgment whether a line of file information is a directory

Public boolean isdir (string line) {return ((String) Parseline (line) .get (0)). INDEXOF ("D")! = -1;}

Public Boolean isfile (String line) {return! isdir (line);

/ / Handling the line information acquired by getFileList

Private arraylist parseline (string line) {ArrayList S1 = new arraylist (); stringtokenizer st = new stringtokenizer (line, ""); while (st.hasmoretoKens ()) {s1.add (st.nextToken ());} retturn 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 = usrname;} 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;}

}

============== Usage method case ====================

1 Sendmail: <% sendmail sm = new sendmail (); sm.sethost ("smtp.vip.sina.com", "user", "pass"); sm.setsubject ("xxx"); sm.Setto (" XX "); .... Casset Several SET Write, ....... Many 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 ();% >

Name Size Creation Time <% // Traverse the information in the current directory acquired with GetFileList and get a line of information for each file (item it = ftpc.getfileList (). Iterator (); it.hasnext ();) {String line = (string) IT.Next ();%>
<% IF (ftpc.isdir (line)) {%> DIR <%} else {%> file <%}%> < % = ftpc.getFileName (line)%> <% = ftpc.getFileSize (line)%> <% = ftpc.getfiledate (line)%> <%}%>

Description: 1 FTPConnection, if the file name contains spaces, there may be an error

2 Sendmail, the loadDefault () function does not provide implementation, you can initialize your own Properties file.

3 Use Sendmail, please modify all Logger, which is my own record class, forget to delete it, consider using system.out.println instead of 4 ftpConnection, if you are used on a normal user page, do not use a single sample mode Adopt ordinary classes and add them to Session

5 FTPConnection changes to the directory to modify the PATH, so you can continue to browse the contents of the lower class directory.

转载请注明原文地址:https://www.9cbs.com/read-4972.html

New Post(0)
CopyRight © 2020 All Rights Reserved
Processed: 0.049, SQL: 9