我正在测试从C#发送电子邮件,因为它使用以下代码:
MailMessage message = new MailMessage();
message.To.Add("user@gmail.com");
message.From = new MailAddress("me@server.com");
message.Subject = "Test subject";
message.Body = "Test body";
SmtpClient client = new SmtpClient("server");
client.Timeout = 10000;
client.EnableSsl = true;
client.UseDefaultCredentials = false;
NetworkCredential credentials = new NetworkCredential("me@server.com", "CorrectPassword");
client.Credentials = credentials;
try
{
client.Send(message); // OK
}
catch (Exception ex)
{
MessageBox.Show("Exception caught in CreateTestMessage2(): {0}", ex.ToString());
}
然后,尝试开始控制连接中断和主要是无效密钥的异常,但是请注意,即使使用了错误的密钥,邮件仍会发送。
NetworkCredential credentials = new NetworkCredential("me@server.com", "BadPassword");
client.Credentials = credentials;
try
{
client.Send(message); // OK, the email has been sent
}
catch (Exception ex)
{
MessageBox.Show("Exception caught in CreateTestMessage2(): {0}", ex.ToString());
}
如何禁用自动保存凭据?或者,如何删除存储的凭据?
答案 0 :(得分:1)
SmtpClient关于这两个属性(UseDefaultCredentials和Credentials)的工作方式由代码MS决定。这是它们的实现方式:
public bool UseDefaultCredentials {
get {
return (transport.Credentials is SystemNetworkCredential) ? true : false;
}
set {
if (InCall) {
throw new InvalidOperationException(SR.GetString(SR.SmtpInvalidOperationDuringSend));
}
transport.Credentials = value ? CredentialCache.DefaultNetworkCredentials : null;
}
}
public ICredentialsByHost Credentials {
get {
return transport.Credentials;
}
set {
if (InCall) {
throw new InvalidOperationException(SR.GetString(SR.SmtpInvalidOperationDuringSend));
}
transport.Credentials = value;
}
}
这让我前行了,因为我在设置凭据后将默认值设置为false,而我无法让gmail进行身份验证。如果您深入了解有关SmtpClient和SmtpTransport的代码,该代码似乎仅在第一次发送请求期间一次建立连接。因此,似乎无法在同一客户端中再次“设置”凭据。如果我正确地读取了代码,那么即使在第一次发送请求后再次调用UseDefaultCredentials也无法正常工作。据我所知,这段代码是导致它发生的原因:
private void GetConnection()
{
if (!_transport.IsConnected)
{
_transport.GetConnection(_host, _port);
}
}
如果您想深入了解MS开源代码,请点击这里。
https://source.dot.net/#System.Net.Mail/System/Net/Mail/SmtpClient.cs https://source.dot.net/#System.Net.Mail/System/Net/Mail/SmtpTransport.cs