Friday 11 July 2014

Using C# with Gmail - Part 1, POP3

While this part is for gmail, it can also be used for other email providers. I'm also assuming that you have a gmail account. If you haven't, you can still use the code, but you'll need to alter some parts.

Introduction


There are two parts to any form of email application - the sending and the receiving. Neither of these are hard to code, but but they can get a bit messy. POP3 is not natively supported in .NET, so it will need coding up. Thankfully, it's not difficult.

Connecting to POP3


The POP3 system allows software to connect to a remote server and using a predefined set of instructions, access emails. Gmail requires an SSL connection. SSL is supported in System.Net.Security. The actual connection is quite simple.

The strings username and password are exactly what they say they are - your username and password

SslStream nstream;
       
public SslStream Connect(string username, string password)
{
   string message;
   string response;
   TcpClient tcpClient = new TcpClient();
   tcpClient.Connect("pop.gmail.com", 995);

995 is the port needed to connect to the gmail POP3 server. Notice at this point, nothing has been done with the SSL connection - all that has happened is that a connection has been made by the software to a port.

   nstream = new SslStream(tcpClient.GetStream());
   nstream.AuthenticateAsClient("pop.gmail.com");
   response = Response(nstream);

OK, we've now connected to the server using SSL (tcpClient.GetStream() is used to obtain the underlying network stream in use) and it's time to listen to the server

   if (response.Substring(0, 3) != "+OK")
   {
      throw new Pop3Exception(response);
   }

   message = "USER " + username + "\r\n";
   Write(message, nstream);
   response = Response(nstream);
   if (response.Substring(0, 3) != "+OK")
   {
      throw new Pop3Exception(response);
   }

   message = "PASS " + password + "\r\n";
   Write(message, nstream);
   response = Response(nstream);
   if (response.Substring(0, 3) != "+OK")
   {
      throw new Pop3Exception(response);
   }
   return nstream;
}

At this point the software has connected to the server. The above method has two helper methods associated with it, Response and Write. These are the main communication methods for the server, so let's detail them now.

private void Write(string message, SslStream nstream)
{
   System.Text.ASCIIEncoding en = new System.Text.ASCIIEncoding() ;
   byte[] WriteBuffer = new byte[1024] ;
   WriteBuffer = en.GetBytes(message) ;
    nstream.Write(WriteBuffer, 0, WriteBuffer.Length);
}
       
private string Response(SslStream stream)
{
   System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
   byte[] serverbuff = new Byte[1024];
   int count = 0;
   while (true)
   {
      byte[] buff = new Byte[2];
      int bytes = stream.Read(buff, 0, 1 );
      if (bytes == 1)
      {
          serverbuff[count] = buff[0];
          count++;

          if (buff[0] == '\n')
          {
             break;
          }
       }
       else
       {
          break;
       };
    };

    string retval = enc.GetString(serverbuff, 0, count );
    return retval;
}

Disconnecting from the server is just a case of sending the disconnect message, waiting for the reply and well, that's about it

public void Disconnect(SslStream netstream)
{
   string message;
   string response;
   message = "QUIT\r\n";
   Write(message, netstream);
   response = Response(netstream);
   if (response.Substring(0, 3) != "+OK")
   {
      throw new Pop3Exception(response);
    }
}

1 comment:

  1. Hello Paul,
    The Article on Using C# with Gmail - Part 1, POP3.is nice It give detail information with Step by Step ,Thanks for Sharing the information.Xamarin Apps Development

    ReplyDelete