|
Hello !
i have an application in vb.net 2010 , and i'm using System.Net.Mail to send emails.
is there any way to test smtp connection , before begin to send emails .
Thank you !
|
|
|
|
|
The only way to really test it is to try and send an email. Kind of defeats the purpose now, doesn't it?
|
|
|
|
|
thank you , but i need to check if smtp server is ready , and if not i need to display a warning to user and cancel the sending process. If is ready i can begin sending emails.
i have found this code , but doesn't work when i test with a invalid smtp server name:
public bool ValidSMTP(string hostName)
{
bool valid = false;
try
{
TcpClient smtpTest = new TcpClient();
smtpTest.Connect(hostName, 25);
if (smtpTest.Connected)
{
NetworkStream ns = smtpTest.GetStream();
StreamReader sr = new StreamReader(ns);
if (sr.ReadLine().Contains("220"))
{
valid = true;
}
smtpTest.Close();
}
}
catch
{
throw;
}
return valid;
}
|
|
|
|
|
If you give the Connect method an invalid hostname and port that cannot be connected, it'll throw a SocketException with the error code in it.
if the hostname is a real server but nothing is listening on 25, it'll throw a SocketException.
If the hostname is real and 25 is blocked by a firewall, you'll get a SocketException.
Sooo... what's with the lonely little "throw" statement? Remove that and your code will work. That is, assuming that the SMTP server is listening on port 25...
The problem with this code is that you're only testing the server connection, not the ability to send email. Just because the server responds to a connection request does not mean that the credentials given for the SMTP account to send an email will work.
That's why I said the best way to check is to actually send an email.
|
|
|
|