从asp.net使用Gmail发送电子邮件

时间:2014-08-17 09:51:31

标签: c# asp.net gmail

我正在尝试使用asp.net中的gmail发送邮件

我的代码:

using (MailMessage mm = new MailMessage(txtEmail.Text, txtTo.Text))
        {
            mm.Subject = txtSubject.Text;
            mm.Body = txtBody.Text;
            if (fuAttachment.HasFile)
            {
                string FileName = Path.GetFileName(fuAttachment.PostedFile.FileName);
                mm.Attachments.Add(new Attachment(fuAttachment.PostedFile.InputStream, FileName));
            }
            mm.IsBodyHtml = false;
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com";
            smtp.EnableSsl = true;
            smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
            NetworkCredential NetworkCred = new NetworkCredential(txtEmail.Text, txtPassword.Text);
            smtp.UseDefaultCredentials = true;
            smtp.Credentials = NetworkCred;
            smtp.Port = 587;
            smtp.Send(mm);
            ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Email sent.');", true);
        }

但是我收到了错误:

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at

我的错误在哪里?

2 个答案:

答案 0 :(得分:0)

您可以尝试以下建议:

  1. 尝试设置" UseDefaultCredentials"到"错误" smtp.UseDefaultCredentials = false;
  2. 尝试登录您的Gmail帐户,可能会阻止访问。
  3. 尝试启用对您的Gmail帐户的访问权限,请参阅此链接以获取更多信息http://email.about.com/od/gmailtips/qt/How-To-Unlock-Gmail-For-A-New-Email-Program-Or-Service.htm

答案 1 :(得分:0)

更改“smtp.UseDefaultCredentials = true;” to“smtp.UseDefaultCredentials = false;”。或者使用以下代码测试您的Gmail帐户。

using (MailMessage mm = new MailMessage(new MailAddress("sender@example.com"), new MailAddress("recipient@example.com")))
        {
            mm.Subject = "test";
            mm.Body = "body test";

            mm.IsBodyHtml = false;
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com";
            smtp.EnableSsl = true;
            smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
            NetworkCredential NetworkCred = new NetworkCredential("sender@example.com", "password");
            smtp.UseDefaultCredentials = false;
            smtp.Credentials = NetworkCred;
            smtp.Port = 587;
            smtp.Send(mm);

        }

<强>更新

转到:google.com/settings/security?hl=en_GB,如果字段“Access for less secure apps”已禁用,请点击设置并将其更改为启用...然后使用上面的代码测试您的连接。它适用于我的新gmail用户