Cannot send mail with c#

Göran Härdelin 1 Reputation point
2022-09-19T14:14:27.253+00:00

Have this c# code and trying to send mail:

            MailMessage mail = new MailMessage(fromAddress.Address, toAddress.Address);  
            SmtpClient client = new SmtpClient();  

            client.EnableSsl = true;  
            client.Host = "smtp-mail.outlook.com";  
            client.UseDefaultCredentials = false;  
            client.Credentials = new NetworkCredential(fromAddress.Address,   
                fromPassword);  
            client.Port = 587;  
            client.DeliveryMethod = SmtpDeliveryMethod.Network;  
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls |  
                SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;  

            mail.Subject = subject;  
            mail.Body = body;  

            client.Send(mail);  

Get the error message: Client not authenticated to send mail. Error: 535 5.7.139 Authentication unsuccessful, the user credentials were incorrect

What do I have to do?

Exchange Exchange Server Development
Exchange Exchange Server Management
{count} votes

3 answers

Sort by: Most helpful
  1. Göran Härdelin 1 Reputation point
    2022-09-19T16:33:47.107+00:00

    Hi again Dillon

    Do not understand what's happening, it works when I debug the code but not when I run it. I get the error: 5.7.0 Authentication Required.

    Best regards
    Göran

    0 comments No comments

  2. Dillon Silzer 57,826 Reputation points Volunteer Moderator
    2022-09-19T18:59:43.497+00:00
    0 comments No comments

  3. Göran Härdelin 1 Reputation point
    2022-09-19T21:55:55.61+00:00

    Hi again Dillon

    I don't have an office365 email, just an outlook email. Get the same error as before, but in debug mode it's working. Don't understand why it's working in debug but not in production.

    Best regards
    Göran

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.