如何使用smtp客户端发送电子邮件时修复smtp身份验证运行时错误?

时间:2015-04-04 07:17:35

标签: c# asp.net smtp smtpclient smtp-auth

我正在使用smtp客户端在我的应用程序中发送简单的电子邮件,之前我正在使用此代码,它运行正常。现在,当我尝试从本地主机再次运行我的项目并尝试发送电子邮件时。我收到了一个运行时错误

SMTP服务器需要安全连接或客户端未经过身份验证。服务器响应为:5.5.1需要身份验证。

我不知道发生了什么,因为之前工作正常。现在我无法发送电子邮件,所有我得到的都是这个错误。我几乎无法解决出错的问题。我该如何解决这个问题?以下是我的代码:谢谢......

SmtpClient client = new SmtpClient();

                client.Host = "smtp.gmail.com"; 

                client.Port = 587;

                client.EnableSsl = true;

                client.Credentials = new System.Net.NetworkCredential(@"myemailaddress@gmail.com",@"myemailpassword");            

                // create message
                MailMessage message = new MailMessage();

                message.From = new MailAddress(TextBox4.Text);
                message.To.Add(new MailAddress(TextBox1.Text));
                message.Subject = TextBox2.Text;
                message.Body = TextBox3.Text; //body of the message to be sent
                message.BodyEncoding = System.Text.Encoding.UTF8;
                message.IsBodyHtml = true;
                // message.Subject = "subject";
                message.SubjectEncoding = System.Text.Encoding.UTF8;

               try
               {
                    client.Send(message);
                    Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Alert", "alert('Mail has been successfully sent!')", true);

                }
                catch (SmtpException ex)
                {

                    Response.Write(ex.Message);

                }
                finally
                {
                    // Clean up.
                    message.Dispose();
                }

1 个答案:

答案 0 :(得分:1)

只需转到此处:Less secure apps,使用您的电子邮件和密码登录,用于在c#代码中发送邮件,然后选择Turn On

另请点击此链接,然后点击继续 Allow access to your Google account

我也稍微编辑一下:

public string sendit(string ReciverMail)
{
    MailMessage msg = new MailMessage();

    msg.From = new MailAddress("YourMail@gmail.com");
    msg.To.Add(ReciverMail);
    msg.Subject = "Hello world! " + DateTime.Now.ToString();
    msg.Body = "hi to you ... :)";
    SmtpClient client = new SmtpClient();
    client.UseDefaultCredentials = true;
    client.Host = "smtp.gmail.com";
    client.Port = 587;
    client.EnableSsl = true;
    client.DeliveryMethod = SmtpDeliveryMethod.Network;
    client.Credentials = new NetworkCredential("YourMail@gmail.com", "YourPassword");
    client.Timeout = 20000;
    try
    {
       client.Send(msg);
        return "Mail has been successfully sent!";
    }
    catch (Exception ex)
    {
        return "Fail Has error" + ex.Message;
    }
    finally
    {
       msg.Dispose();
    }
}