Can't send mail using SmtpClient

2019-06-26 07:34发布

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.

标签: c# .net smtp
2条回答
劫难
2楼-- · 2019-06-26 08:05

The server responds with 5.7.1 Client was not authenticated but only if you do not set UseDefaultCredentials to true. This indicates that the NetworkCredential that you are using is in fact wrong.

Either the user name or password is wrong or perhaps you need to specify a domain? You can use another constructor to specify the domain:

new NetworkCredential("MyUserName", "MyPassword", "MyDomain");

Or perhaps the user that you specify does not have the necessary rights to send mail on the SMTP server but then I would expect another server response.

查看更多
Anthone
3楼-- · 2019-06-26 08:21

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");
查看更多
登录 后发表回答