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

    Question

  •  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.

    Friday, May 06, 2005 10:33 PM

Answers

  • HotQQ,

    Is this still with the Gmail server? If yes then read on or else please specify what server you are using and what error you are seeing.

    Gmail Smtp has 2 ports exposed 465 and 587. 465 port is for Exchange structre and thats why the Smtp protocol doesnt work against it. We have testcases internally that try to send mail to port 587 of gmail and it has been working fine.

    Let us know how it goes when you try it against port 587

    Wednesday, September 21, 2005 5:11 PM
    Moderator

All replies

  • 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

    Tuesday, May 10, 2005 5:08 PM
    Moderator
  • 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. 
    Tuesday, May 10, 2005 9:35 PM
  • 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>
    Thursday, May 12, 2005 4:06 AM
    Moderator
  • 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.
    Thursday, May 12, 2005 10:40 PM
  • 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" />



    Friday, May 13, 2005 10:01 PM
    Moderator
  • 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.

    Friday, May 13, 2005 11:26 PM
  • 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#
    • Proposed as answer by ABetterWay Wednesday, August 10, 2011 10:27 PM
    Saturday, May 14, 2005 1:26 AM
  • One more clue, even if you set the timeout value to be 1, it still stuck at the same place.

    Thanks
    Saturday, May 14, 2005 1:30 AM
  • 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.

    Thursday, May 19, 2005 7:41 AM
    Moderator
  • 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.

    Thursday, May 19, 2005 1:25 PM
  • 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
    Thursday, May 19, 2005 8:09 PM
    Moderator

  • 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.

    Friday, May 20, 2005 1:56 AM
  • I have filed a bug internally and would let you know what the resolution was. Thanks for the information.
    Monday, May 23, 2005 11:10 PM
    Moderator
  • 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.
    Tuesday, May 24, 2005 8:31 PM
    Moderator
  • Hi,

    Thanks.
    Wednesday, May 25, 2005 9:52 PM
  • Hi

    I am having a similar issue with System.net. I have a Client Windows application which and i am using the following code to check the URL and i am getting error in some clients. There is no proxies or Firewalls in the middle.

    I added the above code to see the error but it's not writing theSystem.Net.log file. Where does it write in which folder.

    Thank you,
    Ranjith
    Thursday, June 23, 2005 5:41 PM
  • Make sure the config file is named [appname].exe.config and then the log file should be generated from the directory where the app was launched from

    Let  me know what happens

    Btw, this will work with Beta2 of the framework only. The logging for beta1 was slightly different
    Mahesh

    Friday, June 24, 2005 3:54 AM
    Moderator
  • Ranjith,

    The System.Net.log file could be found in the Bin folder if the app was launched from there.
    Friday, June 24, 2005 7:01 AM
  • Test Reporting:

    The code below still has the same bug as before.
    It does not work in the RC version of VS.NET 2005.

    '=============================================>
            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

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

    Wednesday, September 21, 2005 1:37 AM
  • HotQQ,

    Is this still with the Gmail server? If yes then read on or else please specify what server you are using and what error you are seeing.

    Gmail Smtp has 2 ports exposed 465 and 587. 465 port is for Exchange structre and thats why the Smtp protocol doesnt work against it. We have testcases internally that try to send mail to port 587 of gmail and it has been working fine.

    Let us know how it goes when you try it against port 587

    Wednesday, September 21, 2005 5:11 PM
    Moderator
  • mahjayar,

    I tried to send mail to 587 of gmail and it works fine.
    The port 465, just like you said, Failed.

    Thankx.

    I have another test:
    I try it against port 465 using The Security Library at http://www.mentalis.org and Smtp protocol and it works fine too.

    So you confuse me by the words: 465 port is for Exchange structre and thats why the Smtp protocol doesnt work against it.

    Thanks for any opinion.

    Thanks again.

    Wednesday, September 21, 2005 10:14 PM
  • Hotqq,
    My bad. I should have been more clearer. What I meant was that port 465 is for Outlook clients to connect and in our internal testing we found out that our Smtp + auth implementation does not exactly mimic the Outlook Smtp+auth implementation. Thats why we had to go to the "Other SMtp Client port" on google.

    Let me know if you are still unclear.

    Mahesh
    Thursday, September 22, 2005 6:38 PM
    Moderator
  • mahjayar,

    Thanks  for your patient. And give me any comment.

    Thank you!!
    Friday, September 23, 2005 6:44 AM
  • Glad to be of helpSmile
    Friday, September 23, 2005 9:04 PM
    Moderator
  • Sad

    I'm using VS 2005 express and the issue is not solved.

    Do you have an update on the issue mahjayar???
    Monday, November 14, 2005 11:23 AM
  • If you have some sample code for this then do send me as i am facing the same problem and not getting how to use Security Lib.

    Thanks
    Monday, November 28, 2005 12:27 PM
  • Hi guys, I've just been having this very same port 465 problem. half hour of looking at output from Ethereal and scratching my head. Finally a search on Google threw up your good advice. I switched to port 587 and my code works fine.

     

    I’m using Visual Studio 2005 Professional RTM.


    Thanks!



    Tuesday, November 29, 2005 5:13 PM
  • 587 - Thanks!!! It works now!!!


    MailMessage msgMail = new MailMessage("?????@gmail.com", "??????@mail.ru", "subject", "message body");
    SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
    smtp.EnableSsl = true;
    smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
    smtp.Credentials = new System.Net.NetworkCredential("?????@gmail.com", "?????");
    try
    {
       smtp.Send(msgMail);
    }
    catch (Exception ex)
    {
    }

     

    Tuesday, November 29, 2005 7:55 PM
  • Hi,

    I tried a lot but failed to get sucess in sending mail using GMAIL. I tried with visual studio 2005 (RTM) but still not getting any success.

    Dragoljub, i tried with the code you posted but its not working. If you have some other code which it tested and worknig then please post it so that it will help others.
    Tuesday, December 06, 2005 9:25 AM
  • Hi Bhavesh,

    I've just taken the code written by Dragoljub, changed it into vb.net,  and added a few constants. His code works fine. My variation of it works fine.

    You have probably checked the following but anyway:

    1. Is your google account valid and active ?
    2. Do you have a firewall or something preventing the email getting out ?
    3. Is your internet connectivity ok ?
    3. What error do you get exactly ?


    Heres my vb.net code, its trivial to convert to C#

    To reuse

    1. run vs 2005
    2. create new winforms vb.net project
    3. add button to form
    4 double click button and past this code, replacing ??? with your username and password - check you can loginto google using web interface



    Const googleMailPortNumber As Integer = 587

    ' Replace ???? with your username and password as appropiate

    Const userName As String = "???????"

    Const passWord As String = "???????"

    Dim msgMail As MailMessage

    Dim smtp As SmtpClient

    'Example send email from self to self, just to show it works

    msgMail = New MailMessage(userName, userName, "subject", "message body")

    'Very important to use port 587 as port port 465 simply doesnt work with

    '.NET smtp class

    smtp = New SmtpClient("smtp.gmail.com", googleMailPortNumber)

    'SSL must be enabled as google nicely uses encryption

    smtp.EnableSsl = True

    smtp.DeliveryMethod = SmtpDeliveryMethod.Network

    smtp.Credentials = New System.Net.NetworkCredential(userName, passWord)

    smtp.Send(msgMail)


    5. at top of source file add

    Imports System.Net.Mail


    6. build, run, click the button and your email should be sent.


    Hope this helps!
    Tuesday, December 06, 2005 12:42 PM
  • Hi bamboowave,

    Thanks for your quick reply. I tried with the code you sent and came across the error which is given below.

    "The remote certificate is invalid according to the validation procedure."

    I tried to answer all your questions also.
    1. Is your google account valid and active ?
    Bhavesh -> Yes it is valid, active and working properly.

    2. Do you have a firewall or something preventing the email getting out ?
    Bhavesh -> No, there is nothnig like that which prevents for sending or receiving mail. I tried with my company a/c for which server is hosted outside and its worknig fine.

    3.Is your internet connectivity ok ?
    Bhavesh -> Yes, its connected and worknig.

    4. What error do you get exactly ?
    Bhavesh ->
    "The remote certificate is invalid according to the validation procedure."

    Wednesday, December 07, 2005 6:03 AM
  • Hi again Bhavesh,

    In short I don't have a solution, but have a few suggestions to help you track down your problem.

    "The remote certificate is invalid according to the validation procedure."

    I believe this is saying some thing like the domain name encoded into the certificate does not match the domain name of the site. (we are using SSL)

    eg If you type into a browser https://gmail.com you get a certificate error, if you enter https://gmail.google.com you don’t get the error as that’s the correct domain name for the certificate.

    However back to SMTP, I've just rerun my posted code and I can still send email fine.

    I tried using both
    smtp.googlemail.com and smtp.gmail.com and both send email fine.

    So there is possibly something strange about your machine's setup, security or perhaps domain security or maybe Google was just having a bad day when you tried ?


    I did a search on Google and came up with something which may help you track down the problem. The article describes how you can enable System.Net tracing to display detailed information

    http://blogs.msdn.com/dgorti/archive/2005/09/18/471003.aspx

    Add an app.config file to your project and paste in the supplied config file, found below the section titled

    "You can enable both the Sockets and System.Net sources with the following config file "

    Now run your app, try and send an email, then look in the bin/debug folder for the file. In this file you will find  

    system.net.trace.log - this contains lots of detailed information.

    In particular look at the [Subject] section. This is showing the DNS of the ertificate as being smtp.googlemail.com which matches the smtp port I am using.
    See what yours says.


    [Subject]
      CN=smtp.googlemail.com, O=Google Inc, L=Mountain View, S=California, C=US
      Simple Name: smtp.googlemail.com
      DNS Name: smtp.googlemail.com



    I hope this helps you solve your problem. Please let us know what the solution to your problem is, or perhaps post your log file for others to comment on  (make sure you log file doesn’t contain anything sensitive you wouldn’t want others to see)

    Thursday, December 08, 2005 8:28 PM
  • hi bamboowave,

    I got success in sending mails to using gmail smtp. I tried with the suggestions you mentioned and it worked.

    Previously I was using IP address instead of smtp.googlemail.com and due to this it was not allowing.

    Currently its working with smtp.googlemail.com but not with smtp.gmail.com.

    I have one more question for you, Is it possible with .net framework 2.0 to use POP with SSL. If yes then please tell me the way with which its possible.

    Thanks for all your support and I really appreciate your help.


    Tuesday, December 13, 2005 11:26 AM
  • Thank you very much for this information. I almost gave up System.Net.Mail and use System.Web.Mail instead because of the port 465 issue.
    Monday, March 13, 2006 7:59 PM
  • Hello,

    I am using VB.Net 2005 and SMTPCLient

    My code is as follows:

    Dim cred As New System.Net.NetworkCredential

    cred.UserName = ("uname")

    cred.Password = ("pwd")

    Dim mailServerName As String = "mypopserver"

    subj = "Confirmation Mail from us"

    Dim message As MailMessage = New MailMessage("me@domain.com", "you@domain.com", subj, "This mail is a confirmation Mail I")

    Dim mailclient As New SmtpClient ("mysmtpmailserver", 465)

    message.BodyEncoding = Encoding.Default

    mailclient.Host = mailServerName

    mailclient.EnableSsl = True

    mailclient.DeliveryMethod = SmtpDeliveryMethod.Network

    mailclient.UseDefaultCredentials = False

    mailclient.Credentials = cred

    mailclient.Send(message)

    message.Dispose()

    It gives the following error:

    System.Exception.InnerException {"A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond"} 

    Any guessess?

     

    Tuesday, November 28, 2006 1:37 PM
  • I'm using VS 2005. Having the same problem.
    What to do????
       
    Tuesday, June 05, 2007 5:51 AM
  • Hi Jay,

    I am trying the same code to send an automatic email same code works for my gmail account but when i try to send the mail from my company SMTP account timeout error is coming with the same timeout exception and again the error of blocking request is coming. can you provide some help for that also.

     

    thanks

    Vineet

    Thursday, June 28, 2007 7:04 AM
  • I test with this code:

     

    Dim aSMTP As Net.Mail.SmtpClient

    Dim credential As Net.NetworkCredential

    aSMTP = New Net.Mail.SmtpClient(Server)

    credential = New Net.NetworkCredential("", login + vbCrLf + password)

    'credential = New Net.NetworkCredential(login,password)

    aSMTP.Credentials = credential

    aSMTP.DeliveryMethod = Net.Mail.SmtpDeliveryMethod.Network

    aSMTP.EnableSsl = False

    aSMTP.Send(From, To, "Test", "This is an example")

     

    It's ok

    When i use ".net reflector" for decompile "system.net.mail.SmtpLoginAuthenticationModule" the code send only password, not the login to the SMTP server.

     

    Friday, June 29, 2007 4:07 PM
  • Try removing
    .EnableSsl = True
    and adding
    .UseDefaultCredentials = False

    This is how i do mine and it works fine

                Dim emailClient As New Net.Mail.SmtpClient(kSMTPServer, kSMTPPort)
                emailClient.UseDefaultCredentials = False
                emailClient.Credentials = New System.Net.NetworkCredential(kSMTPUser, kSMTPPassword)
                emailClient.Send(New Net.Mail.MailMessage(kSMTPEmail, kSendTo, GetSubject(bugType), GetHeader() & bugMsg))
    Tuesday, November 13, 2007 10:08 PM
  •  

    I've a similar code, but in my case my pop is an enterprise server. Our Pop use an 465 port and SSL actived. But always my application response Time-out. I've enable the log and that's the lines about problem, but i understand were's the reality problem:

     

    System.Net.Sockets Error: 0 : [4444] Exception in the Socket#60844870::Receive - Una operación de bloqueo fue interrumpida por una llamada a WSACancelBlockingCall
    System.Net.Sockets Verbose: 0 : [4444] Exiting Socket#60844870::Receive()  -> 0#0
    System.Net Error: 0 : [4444] Exception in the SmtpClient#65893722:Tongue Tiedend - No se puede escribir datos de en la conexión de transporte: Una operación de bloqueo fue interrumpida por una llamada a WSACancelBlockingCall.
    System.Net Error: 0 : [4444]    en System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
       en System.Net.DelegatedStream.Read(Byte[] buffer, Int32 offset, Int32 count)
       en System.Net.BufferedReadStream.Read(Byte[] buffer, Int32 offset, Int32 count)
       en System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader caller, Boolean oneLine)
       en System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader caller)
       en System.Net.Mail.SmtpReplyReader.ReadLine()
       en System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port)
       en System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port)
       en System.Net.Mail.SmtpClient.GetConnection()
       en System.Net.Mail.SmtpClient.Send(MailMessage message)

     

    Our network use a Proxy to navigate outside the intranet, but the pop is inside, another caracterist of the pop is that use a certiicate when the connection is from outside the network.....

     

    Thanks.

    Thursday, January 17, 2008 11:45 AM
  • There are two types of SSL authentication for SMTP, and System.Net.Mail only supports one. System.Net.Mail does not have the capability for SSL on connect (Implicit SSL) and only supports SSL after protocol negotiation (Explicit SSL). 
     
    Explicit SSL
    ------------
        System.Net.Mail only supports “Explicit SSL”.  Explicit SSL starts as unencrypted on port 25, then issues a STARTDLS and switches to an Encrypted connection.  See RFC 2228.

        Explicit  SLL would go something like: Connect on 25 -> StartTLS (starts to encrypt) -> authenticate -> send data

        If the SMTP server expects SSL/TLS connection right from the start then this will not work.

    Implicit SSL
    ------------
        There is no way to use Implicit SSL (SMTPS) with System.Net.Mail.  Implicit SSL would have the entire connection is wrapped in an SSL layer.  A specific port would be used (port 465 is common).  There is no formal RFC covering Implicit SSL.

        Implicit  SLL would go something like: Start SSL (start encryption) -> Connect -> Authenticate -> send data
     


    Dan
    Monday, June 02, 2008 4:57 PM
  • Ok I know this is an old thread, what I have to ask is directly related to it....

    I have a sub procedure that uses SmtpClient and System.Net.NetworkCredential to send email. My company just moved its email to google. So I am changing an auto report email system to use google as well ...

    If I use this code:

            Dim MailClient As New SmtpClient("smtp.googlemail.com")

            MailClient.Port = 587
            MailClient.EnableSsl = True
            MailClient.DeliveryMethod = SmtpDeliveryMethod.Network
            MailClient.Credentials = New System.Net.NetworkCredential("xxxxx@gmail.com", "password")

    meaning I have it hard coded with literal strings .. I can send email just fine.

    If I do this:

            Dim SMTPServerAddr As String = Configuration.ConfigurationManager.AppSettings("SMTPServerAddress").ToString
            Dim SMTPUser As String = Configuration.ConfigurationManager.AppSettings("SMTPUser").ToString
            Dim SMTPPassword As String = Configuration.ConfigurationManager.AppSettings("SMTPPassword").ToString

            Dim MailClient As New SmtpClient(SMTPServerAddr)

            MailClient.Port = 587
            MailClient.EnableSsl = True
            MailClient.DeliveryMethod = SmtpDeliveryMethod.Network
            MailClient.Credentials = New System.Net.NetworkCredentialSMTPUser, SMTPPassword)

    then the send command fails ... the only difference in the method is that variables are used instead of literals. I checked and rechecked to be 100000% sure that the values in the config file were correct and they are .. I step through the code to be sure the variables are populated and they do ...

    It just doesn't work for me if I have variables in the credentails for the smtp server.

    I even tried an old VB6 trick of putting () around the string var to tell vb to use the literal values, that didn't work either.

    anybody have any idea as to why this would happen?

    Thanks
    Jon

    Wednesday, October 21, 2009 8:13 PM
  • Hi,

    one day of work and I god it. Here is some C# Code what is working when you have a Gmail e-mais account to use the SSL Authentification. Have fun:

     

                    static bool mailSent = false;
                    private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
                    {
                        // Get the unique identifier for this asynchronous operation.
                        String token = (string)e.UserState;

                        if (e.Cancelled)
                        {
                            Console.WriteLine("[{0}] Send canceled.", token);
                        }
                        if (e.Error != null)
                        {
                            Console.WriteLine("[{0}] {1}", token, e.Error.ToString());
                        }
                       else
                        {
                            Console.WriteLine("Message sent.");
                        }
                        mailSent = true;
                    }

           static void Main()
            {

              //using System.Net.Mail;
              //Posteingangsserver: POP3: pop.googlemail.com (SSL; Port 995), IMAP: imap.googlemail.com (SSL; Port 993)
              //Postausgangsserver: smtp.googlemail.com (SSL; Port 465 oder 587)
              //Benutzername: "UserName", "Passwort"
              //Besonderheiten: Verwendet SMTP-Authentifizierung.
              // Command line argument must the the SMTP host.
                SmtpClient client = new SmtpClient("smtp.googlemail.com", 587);

                // Credentials are necessary if the server requires the client
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.Credentials = new NetworkCredential("Your@gmail.com", "xxxxxxx"); //Has to be GMAIL.COM
                //client.UseDefaultCredentials = false; //Do not use false
                client.EnableSsl = true;
                client.Timeout = 20000;


                MailAddress from = new MailAddress("Your@gmail.com",
                   "Your Name " + (char)0xD8+ " Your LastName",
                    System.Text.Encoding.UTF8);
                // Set destinations for the e-mail message.
                MailAddress to = new MailAddress("SendTo@XXXXX.com");
                // Specify the message content.
                MailMessage message = new MailMessage(from, to);
                message.Body = "This is a test e-mail message sent by an application. ";
                message.BodyEncoding =  System.Text.Encoding.UTF8;
                message.Subject = "test message 1" + someArrows;
                message.SubjectEncoding = System.Text.Encoding.UTF8;
                // The userState can be any object that allows your callback
                // method to identify this send operation.
                // For this example, the userToken is a string constant.
                string userState = "test message1";
                client.SendAsync(message, userState);
                string answer = Console.ReadLine();
                // If the user canceled the send, and mail hasn't been sent yet,
                // then cancel the pending operation.
                if (answer.StartsWith("c") && mailSent == false)
                {
                    client.SendAsyncCancel();
                }

                // Clean up.
               
                message.Dispose();
     }

    Sunday, August 08, 2010 5:38 PM
  • PS I use:

     

    using

     

    System;

    using

     

    System.Collections.Generic;

    using

     

    System.Linq;

    using

     

    System.Text;

    using

     

    System.Net;

    using

     

    System.Net.Mail;

    using

     

    System.Net.Mime;

    using

     

    System.Threading;

    using

     

    System.ComponentModel;

    using

     

    System.Net.Security;

    Sunday, August 08, 2010 5:39 PM
  • protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                MailMessage mm = new MailMessage();
                mm.To.Add("Receiver's Mail Address");
                mm.From = new MailAddress("Sender's Mail Address");
                mm.Subject = "SMTP Mail Test";
                mm.Body = "This is the body of test message.";
                SmtpClient sc = new SmtpClient("smtp.gmail.com",587);
                sc.EnableSsl=true;
                sc.Credentials = new NetworkCredential("Mail uid", "Mail pwd");
                sc.Send(mm);
                Response.Write("Mail Sent.");
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }
    Monday, June 13, 2011 6:10 AM
  • Anyone can help me.

    I don't know,how to solve this problem.

    I have download facebook hack software,after that i log in the hack sotfware.

    After that,its said like this :

    ************** Exception Text **************
    System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at                              
       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 sender, MailAddressCollection recipients, String deliveryNotify, SmtpFailedRecipientException& exception)
       at System.Net.Mail.SmtpClient.Send(MailMessage message)
       at Facebook_Clock_v1._2.Form1.ButtonX1_Click(Object sender, EventArgs e)
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at DevComponents.DotNetBar.ButtonX.OnClick(EventArgs e)
       at DevComponents.DotNetBar.ButtonX.OnMouseUp(MouseEventArgs e)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at DevComponents.DotNetBar.PopupItemControl.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

    Thursday, February 23, 2012 6:43 PM
  • Mahjayar:

    From your postings, I infer that you may be one of the employees of Microsoft and that you may be intimately familiar with System.Net.Mail (v4.0, runtime: v4.0.30319)

    I having difficulty sending messages via SMTP using my GMail credentials. I am using VS10 on a Windows 7 client.

    Following information may help you understand my situation:

    1. I get a generic "Failure to send message" error message.

    2. The same GMail account is successfully configured in my Outlook.

    3. In outlook, I see that it uses TLS for encryption of outgoing messages on Port 587. If I change it to SSL and keep the port as 587, even the test message does not go out.

    Can you please guide me in resolving the issue?


    • Edited by TheVenkster Thursday, January 03, 2013 1:44 AM
    Thursday, January 03, 2013 1:43 AM
  • You may have a firewall that is blocking Port 587.  If you are using Net 4.0 or later make sure you set the delivery method to Network (see below) Outlook uses the credentials in the Control Panel : Mail setup utility (the Pop3 account).  You have two ways of connecting to the to the SMTP server.  One is supply the credentials (User ID and Password) in the program.  The other method is to use the default credentials from Control Panel.  If you want to use the POP3 setting set default to true.  trhis should also get around the firewall problems.

                SmtpClient client = new SmtpClient();
                client.DeliveryMethod = SmtpDeliveryMethod.Network;   //<--- Make sure use use this seeting
                client.UseDefaultCredentials = true  //<-  use true to use Control panel settings POP3 account


    jdweng

    Thursday, January 03, 2013 10:54 AM