How to use System.Net.Mail.SmtpClient via SSL and Authentication?

 Below is my code, and is just blocked there. There is no any error message.

'=============================================>
        Dim msg As String = "---"
        Try
            Dim strAddress As String = "xxx@xxxx.com"
            Dim sm As New SmtpClient(Host, Port)
            With sm
                .EnableSsl = True
                .Credentials = New NetworkCredential("MyuserName", "MyPass")
            End With

            Dim _from As MailAddress = New MailAddress(strAddress)
            Dim _to As MailAddress = New MailAddress(strAddress)
            Dim mMsg As New MailMessage(_from, _to)
            mMsg.Subject = "Happy AAA"

            sm.Send(mMsg)

            msg = "Seccess!"

        Catch ex As Exception
            msg = ex.Message
        End Try

        TextBox1.Text = msg

'<<=================================================

Thanks for any suggestion.




Answer this question

How to use System.Net.Mail.SmtpClient via SSL and Authentication?

  • ffe_bob

    Hi,
    We have identified the problem and have also checked in the fix. You should see this working in the next release of Whidbey 2.0 (Final version).

    Thanks again for the feedback and reporting the problem.


  • keenan10000


    I tried to test four kind of clients again and the results are as the following:

    -------------------------------->
    Smtp Server: smtp.gmail.com
                  port: 465

    Client 1: Seccess!
                Using The Security Library at http://www.mentalis.org + VS.NET 2003

    Client 2: Seccess! (it has been fixed)
                Using Microsoft Outlook 2003

    Client 3: Seccess!
                Using Gmail API v0.7.x at http://sourceforge.net/projects/gmail-api/ + VS.NET 2003

    Client 4: Failed! Tongue Tied
                Using System.Net.Mail.SmtpClient in VS.NET 2005 Beta 2

    <--------------------------------

    I think System.Net.Mail.SmtpClient must have got something lost.

    Thnaks for any suggestion.



  • sat8003

    Your code looks correct.  If you are using Windows integrated authentication you might also need to set the domain on the credential that you are using.

    It's not clear to me what problem you are seeing.  Does the call to Send block   Does the call ever timeout   Do you get any exceptions   Does the send appear to work, but you don't receive the message

    Daniel Roth
    System.Net



  • Raghavendra Prabhu

    Thanks. I rearrange all infomation as follow

    The code
    ----------------------------------------->
            Dim msg As String = "---"
            Try
                Dim strAddress As String = "xxx@xxxx.com"
                Dim sm As New SmtpClient(Host, Port)
                With sm
                    .EnableSsl = True
                    .Credentials = New NetworkCredential("MyuserName", "MyPass")
                    .TimeOut = 20000       ' I add this extra line
                End With
                Dim _from As MailAddress = New MailAddress(strAddress)
                Dim _to As MailAddress = New MailAddress(strAddress)
                Dim mMsg As New MailMessage(_from, _to)
                mMsg.Subject = "Happy AAA"

                sm.Send(mMsg)

                msg = "Seccess!"

            Catch ex As Exception
                msg = ex.Message
            End Try

            TextBox1.Text = msg
    <-------------------------------------------------

    The App.exe.config
    -------------------------------------------------->
    <system.diagnostics>
            <sources>
                <!-- This section defines the logging configuration for My.Application.Log in Windows Forms projects.-->
                <source name="Microsoft.VisualBasic.Logging.Log.WindowsFormsSource" switchName="DefaultSwitch">
                    <listeners>
                        <add name="FileLog"/>
                        <!-- Uncomment the below section to write to the Application Event Log -->
                        <!--<add name="EventLog"/>-->
                    </listeners>
                </source>

       
               <source name="System.Net">
                       <listeners>
                            <add name="System.Net"/>
                       </listeners>
                 </source>
                 <source name="System.Net.Sockets">
                       <listeners>
                            <add name="System.Net"/>
                       </listeners>
                </source>
                <source name="System.Net.Mail">
                       <listeners>
                            <add name="System.Net"/>
                       </listeners>
                </source>
       </sources>
       <switches>
                <add name="DefaultSwitch" value="Information" />

                <add name="System.Net" value="Verbose" />
                   <add name="System.Net.Sockets" value="Verbose" />
                   <add name="System.Net.Mail" value="Verbose" />

      </switches>
      <sharedListeners>
                <add name="FileLog"
                     type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.1200.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"
                     initializeData="FileLogWriter"/>

                <add name="System.Net"
                              type="System.Diagnostics.TextWriterTraceListener"
                              initializeData="System.Net.log"/>

       <!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
                <!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> -->
            </sharedListeners>

      <trace autoflush="true" />

      </system.diagnostics>
    <--------------------------------------------------


    I got the System.NET.log as follow
    --------------------------------------------------->
    System.Net Information: 0 : HeaderCollection#2192437::Set(mime-version)
    System.Net Information: 0 : Exiting HeaderCollection#2192437::Set()
    System.Net Information: 0 : SmtpClient#14011335::Send(using delivery method: Network)
    System.Net.Sockets Information: 0 : Socket#48657371::Socket(InterNetwork#2)
    System.Net.Sockets Information: 0 : Exiting Socket#48657371::Socket()
    System.Net.Sockets Information: 0 : Socket#48657371::Connect(109:465#1839982737)
    System.Net.Sockets Information: 0 : Exiting Socket#48657371::Connect()
    System.Net Information: 0 : SmtpTransport+SmtpReplyStream#55492274::Close()
    System.Net Information: 0 : BufferedReadStream#39948218::Read(Byte[]#1689058)
    System.Net Information: 0 : Exiting BufferedReadStream#39948218::Read()  -> 0#0
    System.Net Information: 0 : BufferedReadStream#39948218::Read(Byte[]#1689058)
    System.Net.Sockets Information: 0 : Socket#48657371::Receive()
    System.Net.Sockets Information: 0 : Socket#48657371::Dispose()
    System.Net.Sockets Error: 0 : Exception in the Socket#48657371::Receive - The process is ternimated by WSACancelBlockingCall 。
    System.Net Error: 0 : Exception in the SmtpClient#14011335::Send - Unable to read data from the transport connection.
    System.Net Error: 0 :    at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
       at System.Net.DelegatedStream.Read(Byte[] buffer, Int32 offset, Int32 count)
       at System.Net.BufferedReadStream.Read(Byte[] buffer, Int32 offset, Int32 count)
       at System.Net.Mail.SmtpTransport.SmtpReplyStreamFactory.Read(SmtpReplyStream caller, Byte[] buffer, Int32 offset, Int32 count)
       at System.Net.Mail.SmtpTransport.SmtpReplyStreamFactory.Close(SmtpReplyStream caller)
       at System.Net.Mail.SmtpTransport.SmtpReplyStream.Close()
       at System.Net.Mail.SmtpTransport.SmtpConnection.Connect(String host, Int32 port)
       at System.Net.Mail.SmtpTransport.Connect(String host, Int32 port)
       at System.Net.Mail.SmtpClient.Connect()
       at System.Net.Mail.SmtpClient.Send(MailMessage message)
    <-------------------------------------------------------------

    Thanks again.



  • Mark Chad

    Hi, the result in your debug is really interesting and helpful.

    Someone said that the Google adopts the Security Library at http://www.mentalis.org to develop gmail service (I do not know if it is true). So I tried to use the Security Lib and successly sent mail via gmail.

    So I guess System.Net.Mail.SmtpClient must have something missed.

    Thanks.



  • Suresh K

    That is interesting. I tried hooking up a delegate for Remote Servr certificate validation and wanted to see if we get past the point of atleast completing the SSL handshake.


    The code I added was


    public static bool RemoteServerCertificateValidationCallback(
     Object sender,
     X509Certificate certificate,
     X509Chain chain,
     SslPolicyErrors sslPolicyErrors)
     {
      Console.WriteLine("Remote Server Cert validation callback called");
      Console.WriteLine(sslPolicyErrors);
      return sslPolicyErrors == SslPolicyErrors.None;
     }

    and I enabled this in my main code by calling
       ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
       ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(RemoteServerCertificateValidationCallback);

    I even tried setting the Security protocol to Tls.

    For port 465, the SSL handshake was never completed. Then I tired the other port specifed at gmail 587 and here is the output I got

    C:\Work>GmailSample.exe
    Remote Server Cert validation callback called
    None
    System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The ser
    ver response was: 5.7.0 Authentication Required
       at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response)
       at System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, String from)
       at System.Net.Mail.SmtpTransport.SendMail(MailAddress from, MailAddressCollection recipients, SmtpFailedRecipientExce
    ption& exception)
       at System.Net.Mail.SmtpClient.Send(MailMessage message)
       at GmailSample.Main(String[] args)

    Note that this time it completed the SSL handshake but the authentication failed. I will need to do some more debugging on this to find out whats wrong but if I had to guess I would guess that the gmail Smtp server is doing something out of the ordinary. I will post the progress on this tomorrow.



  • Greg Balajewicz

    Daniel, thanks for your response.

    I'm not using Windows integrated authentication, because I took Gmail to test the SSL function in SmtpClient. 

    My problem is that the call timeout. I think the Authentication is where the problem exist. I do'nt know how to fix it.

    Thanks again. 

  • Chris V

    Hi,
    Try enabling logging and look at the log file to see where the framework is waiting. My guess is that its waiting for response from the server.

    To enable logging, add the following to your app.exe.config

    <configuration>
        <system.diagnostics>
            <sources>
                <source name="System.Net">
                    <listeners>
                        <add name="System.Net"/>
                    </listeners>
                </source>
                <source name="System.Net.Sockets">
                    <listeners>
                        <add name="System.Net"/>
                    </listeners>
                </source>
            </sources>
            <switches>
                <add name="System.Net" value="Verbose" />
                <add name="System.Net.Sockets" value="Verbose" />
            </switches>
            <sharedListeners>
                <add name="System.Net"
                    type="System.Diagnostics.TextWriterTraceListener"
                    initializeData="System.Net.log"
                    />
            </sharedListeners>
            <trace autoflush="true" />
        </system.diagnostics>
    </configuration>

  • bw_123

    Hi,

    Looks like every one else is having the same problem with other email clients. Check the gmail forums at
    http://groups-beta.google.com/group/Gmail-Help-Discussion/browse_thread/thread/9da19ee0e4dd0035/e27da117136675e2#e27da117136675e2

    Their problem (repeatdly asking for password) is correct with my analysis on port 587. As for the other port, looks like gmail is indeed having some trouble
    Mahesh

  • _Alen_

    One more clue, even if you set the timeout value to be 1, it still stuck at the same place.

    Thanks

  • soulmate75

    HI,
    Well it looks like we are erroring out on receive from the server.  But we need more information. Did you enable the log to verbose..because all I see is Error and Information. Also could you also add the System.Net.Mail listener. Just add this to your existing config file under configuration\system.diagnostics\sources

    <source name="System.Net.Mail">
                    <listeners>
                        <add name="System.Net"/>
                    </listeners>
    </source>

    and under switches add this
    <add name="System.Net.Mail" value="Verbose" />





  • Julius Rastad

    I have filed a bug internally and would let you know what the resolution was. Thanks for the information.

  • listerg

    Hi, thanks for your suggestion.

    I got some error messages as follow

    --------------------->
    ystem.Net Information: 0 : HeaderCollection#37460558::Set(mime-version)
    System.Net Information: 0 : Exiting HeaderCollection#37460558::Set()
    System.Net Information: 0 : SmtpClient#59487907::Send(using delivery method: Network)
    System.Net.Sockets Information: 0 : Socket#23085090::Socket(InterNetwork#2)
    System.Net.Sockets Information: 0 : Exiting Socket#23085090::Socket()
    System.Net.Sockets Information: 0 : Socket#23085090::Connect(111:465#1874454673)
    System.Net.Sockets Information: 0 : Exiting Socket#23085090::Connect()
    System.Net Information: 0 : SmtpTransport+SmtpReplyStream#6964596::Close()
    System.Net Information: 0 : BufferedReadStream#17113003::Read(Byte[]#30544512)
    System.Net Information: 0 : Exiting BufferedReadStream#17113003::Read()  -> 0#0
    System.Net Information: 0 : BufferedReadStream#17113003::Read(Byte[]#30544512)
    System.Net.Sockets Information: 0 : Socket#23085090::Receive()
    System.Net.Sockets Information: 0 : Socket#23085090::Dispose()
    System.Net.Sockets Error: 0 : Exception in the Socket#23085090::Receive - break the process by WSACancelBlockingCall 。
    System.Net Error: 0 : Exception in the SmtpClient#59487907::Send - Unable to read data from the transport connection.
    System.Net Error: 0 :    at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
       at System.Net.DelegatedStream.Read(Byte[] buffer, Int32 offset, Int32 count)
       at System.Net.BufferedReadStream.Read(Byte[] buffer, Int32 offset, Int32 count)
       at System.Net.Mail.SmtpTransport.SmtpReplyStreamFactory.Read(SmtpReplyStream caller, Byte[] buffer, Int32 offset, Int32 count)
       at System.Net.Mail.SmtpTransport.SmtpReplyStreamFactory.Close(SmtpReplyStream caller)
       at System.Net.Mail.SmtpTransport.SmtpReplyStream.Close()
       at System.Net.Mail.SmtpTransport.SmtpConnection.Connect(String host, Int32 port)
       at System.Net.Mail.SmtpTransport.Connect(String host, Int32 port)
       at System.Net.Mail.SmtpClient.Connect()
       at System.Net.Mail.SmtpClient.Send(MailMessage message)
    <-----------------------------------------

    I still do'nt know how to handle this problem. Thanks for any suggestion.


  • Catdaemon

    I also ran into the same problem. I used debugger to break it to grab the stack as shown below. Then, I F5 to continue and borke it again. It was at the same stack. Therefore, I believe it was stuck at this call stack.

    Help will be much appreciated.

    Thanks

      System.dll!System.Net.Sockets.Socket.Receive(byte[] buffer = {Dimensions:[256]}, int offset = 0, int size, System.Net.Sockets.SocketFlags socketFlags = None, out System.Net.Sockets.SocketError errorCode = Success) + 0x12e bytes 
      System.dll!System.Net.Sockets.Socket.Receive(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags) + 0x1d bytes 
      System.dll!System.Net.Sockets.NetworkStream.Read(byte[] buffer, int offset, int size) + 0x78 bytes 
      System.dll!System.Net.DelegatedStream.Read(byte[] buffer, int offset, int count) + 0x2a bytes 
      System.dll!System.Net.BufferedReadStream.Read(byte[] buffer, int offset, int count) + 0x61 bytes 
      System.dll!System.Net.Mail.SmtpReplyStreamFactory.ReadLines(System.Net.Mail.SmtpReplyStream caller, bool oneLine) + 0x119 bytes 
      System.dll!System.Net.Mail.SmtpReplyStreamFactory.ReadLine(System.Net.Mail.SmtpReplyStream caller) + 0x1b bytes 
      System.dll!System.Net.Mail.SmtpReplyStream.ReadLine() + 0xd bytes 
      System.dll!System.Net.Mail.SmtpConnection.GetConnection(string host = "smtp.gmail.com", int port = 465) + 0x328 bytes 
      System.dll!System.Net.Mail.SmtpTransport.GetConnection(string host, int port) + 0x13d bytes 
      System.dll!System.Net.Mail.SmtpClient.GetConnection() + 0x2b bytes 
      System.dll!System.Net.Mail.SmtpClient.Send(System.Net.Mail.MailMessage message = {System.Net.Mail.MailMessage}) + 0x63b bytes 
    > test4.EXE!SendMailTest.SendMailTest.SendMailNET2() Line 41 + 0xd bytes C#
      test4.EXE!SendMailTest.SendMailTest.Main(string[] args = {Dimensions:[0]}) Line 20 + 0x5 bytes C#

  • How to use System.Net.Mail.SmtpClient via SSL and Authentication?