// SmtpConnection.cs
//
// This file is based (in parts) on SmtpEmailer code by Steaven Woyan (mailto:swoyan@hotmail.com),
// and by extension on logic/code design from PJ Naughter's C++ SMTP package
// located at http://www.naughter.com/smpt.html.
//
// The original code has been adapted for use in Aggie by Ziv Caspi.
// See SmtpBatchMailer.cs for a list of changes.
using System;
using System.IO;
using System.Net.Sockets;
namespace Bitworking.Smtp{
public class SmtpConnection {
#region Private data
private TcpClient socket;
private StreamReader reader;
private StreamWriter writer;
private bool connected;
private bool offline;
#endregion
#region Properties
public bool Offline {
get { return offline; }
set { offline = value; } // TODO: Useful only if the connection has not been started yet
}
public bool Connected {
get { return connected; }
}
#endregion
#region Construction and destruction
public SmtpConnection() {
socket = new TcpClient();
}
public void Open( string host ) {
Open( host, 25 );
}
public void Open( string host, int port ) {
if ( !offline ) {
if(host == null || host.Trim().Length == 0 || port <= 0) {
throw new System.ArgumentException("Invalid Argument found.");
}
socket.Connect(host, port);
reader = new StreamReader(socket.GetStream(), System.Text.Encoding.ASCII);
writer = new StreamWriter(socket.GetStream(), System.Text.Encoding.ASCII);
}
connected = true;
} // Open( string, int )
public void Close() {
if ( !offline ) {
reader.Close();
writer.Flush();
writer.Close();
reader = null;
writer = null;
socket.Close();
}
connected = false;
} // Close
#endregion
#region Data exchange
public void SendCommand( string cmd ) {
// TODO: (ZIVC) We need better debugging support...
if ( offline ) {
// System.Diagnostics.Debug.WriteLine( cmd );
// System.Diagnostics.Debug.Flush();
}
if ( !offline ) {
writer.WriteLine(cmd);
writer.Flush();
}
} // SendCommand
public void SendData( char[] buf, int index, int length ) {
if ( !offline )
writer.Write(buf, index, length);
} // SendData
public void GetReply( out string reply, out int code ) {
// TODO: Better error control here
if ( !offline ) {
while ( true ) {
reply = reader.ReadLine();
if ( reply.Length < 4 ) {
code = -1;
break;
}
if ( reply[3] == '-' )
continue; // Multiple response lines. Get only the last one (currently!)
code = ((reply == null)
? -1
: Int32.Parse( reply.Substring( 0, 3 ) ));
break;
}
}
else {
reply = "100 OFFLINE MODE";
code = 100;
}
} // GetReply
#endregion
} // class SmtpConnection
} // namespace Bitworking.Smtp
|