Our company is switching the SMTP mail server to Office 365. The key issue is the new SMTP server "smtp.office365.com" only supports TLS encryption. Thus I cannot use CredentialCache.DefaultNetworkCredentials
to encode my Windows log-in password automatically.
var smtpClient = new SmtpClient("smtp.oldserver.com")
{
Credentials = CredentialCache.DefaultNetworkCredentials
};
const string from = "myemail@xyz.com";
const string recipients = "myemail@xyz.com";
smtpClient.Send(from, recipients, "Test Subject", "Test Body");
Previously this works without any issue. But if I now change the above snippet to:
var smtpClient = new SmtpClient("smtp.office365.com");
smtpClient.EnableSsl = true;
smtpClient.Port = 587;
smtpClient.Credentials = CredentialCache.DefaultNetworkCredentials;
I'm now getting:
Unhandled Exception: System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM
But if I specify my Windows login username and password in the code it works fine:
smtpClient.Credentials = new NetworkCredential("myemail@xyz.com", "mypassword");
So:
- Is it possible to encode the password using
DefaultNetworkCredentials
but make it workable under TLS encryption? - If 1. is not possible, is there a better way to encode my Windows password somewhere else without directly revealing it as plaintext in the code?