I just wrote a few pieces of code today, which is used in a project under development.
Although it was found from various places, it was improved after I modified it.
1 Sendmail -- used to send greeting cards in projects
The original code from aistill: http://www.csdn.net/Develop/Read_Article.asp? Id = 14929
This code modifies some implementations. Any attachment can be added and HTML is supported.
You can choose not to set the title or content properly.
This class uses javamail and JAF package, need to be downloaded separately from the http://java.sun.com
In addition, the class uses my own logger class, which can be modified according to your own situation.
2 ftpconnection -- used for project download management
Provides FTP browsing, list, and other simple functions. Due to the limitations of the B/S architecture
It cannot be widely used. Only applicable to individual administrator users
In view of the significance of using the web method to access FTP and upload and download, only the browsing function is provided.
The purpose is to obtain the file name from FTP and add it to the database for download.
This class adopts the ftpclient class provided by Sun. This type of function is extremely weak ....
Passed the test on the ServU Server
Improvement: If you want to allow multiple users to use it, you can consider adding its instance to the session.
============= Code: Sendmail. Java =======================================
Package Nona. util;
/**
* The following packages need to be downloaded.
* 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 sending class, used to send emails and attachments
* Supports MIME format and HTML, and multiple attachments
* <P> title: ice cloud studio </P>
* <P> Description: email sending </P>
* <P> copyright: Copyright (c) 2003 </P>
* <P> company: A icecloud@sina.com </P>
* @ Author ice cloud
* @ Version 1.0 august.23rd 2003
* @ Todo users modify logger. log to system. Out. println
*/
Public class Sendmail {
Private mimemessage mimemsg; // mime email object
Private session; // email Session Object
Private Properties props; // System Properties
Private multipart MP; // multipart object, mail content, title, attachments, and other content are added to it, and then the mimemessage object is generated.
Private string authentication = "false"; // whether SMTP authentication is required
Private string username = ""; // SMTP authentication username and password
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 (): Get the email session object! ");
Session = session. getdefainstance instance (props, null); // get the mail Session Object
}
Catch (exception e ){
Logger. logerr (this, "createmimemessage (): An error occurred while obtaining the email session object! ");
Logger. logerr (this, e );
Return false;
}
Try {
Mimemsg = new mimemessage (session); // create a mime mail object
MP = new mimemultipart ();
Return true;
}
Catch (exception e ){
Logger. logerr (this, "createmimemessage (): An error occurred while creating the mime mail object! ");
Logger. logerr (this, e );
Return false;
}
}
Private Boolean initmail (){
If (props = NULL ){
Props = system. getproperties (); // obtain the system property object
}
If ("". Equals (host) {// sets the host
Loaddefault ();
}
Props. Put ("mail. SMTP. Host", host); // set the SMTP host
If (! This. createmimemessage ())
Return false;
Props. Put ("mail. SMTP. Auth", authentication); // sets Authentication
Try {
If (! "". Equals (subject) // sets the title
Mimemsg. setsubject (subject );
If (! "". Equals (from) // sets the sender
Mimemsg. setfrom (New internetaddress (from ));
If (! "". Equals (to) // sets the recipient
Mimemsg. setrecipients (message. recipienttype.,
Internetaddress. parse ());
If (! "". Equals (CC) // sets CC
Mimemsg. setrecipients (message. recipienttype. CC,
(Address []) internetaddress. parse (CC ));
If (! "". Equals (BCC) // sets BCC
Mimemsg. setrecipients (message. recipienttype. BCC,
(Address []) internetaddress. parse (BCC ));
If (! "". Equals (reply) // sets the reply
Mimemsg. setreplyto (Address []) internetaddress. parse (reply ));
// If (! "". Equals (date) // sets the date
// Mimemsg. setsentdate (new date (date ));
If (! "". Equals (body) {// set content
If (! This. textmail ){
Bodypart BP = new mimebodypart ();
BP. setcontent (body, mailtype );
MP. addbodypart (BP );
}
Else {
Mimemsg. settext (body );
}
}
If (! Attachment. isempty () {// set the attachment
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 (): An error occurred while setting the email! ");
Logger. logerr (this, e );
Return false;
}
}
Public Boolean send (){
Try {
If (initmail ()){
If (MP. getcount ()> 0)
Mimemsg. setcontent (MP );
Mimemsg. savechanges ();
Logger. Log (this, "sending email ....");
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, "the email is sent successfully! ");
Transport. Close ();
Return true;
}
Else {
Return false;
}
}
Catch (exception e ){
Logger. logerr (this, "email sending failed! ");
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 ){
This. 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 .");
}
}
}
}
====================== 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, which allows you to browse FTP and so on
* Only applicable to administrator operations.
*
* <P> title: ice cloud studio </P>
* <P> Description: </P>
* <P> copyright: Copyright (c) 2003 </P>
* <P> company: </P>
* @ Author ice cloud
* @ 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 (){
}
// Method of the Singleton class to obtain a unique instance
Public static ftpconnection getinstance (){
If (instance = NULL ){
Instance = new ftpconnection ();
}
Return instance;
}
// Connect to FTP and enter the current 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 );
}
}
// Disable FTP
Public void close () throws ioexception {
If (client! = NULL ){
Client. closeserver ();
}
}
// Obtain the ftpclient class, which can be operated directly
Public ftpclient getclient () throws ioexception {
If (client = NULL ){
Connect ();
}
Return client;
}
// Return all files and folders in 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 name of the file in 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;
}
// Determine whether the file information of a row 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 );
}
// Process the row information obtained by 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;
}
}
================== Use Case =
1 Sendmail:
<%
Sendmail Sm = new Sendmail ();
SM. sethost ("smtp.vip.sina.com", "user", "pass ");
SM. setsubject ("XXX ");
SM. setto ("XX ");
... Just select a few set to write...
... Many can be omitted
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> name </TD>
<TD> size </TD>
<TD> creation time </TD>
</Tr>
<%
// Retrieve the information in the current directory obtained using getfilelist and obtain a row of information for each file.
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>
Note:
1 ftpconnection, an error may occur if the file name contains spaces
2 In Sendmail, The loaddefault () function is not provided for implementation. You can use your own properties file for initialization.
3. Use Sendmail to modify all logger. This is my custom record class. If you forget to delete it, use system. Out. println instead.
4. If ftpconnection is used on a common user page, do not use a common class in the single-instance mode and add it to the session.
5 ftpconnection when you switch to the directory, you can modify the path so that you can continue to browse the contents of the sub-directory.