2017-09-08 116 views
0

我正在編寫一個C#電子郵件應用程序,目前正在設計用於Gmail,所以我可以測試身份驗證。但是,我收到一個錯誤,這似乎沒有多大意義,因爲我將SSL設置爲true並使用用戶和密碼。身份驗證錯誤發送SMTP請求

錯誤消息: System.Net.Mail.SmtpException:'SMTP服務器需要安全連接或客戶端未通過身份驗證。服務器響應是:5.5.1需要身份驗證。瞭解更多」

using System; 
using System.Net; 
using System.Net.Mail; 

namespace EmailSendingProgram 
{ 
    public class EmailSendingClass 
    { 
     public static void Main(string[] args) 
     { 
      Console.WriteLine("Type your Gmail Address: "); 
      string from = Console.ReadLine(); 

      Console.WriteLine("Type your Gmail Password: "); 
      string password = Console.ReadLine(); 

      Console.WriteLine("Type the Email Address you wish to send to: "); 
      string to = Console.ReadLine(); 

      Console.WriteLine("Type the Subject of the email: "); 
      string subject = Console.ReadLine(); 

      Console.WriteLine("Type or paste in your email (either text or HTML): "); 
      string body = Console.ReadLine(); 

      EmailSendingClass email = new EmailSendingClass(); 
      email.Send(from, password, to, subject, body); 
     } 

     /// handles sending the email 
     /// hardcoded to work with gmail just change the CreateSmtpClient from 
     /// "smtp.gmail.com", 587 to whatever you want to use 
     public void Send(string from, string password, string to, string subject, string body) 
     { 
      var message = CreateMailMessage(from, to, subject, body); 

      // Host and Port setup for use with Gmail 
      using (SmtpClient client = CreateSmtpClient("smtp.gmail.com", 587, from, password)) 
      { 
       client.Send(message); 
      } 
     } 

     /// Defines the SmtpClient for the mail message 
     /// setups up the network credentials to send the email 
     private SmtpClient CreateSmtpClient(string host, int port, string from, string password) 
     { 
      SmtpClient client = null; 

      client = new SmtpClient() 
      { 
       Host = host, 
       Port = port, 
       EnableSsl = true, 
       Credentials = new NetworkCredential(from, password) 
      }; 

      return client; 
     } 

     /// defines what is contained in the email and where it will be sent 
     /// also makes all messages send as HTML 
     private MailMessage CreateMailMessage(string from, string to, string subject, string body) 
     { 
      MailMessage message = null; 

      message = new MailMessage(from, to) 
      { 
       Subject = subject, 
       Body = body 
      }; 

      message.IsBodyHtml = true; 
      return message; 
     } 
    } 
} 

我明白有些事情是被錯誤地完成與身份驗證,但我似乎無法找出具體是什麼。所以任何幫助,將不勝感激。

+0

您使用的是什麼端口? – Isma

+0

@Isma他使用587,因爲它顯示在代碼 –

+0

我想這個錯誤是由於gmail的安全規則。如果您沒有禁用該Gmail帳戶的某些安全設置(不記得它是什麼,抱歉),Gmail即使使用正確的憑據和設置也不會讓您的應用程序進行身份驗證。 – ihpar

回答

0

的問題是不是程序,而是在Gmail中從「不夠安全的應用」拒絕註冊

我只是點擊安全帳戶按鈕,並允許該帳戶被從安全性較低的應用程序簽名。

enter image description here

0

我遇到了由TLS 1.2支持問題引起的類似問題。如果這是你的情況,最簡單的解決方案可能是針對.NET 4.6.1或更高版本。其他建議可以發現herehere