I need to validate the username and password set in an SmtpClient
instance before sending mail. Using this code:
SmtpClient client = new SmtpClient(host);
client.Credentials = new NetworkCredential(username,password);
client.UseDefaultCredentials = false;
// Here I need to verify the credentials(i.e. username and password)
client.Send(mail);
How can I validate whether the user identified by the credentials is allowed to connect and send a mail?
From the Tools menu, choose Account Settings. Select your email account from the list, then click Change. On the Change E-mail Settings window, click More Settings. Click the Outgoing Server tab, then check the My outgoing server (SMTP) requires authentication option.
SMTP Authentication, often abbreviated SMTP AUTH, is an extension of the Simple Mail Transfer Protocol (SMTP) whereby a client may log in using any authentication mechanism supported by the server. It is mainly used by submission servers, where authentication is mandatory.
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.
My production code for username and password validation before sending mail:
public static bool ValidateCredentials(string login, string password, string server, int port, bool enableSsl) {
SmtpConnectorBase connector;
if (enableSsl) {
connector = new SmtpConnectorWithSsl(server, port);
} else {
connector = new SmtpConnectorWithoutSsl(server, port);
}
if (!connector.CheckResponse(220)) {
return false;
}
connector.SendData($"HELO {Dns.GetHostName()}{SmtpConnectorBase.EOF}");
if (!connector.CheckResponse(250)) {
return false;
}
connector.SendData($"AUTH LOGIN{SmtpConnectorBase.EOF}");
if (!connector.CheckResponse(334)) {
return false;
}
connector.SendData(Convert.ToBase64String(Encoding.UTF8.GetBytes($"{login}")) + SmtpConnectorBase.EOF);
if (!connector.CheckResponse(334)) {
return false;
}
connector.SendData(Convert.ToBase64String(Encoding.UTF8.GetBytes($"{password}")) + SmtpConnectorBase.EOF);
if (!connector.CheckResponse(235)) {
return false;
}
return true;
}
More details in the answer to a similar question.
Code on github
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With