SMTP client passing the users logged in domain credentials RRS feed

  • Question

  • The following code works  great providing the right information; however, how can I pass the logged in credentials instead of hard coding the credentials.

    For example instead of this

     client.Credentials = new System.Net.NetworkCredential(userName, password); 

    I would like to do something like this

     client.Credentials = new System.Net.NetworkCredential(logged in credentials); 


     // My code:

                String userName = "user";
                String password = "password";
                MailMessage msg = new MailMessage();
                msg.To.Add(new MailAddress(""));
                msg.From = new MailAddress(userName);
                msg.Subject = "Test Office 365 Account";
                msg.Body = "Testing email using Office 365 account.";
                msg.IsBodyHtml = true;
                SmtpClient client = new SmtpClient();
                client.Host = "myhost";
                client.Credentials = new System.Net.NetworkCredential(userName, password);  
                client.Port = 587;
                client.EnableSsl = true;

    Thursday, August 23, 2018 3:15 PM


All replies

  • Don't set Credentials. Set UseDefaultCredentials to true. The Windows user will then be used instead. Note that your mail provider must support Windows auth.

    Michael Taylor

    Thursday, August 23, 2018 8:55 PM
  • That worked.

    Thank you

    • Marked as answer by morganlomas Friday, August 24, 2018 6:04 PM
    Friday, August 24, 2018 6:04 PM