/ / -------------------------------------------------------------------------------------------- ------------------ / / // / | //// / / - ^ - //// (@ @) // --- ---------------- OOOO - (_) - oooo -------------------- //// Free Software Writen By Navy, Copyleft (C) 2002 // SMTPCLIENT CLASS 1.0 // Use SMTP Server with User Authorization // All Rights Reserved./// oooo // ---------- ---------- OOOO --- () --------------------- / / ()) /// / ((_ /// / _) // ------------------------------------------ ---------------------------------------------------------------------------------------------------------------------------------------
Package encrypt;
Import java.io. *; import java.net. *; import java.util.vector; // Import org.apache.commons.logging.log; // Import org.apache.commons.logging.logfactory; import encrypt. Base64;
/ *** * Standard SMTP Send Creation *
* Standard's SMTP Sending Client Program, support user authentication. *
*
* @Author nAVEN * @see smtpclient *** /
public class SmtpClient {// protected static final Log log = LogFactory.getLog (SmtpClient.class); private static final String CMD_HELO = "HELO"; private static final String CMD_AUTH_LOGIN = "AUTH LOGIN"; private static final String CMD_MAIL_FROM = "MAIL FROM: "; private static final String CMD_RCPT_TO =" RCPT TO: "; private static final String CMD_DATA =" DATA "; private static final String CMD_HELP =" HELP "; private static final String CMD_RSET =" RSET "; private static final String Cmd_noop = "noop"; private static final string cmd_quit = "quit"; private static final string end_of_mail = "/ r/N./R/N";
private static final String RCV_SERVOK = "220"; // 220 service ready private static final String RCV_HELO = "250"; // 250 Requested mail operation completed private static final String RCV_AUTH_LOGIN = "334"; private static final String RCV_AUTH_USER = " 334 "; private static final String RCV_AUTH_PASSWD =" 334 "; private static final String RCV_AUTH_OK =" 235 "; private static final String RCV_MAIL_FROM =" 250 "; private static final String RCV_RCPT_TO =" 250 "; private static final String RCV_DATA =" 354 "; private static final String RCV_SEND_END =" 250 "; private static final String RCV_RSET =" 250 "; private static final String RCV_NOOP =" 250 "; private static final String RCV_QUIT =" 221 "; // 221 service closing transmission channel Private static final int send_block_size = 1024; // Size / ** * Base64 encryption object * / // private base64 base64 = new base64 ();
Private static final int _nothing_special_state = 0; private static final int _last_was_cr_state = 1; private static final INT _LAST_WAS_NL_STATE = 2;
/ ** * Record the status of the message to process the text data sent * / private int _State = 0; / ** * Lock for processing the message data transmission Synchronization processing * / private integer lock = new integer (0); / ** * client socket * / private Socket socketSmtp = null; / ** * socket out printwriter * / private PrintWriter sout = null; / ** * socket int reader * / private BufferedReader sin = null; / ** * smtp email server address * / private String smtpServer = null; / ** * email from user for smtp server * / private String user = null; / ** * user password * / private String passwd = null; / ** * sender's email address * / private String sender = null; / ** * email from user for smtp server, base64 encode * / private String encryptUser = null; / ** * user password, base64 encode * / private String encryptPasswd = null; / ** * client localhost * / priv Ate string localhost = null; / ** * error message * / private string errorstring = "no error";
/ *** * Initialization sender class *
* @Param Server SMTP server address * @Param sender SMTP sender email address *** / public smtpclient (String Server, string sender) {this (Server, NULL, NULL , Sender);} / *** * Initialization Send Reinvisor *
* @Param Server SMTP Server Address * @Param User SMTP Sender Certified User Name * @Param Passwd SMTP Sender Certification Password * @Param Sender SMTP Letter email address *** / public smtpclient (String Server, string user, string passwd, string sender) {this.smtpserver = server; this.user = user; this.parswd = passwd; thermostator = sender; if (this .user! = null && this.passwd! = null) {base64 base64 = new base64 (); // Base64 encode becom byte [] buser = user.getbytes (); byte [] bpasswd = passwd.getbytes (); base64 .startencode (); base64.encode (BSE64.Ength); base64.encode (); this.encryptuser = new string (base64.getencodedre Sult ()); base64.Startencode (); Base64.encode (basswd, bpasswd.length); base64.encode (); this.encryptpasswd = new string (base64.getencodedResult ());}}
/ *** * Obtain an error message *
* @return error message *** / public string geterror () {return errorstring;}
/ *** * When an error is thrown out *
* @Param E error exception *** / private void OneRror (excection e) {this.errorstring = E.getMessage (); //log.error "OneRROR ()" this.erroString); // if (log.IndebugeNabled ()) {// log.debug ("OneRROR ()", e); //}} / *** * Check SMTP protocol communication Whether the information received is successful, that is, at the beginning of the specified return, the SMTP protocol standard. *
* @Param RCVMSG SMTP protocol communication received information * @Param Code SMTP protocol communication Returns * @Exception @Exception oException fails to throw an exception *** / prizode void Check (String rcvmsg, string code) throws ooException { IF (code == null || code.Length () == 0) Return; if (rcvmsg == null || rcvmsg.startswith (code) == false) Throw (New IOException (RCVMSG));}
/ *** * Check that the information received by the SMTP protocol communication is successful, ie, with any beginning, SMTP protocol standard in the specified return code array. *
* @Param RCVMSG SMTP protocol communication received information * @Param Codes SMTP protocol communication Return to the number number * @Exception ioException fails to throw an exception *** / private void Check (String Rcvmsg, string [] Codes) THROWS IOEXCEPTION {IF (CODES == NULL || CODES.LENGTH == 0) Return; Boolean Result = false; for (int i = 0; rcvmsg! = null && i / *** * Write a byte of the message body data to the SMTP server, and process "/ r / n." To "/ r / n ..". * * @Param ch Write a byte * @Exception ioException fails to throw an exception *** / private void write (int CH) throws ooException {synchronized (lock) {switch (CH) {CASE '/ R ': _State = _LAST_WAS_CR_STATE; SOUT.WRITE (' / R '); return; case' / n ': IF (_State! = _last_was_cr_state) Sout.write (' / r '); Sout.Write (' / n ' ); _state = _LAST_WAS_NL_STATE; return; case: // Double the dot at the beginning of a line if (_state == _LAST_WAS_NL_STATE) sout.write (); // Fall through default '.' '.': _state = _NOTHING_SPECIAL_STATE; Sout.write (ch); return;}}} / *** * Section of the SMTP server writes a piece of data for the message body data, and processes "/ r / n." to "/ r / n .." Case. * * @Param Buffer Writing Data Buffer * @Param Offset Written Data Buffer Offset * @Param Length Write Data Buffer Length * @Exception IOException Failure When I Throw Abnormal *** / Private Void Write (CHAR [] Buffer, Int Offset, Int Length) throws ooexception {synchronized (lock) {while (length -> 0) Write (buffer [offset ]);}} / *** * Section of the SMTP server writes a piece of data of the message body data and handles "/ r / n." To "/ r / n ..". * * @Param Buffer Writing data buffer * @Exception ioException fails to throw an exception *** / private void write (char [] buffer) ooException {Write (buffer, 0, buffer.length);} / *** * Section of the SMTP server writes a piece of data of the message body data and handles "/ r / n." To "/ r / n ..". * * @Param String Write data string * @Exception ioException fails to throw an exception *** / private void write (String.ToChararray ());} / *** * Refresh the data of the Socket Stream buffer and submit it. * * @Exception IOException fails to throw an exception *** / private void flush () THROWS ooException {synchronized (lock) {sout.flush ();}} / *** * Write a line of data towards the SMTP server. * * @Param msg Write a line of data strings * @Exception ioException fails to throw an exception *** / private void sendln (String MSG) throws ioException {if (msg == null) msg = "" Sout.println (MSG); Sout.Flush (); // if (log.Indebugenabled ()) {// log.debug ("Sendln () ==>:" msg); //}} / *** * written to the SMTP server write string data. * * @Param msg Write string * @Exception ioException fails to throw an exception *** / private void send (String msg) throws ioException {if (msg == null) msg = ""; sout. Write (msg); sout.flush (); // if (log.Indebugeload ()) {// log.debug ("send () ==>:" msg); //}} / *** * Write a large string data to the SMTP server. * * @Param text Writing string data * @Exception ioException fails to throw an exception *** / private void sendtext (String text) throws ioException {if (text == null) text = ""; if (Text.length ()> send_block_size) {INT i = 0; while (i <= text.length ()) {IF ((i send_block_size) * @return Read the string data * @Exception ioException fails to throw an exception *** / private string receive () throws oException {string rcvmsg = sin.readline (); // if (log.Indebugebled ()) {// log.debug ("receive () <==:" rcvmsg); //} Return RcVMSG;} / *** * Receive a line of string data from the SMTP server and determines if it is a successful return value. * * @Param Code correct SMTP protocol code * @return read strings * @Exception ioException fails to throw exception *** / private string receive (string code) throws ioException {string rcvmsg = Receive Check (RCVMSG, CODE); RETURN RCVMSG;} / *** * Receive a line of string data from the SMTP server, and determines whether it is one of the successful return value arrays. * * @Param Codes correct SMTP protocol code array * @Return read string data * @EXCEPTION IOException fails to throw an exception *** / private string receive (String [] Codes) throws oews ooException {string rcvmsg = Receive (); Check (RCVMSG, CODES); RETURN RCVMSG;} / *** * Connect the SMTP server and send username and password authentication. * * @return return success or failure results * thrown *** / public boolean connect fails @exception IOException () {// connect to smtp server and autherize try {// get localhost name localHost = InetAddress.getLocalHost () .gethostname (); // if (log.IndebugeNabled ()) {// log.debug ("Connect () localhost:" localhost); //} // connection to smtp server socketsmtp = new socket (SMTPSERVER , 25); sout = new PrintWriter (new OutputStreamWriter (socketSmtp.getOutputStream ())); sin = new BufferedReader (new InputStreamReader (socketSmtp.getInputStream ())); receive (RCV_SERVOK); // hello sendln (CMD_HELO localHost); receive (RCV_HELO); if (encryptUser = null && encryptPasswd = null!!) {// auth login sendln (CMD_AUTH_LOGIN); receive (RCV_AUTH_LOGIN); // base64 encode end sendln (encryptUser Receive (RCV_AUTH_USER); Sendln (EncryptPasswd); Receive (RCV_AUTH_OK);}}} Catch (IOException E) {OneRror (E); Closeall (); Return False;} Return true;} / *** * Connection SMTP Server And send an email. * * @Param To Recipient Email Address * @Param MSG Mail Data * @RETURN Return Success Fail Results * @Exception IOException Failure Throw Abnormally *** / Public Boolean Sendmail (String To, String MSG) { Return Sendmail (TO, MSG, NULL);} / *** * Connect the SMTP server and send mail. * * @Param to recipient email address * @Param msg mail data * @Param CC CC recipient email address * @returN return success failure result * @Exception ioException fails to throw an exception *** / public Boolean Sendmail (String to, String Msg, Vector CC) {if (socketsmtp == null || sout == null || sin == null) {closeall (); if (! connect ()) Return False;} Boolean return = false; int count = 0; // Try send for 3 Times if Error While (Retval == False && Count <3) {Try {//mail from sendln (cmd_mail_from sender); Receive (RCV_MAIL_FROM); / / send to sendln (cmd_rcpt_to to); Receive (RCV_RCPT_TO); // Perform CC INT CCSIZE = 0; if (cc! = null && (ccSize = cc.size ())> 0) {for (int i = 0 i / *** * Close the connection to the SMTP server. * *** / private void closeall () {try {if (sout! = null) {sout.close (); sout = null;} if (sin! = null) {sin.close (); sin = NULL;} if (socketsmtp! = null) {socketsmtp.close (); socketsmtp = null;}} catch (ooException e) {//log.error ("Closeall ()", E);}} / ** * * Close the connection to the SMTP server and release the resource. * *** / public void release () {close (); this.socketsmtp = null; // client socket this.sout = null; // socket outprintstream this.sin = null; // Socket int Reader this.smtpServer = null; // smtp email server address this.user = null; // email from user for smtp server this.passwd = null; // user password this.sender = null; // sender's email address this.encryptUser = null; // base64 encode this.encryptpasswd = null; // base64 Encode this.localhost = null; // Client Localhost THIS.ERRORSTRING = "no error"; / *** * Send the quit command and turn off the connection with the SMTP server. * *** / public boolean close () {boolean return = true; if (sout! = null && sin! = null) {Try {// send finish quit sendln (cmd_quit); // receive (); Retval = true;} catch (ioException e) {retval = false; //log.error ("close ()", e);}} closeall (); return rettval;} public string toString () {Return getClass () .getname () "Server:" SMTPSERVER "User:" user "passwd:" passwd "Sender:" sender;}} ///: ~