Connecting to smtp.live.com with the TcpClient class

北慕城南 提交于 2019-12-03 15:40:44

Thanks to nos for putting me on the right track. The smtp.live.com servers require the following sequence of events:

  1. Connect
  2. HELO - will not accept the STARTTLS until this has been sent
  3. STARTTLS - apparently this sets up the server to accept an encrypted connection
  4. SslStream.AuthenticateAsClient() - this seems to let the C# framework and the SMTP server come to an "understanding" :)
  5. Now that we have an encrypted connection, the usual SMTP commands work

Anyway, this code works for both smtp.live.com AND smtp.gmail.com on port 587:

class Program
{
    static void Main(string[] args)
    {
        const string server = "smtp.live.com";
        const int port = 587;
        using (var client = new TcpClient(server, port))
        {
            using (var stream = client.GetStream())
            using (var clearTextReader = new StreamReader(stream))
            using (var clearTextWriter = new StreamWriter(stream) { AutoFlush = true })
            using (var sslStream = new SslStream(stream))
            {
                var connectResponse = clearTextReader.ReadLine();
                if (!connectResponse.StartsWith("220"))
                    throw new InvalidOperationException("SMTP Server did not respond to connection request");

                clearTextWriter.WriteLine("HELO");
                var helloResponse = clearTextReader.ReadLine();
                if (!helloResponse.StartsWith("250"))
                    throw new InvalidOperationException("SMTP Server did not respond to HELO request");

                clearTextWriter.WriteLine("STARTTLS");
                var startTlsResponse = clearTextReader.ReadLine();
                if (!startTlsResponse.StartsWith("220"))
                    throw new InvalidOperationException("SMTP Server did not respond to STARTTLS request");

                sslStream.AuthenticateAsClient(server);

                using (var reader = new StreamReader(sslStream))
                using (var writer = new StreamWriter(sslStream) { AutoFlush = true })
                {
                    writer.WriteLine("EHLO " + server);
                    Console.WriteLine(reader.ReadLine());
                }
            }
        }
        Console.WriteLine("Press Enter to exit...");
        Console.ReadLine();
    }
}

If you want to use ssl on the connection. You should use port 465 for ssl or 587 for tls.

Tip: Try it first without ssl, and add it after you've got things working.

Link: http://www.checktls.com/tests.html to see some starttls examples.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!