How to validate smtp credentials before sending mail?

我们两清 提交于 2019-12-28 01:34:48

问题


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?


回答1:


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.




回答2:


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




回答3:


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.




回答4:


.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)




回答5:


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.




回答6:


Try this:

try
{
   smtpClient.Send(new MailMessage("test@test.com", "test@test.com", "test", "test"));
   return string.Empty;
}
catch (SmtpFailedRecipientException)
{
   return string.Empty;
}
catch (Exception ex)
{
   return string.Format("SMTP server connection test failed: {0}", ex.InnerException != null ? ex.InnerException.Message : ex.Message);
}

It works for me in my validation method. But if you only need to check credentials on sending email, then just surround your sending with try...catch.



来源:https://stackoverflow.com/questions/2426098/how-to-validate-smtp-credentials-before-sending-mail

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!