ASP.NET C# - 从Gmail / Yahoo Live SMTP Server发送电子邮件不起作用

时间:2017-01-04 13:15:17

标签: c# .net email smtp gmail

我正在努力尝试从.NET应用程序发送电子邮件。

我已尝试过从创建新帐户gmail和yahoo(更改主机为yahoo),以及更改端口使用而不使用mail.To,允许不太安全的应用程序,我也尝试启用2步验证并为gmail提供应用程序密码,所有这些密码都失败并出现相同的错误:{" SMTP服务器需要安全连接或客户端未经过身份验证。服务器响应为:5.7.1需要验证"}

这是我的代码:

 SmtpClient smtpClient = new SmtpClient();
        System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("myemail@gmail.com", "pw");
        smtpClient.Credentials = credentials;
        smtpClient.UseDefaultCredentials = false;
        smtpClient.Port = 587;
        smtpClient.EnableSsl = true;
        smtpClient.Host = "smtp.gmail.com";
        smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;

        MailMessage mail = new MailMessage();
        mail.From = new MailAddress("myemail@gmail.com");
        mail.To.Add("myemail@gmail.com");
        mail.IsBodyHtml = true;
        mail.Subject = txtSubject.Text;
        mail.Body = txtBody.Text;
        try
        {
            smtpClient.Send(mail);
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            if (mail != null)
            {
                mail.Dispose();
            }
        }

解决方案:由于人们将来可能遇到问题,解决方案是删除代码行:smtpClient.UseDefaultCredentials = false;

1 个答案:

答案 0 :(得分:0)

smtpClient.UseDefaultCredentials = false;            
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("myemail@gmail.com", "pw");
smtpClient.Credentials = credentials;

按此顺序使用这些行。