[.NET]透過 gmail 寄送 Mail,發生 SMTP 伺服器需要安全連接,或用戶端未經驗證 的錯誤

簡簡單單透過 gmail 去寄送 Mail,發生 5.5.1 Authentication Required. 的錯誤!
到底是怎麼回事呢?

有朋友在問「透過C#用gmail寄信,以下成是哪裡有問題」,

參考google的「Set up POP in mail clients」,smtp 要使用 TSL,而 Port 可使用 587 。

於是使用以下簡單的Code來測試,

var client = new SmtpClient("smtp.gmail.com", 587)
{
	EnableSsl = true,
	DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network,
	UseDefaultCredentials = false,
	Credentials = new NetworkCredential("你的google帳號", "密碼") 
};

client.Send("測試信<rm@gmail.com>", "rainmaker_ho@gss.com.tw", "test", "testbody");
Console.WriteLine("Sent");
Console.ReadLine();

結果卻出現「SMTP 伺服器需要安全連接,或用戶端未經驗證。」的錯誤,如下,

System.Net.Mail.SmtpException was unhandled
  _HResult=-2146233088
  _message=SMTP 伺服器需要安全連接,或用戶端未經驗證。 伺服器回應為: 5.5.1 Authentication Required. Learn more at
  HResult=-2146233088
  IsTransient=false
  Message=SMTP 伺服器需要安全連接,或用戶端未經驗證。 伺服器回應為: 5.5.1 Authentication Required. Learn more at
  Source=System
  StackTrace:
       於 System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response)
       於 System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, MailAddress from, Boolean allowUnicode)
       於 System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception)
       於 System.Net.Mail.SmtpClient.Send(MailMessage message)
       於 System.Net.Mail.SmtpClient.Send(String from, String recipients, String subject, String body)

image

 

 

後來在網路上發現有人說要調整「安全性較低的應用程式存取權限」為「啟用」(預設是「停用」)。

image

設定「啟用」後,再執行一次程式就可以正常送出了哦! 

測試時,使用 Port 25 ,也可以通哦!

另外,也可以使用「Enable Two-Factor Authentication for the account」。

詳細請參考「GMail starts to block less secure apps: how to enable access again」。

希望對大家有幫助。

Hi, 

亂馬客Blog已移到了 「亂馬客​ : Re:從零開始的軟體開發生活

請大家繼續支持 ^_^