Reputation: 432
I was doing tests to send an email from C #, for it use the following code:
MailMessage message = new MailMessage();
message.To.Add("[email protected]");
message.From = new MailAddress("[email protected]");
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("[email protected]", "CorrectPassword");
client.Credentials = credentials;
try
{
client.Send(message); // OK
}
catch (Exception ex)
{
MessageBox.Show("Exception caught in CreateTestMessage2(): {0}", ex.ToString());
}
Then, try to start controlling the exceptions for connection interruption and mainly invalid key, but note that even using incorrect keys, the mail was still sent.
NetworkCredential credentials = new NetworkCredential("[email protected]", "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());
}
How do I disable the automatic saving of credentials? Or, how do I erase the stored credentials?
Upvotes: 0
Views: 48
Reputation: 1811
The way that the SmtpClient works regarding those 2 properties (UseDefaultCredentials and Credentials) is dictated by the code MS has in place. Here is how they are implemented:
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;
}
}
This tripped me up a while back as I was setting the default to false after setting creds and I couldn't get gmail to authenticate. If you look deeper at the code around SmtpClient and SmtpTransport, the code appears to only make the connection a single time during the first send requests. Therefore, it doesn't appear that you can set the credentials "again" during the same client. If I am reading the code correctly, even calling UseDefaultCredentials again won't work AFTER the first send request. This code is what causes it to happen as far as I can tell:
private void GetConnection()
{
if (!_transport.IsConnected)
{
_transport.GetConnection(_host, _port);
}
}
Here are the links to the MS open source code if you want to dig around in there to see what it's doing.
https://source.dot.net/#System.Net.Mail/System/Net/Mail/SmtpClient.cs https://source.dot.net/#System.Net.Mail/System/Net/Mail/SmtpTransport.cs
Upvotes: 1