views:

482

answers:

4

I need to validate the username and password set in SmtpClient object before sending mail.

Here is the code sample:

SmtpClient client=new SmtpClient(host);
client.Credentials=new NetworkdCredentials(username,password);
client.UseDefaultCredentials=false;

//Here I need to verify the credentials(i.e. username and password)
client.Send(mail);

Thanks in advance.....

+1  A: 

There is no way.

SmtpClient bascially can not validate the usernamepassword without contacting the serve it connects to.

What you could do is do it outside SmtpClient, by opening a TCP connection to the server... but authentication CAN be complicated depending how the server is configured.

May I ask WHY you need to know that before sending? normal behavior IMHO would be to wrap sending in appropriate error handling to catch exceptions here.

TomTom
I needed to know if validating can be done. As it happens in MS outlook that before sending mails, it asks for username and password if it is wrong. I wanted to do the same in my application. I appreciate your help.
Manish Gupta
A: 

Validating before, sending mail is not possible with the SMTP client class in .net 2.0.

Attempting to validate by hand, by opening a port is as good as writing your own SMTP client, it is complex.

panzerschreck
A: 

.Net's SmtpClient does not allow you to login without sending a message.

You can check credentials by sending a test message to some extant address that ignores incoming email and checking whether you get an exception.

Note that these test emails will appear in your account's sent folder, if any (eg, Gmail)

SLaks
A: 

I agree with the previous answers, that SmtpClient cannot validate without sending.

But maybe your problem can be solved anyway: If username or password are wrong, client.Send(mail); will throw an exception. You can build a while-loop and a try-catch-block around the sending, catch the exception and ask the user for the correct username and password, then try again. If the user clicks cancel on the dialog or sending succeeds without exception, you exit the while-loop.

Hinek