Reputation: 11
When I m trying to send mail through my C# Code above error is showing. I have searched for possibly all solution but I do not get the solution. I am using the below Code:
MailMessage mail = new MailMessage("SenderMail",Email);
mail.IsBodyHtml = true;
mail.Subject = "An email from Office365";
mail.Body = "<html><body><h1>Hello world</h1></body></html>";
SmtpClient client = new SmtpClient("smtp.office365.com");
client.Port = 587;
client.EnableSsl = true;
client.UseDefaultCredentials = false; // Important: This line of code must be executed before setting the NetworkCredentials object, otherwise the setting will be reset (a bug in .NET)
NetworkCredential cred = new System.Net.NetworkCredential("Sendermail", "Password");
client.Credentials = cred;
client.Send(mail);
Upvotes: 0
Views: 10639
Reputation: 243
Context: I faced the same error, and I thought my credentials were good, because it was working okay every day. I tried to debug, looked for a solution in internet (even in this stackoverflow question-thread), and I spent lots of minutes with no good result.
Solution: Finally, I tried my "supposed correct" credentials on outlook web client and logged in. Result: I got this message: "you password expired! " then I updated the password in web client, I updated credentials and my code and that's it, it worked okay as usual.
Additional info: You may consider to keep password (encrypted) somewhere else (not in source code), so that it can be easily updated.
Upvotes: 0
Reputation: 908
1- I believe the following is missing from your code.
client.DeliveryMethod = SmtpDeliveryMethod.Network;
2- Dont set UseDefaultCredentials value to false. Keep it to its default value. Just remove the line.
This worked for me.
Upvotes: 2