2016-07-23 160 views
0

我创建了一个用于发送电子邮件的Windows应用程序。我已经给了证书。 我打开谷歌/设置/ lesssecure应用程序。虽然它不发送。它显示错误SMTP服务器需要安全连接或客户端未通过身份验证。服务器响应是:5.5.1需要身份验证这里是我的代码。Gmail邮件无法通过C#发送

MailMessage message = new MailMessage(); 
      message.From = new MailAddress("[email protected]"); 
      string[] mailaddress = new string[count]; 
      int i; 
      if (textSubject.Text != string.Empty) 
      { 
       message.Subject = textSubject.Text; 
       if (textBody.Text != string.Empty) 
       { 
        message.To="[email protected]" 
        message.IsBodyHtml = true; 
        string tmpBody = "Hello " + "," + "<br/> <br/>" + textBody.Text + "<br/> <br/>" + "Thanks and Regardds"; 
        message.Body = tmpBody; 
        SmtpClient client = new SmtpClient(); 
        client.UseDefaultCredentials = true; 
        client.Host = "smtp.gmail.com"; 
        client.Port = 587; 
        client.UseDefaultCredentials = false; 
        client.Credentials = new NetworkCredential("[email protected]", "mypassword"); 
        message.Priority = MailPriority.High; 
        client.EnableSsl = true;    
        client.Send(message); 
        MessageBox.Show("Mail has sent successfully !!!", "Success !"); 
       } 
       else 
       { 
        MessageBox.Show("Please Enter Body of the Message !"); 
       } 
      } 
      else 
      { 
       MessageBox.Show("Please Enter Subject !"); 
      } 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message, "Failure !"); 
      log.Fatal(ex.Message); 
     } 
    } 
+1

的[这]可能的复制(http://stackoverflow.com/questions/20906077/gmail-error-the- smtp-server-requires-a-secure-connection-or-the-client-was-not) – Berkay

+0

你不能这样做** message.To =“[email protected]”**因为“To”属性是只读的MailAddressCollection电子邮件。尝试** message.To.Add(“[email protected]”); ** – derloopkat

回答

1

如果开启2步验证,那么你就需要使用应用专用密码登录。你可以在这里创建它: https://support.google.com/accounts/answer/185833?hl=en。如果使用正常密码,则会得到例外5.5.1需要验证。你并不需要大量的代码,这个代码足以发送电子邮件没有依附:

const string from = "[email protected]"; 
    const string to = "[email protected]"; 
    const string subject = "This is subject"; 
    const string body = "This is body"; 
    const string appSpecificPassword = "akdfkajsdhklakdfh"; 

    var mailMessage = new MailMessage(from, to, subject, body); 
    using (var smtpClient = new SmtpClient("smtp.gmail.com", 587)) 
    { 
    smtpClient.EnableSsl = true; 
    smtpClient.Credentials = new NetworkCredential(from, appSpecificPassword); 
    smtpClient.Send(mailMessage); 
    } 
+0

谢谢你...我的问题的完美解决方案 –