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.
[905 byte] By [
HotQQ] at [2008-1-22]

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
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.
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>
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.
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" />
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.
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#
One more clue, even if you set the timeout value to be 1, it still stuck at the same place.
Thanks
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.
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.
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! 
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.
I have filed a bug internally and would let you know what the resolution was. Thanks for the information.
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.
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
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
Ranjith,The System.Net.log file could be found in the Bin folder if the app was launched from there.
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
'<<=================================================
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
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.
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
mahjayar,
Thanks for your patient. And give me any comment.
Thank you!!
Glad to be of help


I'm using VS 2005 express and the issue is not solved.
Do you have an update on the issue mahjayar?
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
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!
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) { } |
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.
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.Mail6. build, run, click the button and your email should be sent.
Hope this helps!
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." 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)
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.
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.
Hello,
I am using VB.Net 2005 and SMTPCLient
My code is as follows:
Dim
cred As New System.Net.NetworkCredentialcred.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?
I'm using VS 2005. Having the same problem.
What to do?
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
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 =
FalseaSMTP.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.