Can not send mail using SmtpClient

advertisements

I want to send mail using SmtpClient class, but it not work. Code:

SmtpClient smtpClient = new SmtpClient();

smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new System.Net.NetworkCredential(obMailSetting.UserName, obMailSetting.Password);

smtpClient.Host = obMailSetting.HostMail;
smtpClient.Port = obMailSetting.Port;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = obMailSetting.Connect_Security;//true
//smtpClient.UseDefaultCredentials = true;//It would work if i uncomment this line
smtpClient.Send(email);

It throws an exception:

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1 Client was not authenticated

I'm sure that username and password is correct. Is there any problem in my code? Thanks.


You can try this :

 MailMessage mail = new MailMessage();
 mail.Subject = "Your Subject";
 mail.From = new MailAddress("senderMailAddress");
 mail.To.Add("ReceiverMailAddress");
 mail.Body = "Hello! your mail content goes here...";
 mail.IsBodyHtml = true;

 SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
 smtp.EnableSsl = true;
 NetworkCredential netCre =
                  new NetworkCredential("SenderMailAddress","SenderPassword" );
 smtp.Credentials = netCre;

 try
  {
     smtp.Send(mail);
  }
  catch (Exception ex)
  {
    // Handle exception here
  }

You can try this out :
In the Exchange Management Console, under the Server Configuration node, select Hub Transport and the name of the server. In the Receive Connectors pane, open either of the Recive Connectors (my default installation created 2) or you can create a new one just for TFS (I also tried this and it worked). For any of these connectors, open Properties and on the Permission Groups tab ensure that Anonymous Users is selected (it's not by default).

Or

You can also try this by initializing SmtpClient as follows:

SmtpClient smtp = new SmtpClient("127.0.0.1");