I'm building a windows forms application that's supposed to run on a remote/isolated machine and send error notifications by email to the admins. I've tried employing System.Net.Mail
classes to achieve this but I'm running into a strange problem:
1. I get an error message:
System.IO.IOException: Unable to read data from the transport connection:
An existing connection was forcibly closed by the remote host.--->
System.Net.Sockets.SocketException: An existing connection was forcibly closed by
the remote host at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset,
Int32 size, SocketFlags socketFlags) at System.Net.Sockets.NetworkStream.
Read(Byte[] buffer, Int32 offset, Int32 size)
2. I tried sniffing the network activity to see what was going wrong. So here's how it goes:
i) The DNS lookup for my SMTP server's hostname works
ii) My application connects to the SMTP server and sends "EHLO MY-HOSTNAME"
iii) SMTP server responds back with it's usual
iv) My application sends "AUTH login abcdxyz" and receives an acknowledgement packet
At this point, it seems that either the SMTP server doesn't seem to request for the password or my machine shuts off the connection to the SMTP server before the SMTP server could request for a password.
I've tried using different SMTP ports and SMTP hosts. Also, I tried disabling my firewall and AV, but no luck. While connecting to my SMTP server using PuTTY and issuing the same sequence of commands as my application does (picked from the packet sniffer), everything works out fine and I'm able to send out the email.
Here's the code that I'm using:
Imports System.Net
Imports System.Net.Mail
Public Function SendMail() As Boolean
Dim smtpClient As New SmtpClient("smtp.myserver.com", 587) 'I tried using different hosts and ports
smtpClient.UseDefaultCredentials = False
smtpClient.Credentials = New NetworkCredential("username@domain.com", "password")
smtpClient.EnableSsl = True 'Also tried setting this to false
Dim mm As New MailMessage
mm.From = New MailAddress("username@domain.com")
mm.Subject = "Test Mail"
mm.IsBodyHtml = True
mm.Body = "<h1>This is a test email</h1>"
mm.To.Add("someone@domain.com")
Try
smtpClient.Send(mm)
MsgBox("SUCCESS!")
Catch ex As Exception
MsgBox(ex.InnerException.ToString)
End Try
mm.Dispose()
smtpClient.Dispose()
Return True
End Function
Any advice?
In C# it works like this:
Do not forget the
using System.Net.Mail;
I Think in VB it works like this to, here is the code, it might have some errors, I don't often write in vb.net:
Do not forget to import
System.Net.Mail
try to use this:
dont forget to call:
SendMail.Design