The other two methods are implemented in our class and described in the next paragraphs. The Write method writes data to the socket.
public void Write( string message)
{
System.Text.ASCIIEncoding en = new System.Text.ASCIIEncoding()
;
byte[] WriteBuffer = new byte[ 1024] ;
WriteBuffer = en. GetBytes( message) ;
NetworkStream stream = GetStream() ;
stream. Write( WriteBuffer, 0, WriteBuffer. Length);
}
It must be remembered that C#'s native string type is not based on the ASCII
characters, but rather is based on Unicode. Thus in order to send messages
on SMTP we must first convert the string input parameter to an array of ASCII
bytes. We use the ASCIIEncoding
class in dotNET to make this transformation.
Then we retrieve
the socket stream using the GetStream
method inherited from the TcpClient
class
and write the bytes to the stream.
The Response method receives data from the socket.
public string Response()
{
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
byte[] serverbuff = new Byte[ 1024];
NetworkStream stream = GetStream();
int count = stream. Read( serverbuff, 0, 1024 );
if (count == 0)
return "";
return enc. GetString( serverbuff, 0, count );
}
The Response
method begins by retrieving the bytes from the stream and then
converts the incoming ASCII bytes to our native C# string
type. Now that we have
an SMTP class, you might be wondering how you use it.
Comments