4

i'm trying to create a simple client of SMTP with socket in C#, heres what i have:

 static void Main(string[] args)
    {
        try
        {
            Socket socket;
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            // connect to the SMTP server
            socket.Connect(new IPEndPoint(Dns.GetHostEntry("smtp.gmail.com").AddressList[0], int.Parse("587")));
            PrintRecv(socket);
            SendCommand(socket, string.Format("HELO {0}\r\n", Dns.GetHostName()));
            SendCommand(socket, "STARTTLS\r\n");
            Console.WriteLine("Done");

        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
        Console.ReadKey();
    }
    static void SendCommand(Socket socket, string com)
    {
        Console.WriteLine(">>>" + com);
        socket.Send(Encoding.UTF8.GetBytes(com));
        PrintRecv(socket);
    }
    static void PrintRecv(Socket socket)
    {
        byte[] buffer = new byte[500];
        socket.Receive(buffer);
        Console.WriteLine("<<<" + Encoding.UTF8.GetString(buffer, 0, buffer.Length));
    }

As you see i'm using GMAIL, and it needs to use SSL...My problem is when i try using SSLStream like this:

Stream s = GenerateStreamFromString("quit\r\n");
            SslStream ssl = new SslStream(s); //All OK until here
            ssl.AuthenticateAsClient(System.Environment.MachineName);// <<< MY PROBLEM

I think i don't fully understand this SslStream, i searched a lot(saw those examples on MSDN)... In simple words, i need to know how to setup this SslStream to be used on the SMTP.

1 Answers1

0

You haven't specified the server that you share the SslStream with when you are trying to authenticate. You left it as your machine name instead.

The solution would look something like this

SslStream secureStream = new SslStream(new NetworkStream(ClientSocket));
secureStream.AuthenticateAsClient("smtp.gmail.com");

If it worked correctly you should be able to send resend HELO using the stream and receive an output along the lines of: 250-smtp.gmail.com at your service

Harry Ramsey
  • 93
  • 1
  • 10