2017-09-08 88 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