Custom SMTP in C#

The Other Methods

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.

You might also like...

Comments

About the author

Randy Charles Morin

Randy Charles Morin Canada

Randy's article are Copyright 1998-2003 Randy Charles Morin

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“It is practically impossible to teach good programming style to students that have had prior exposure to BASIC. As potential programmers, they are mentally mutilated beyond hope of regeneration.” - E. W. Dijkstra