【问题标题】:Sending email through Gmail throws an error通过 Gmail 发送电子邮件会引发错误
【发布时间】:2018-03-21 20:16:03
【问题描述】:

我正在开发一个 Web 应用程序,我在此电子邮件发送代码之间卡住了。我正在处理联系页面,任何人都可以向您发送电子邮件,正如你们所知。此代码工作正常,但我无法通过此错误

正如我所说,我正在使用 Asp.Net Mvc,所以这是我使用 gmail 帐户的 POST 控制器,这样它就不会在任何邮件服务之间发生冲突。

  public ActionResult sendemail()
    {
        return View();
    }

    [HttpPost]
    public ActionResult sendemail(string to, string from, string subject, string body, string pwd)
    {
        SmtpClient client = new SmtpClient();
        client.Host = "smtp.gmail.com";
        client.Port = 587;
        client.EnableSsl = true;

        client.UseDefaultCredentials = true;
        client.Credentials = new NetworkCredential("faseehyasin12@gmail.com", pwd);
        client.DeliveryMethod = SmtpDeliveryMethod.Network;

        MailMessage mail = new MailMessage();
        mail.To.Add(to);
        mail.From = new MailAddress(from);
        mail.Subject = subject;
        mail.Body = body;
        try
        {
            client.Send(mail);
            Response.Write("ok");
            return View();
        }
        catch(Exception e)
        {
            throw e;
        }

    }

这是我的观点,我想问一下我是否真的需要密码才能通过此代码向某人发送电子邮件?

我的 GET 控制器是空的,只有编写的代码是 return view() 所以我不会费心去拿 ss。我也允许“不太安全的应用程序”,但它仍然给我这个错误。需要帮助

【问题讨论】:

  • ASP.NET MVC 是一个Web 框架。它与发送电子邮件无关。发布您的代码,而不是代码的图像。图像无法编译和测试,没有人会为了测试而输入所有内容。不过,就 this 错误而言,该消息已经说明了问题所在。 服务器需要 SSL,或者凭据错误
  • 已经有解释如何使用 GMail 发送电子邮件的副本。使用单元测试或小型控制台应用程序来测试您的设置,而不是使用成熟的网站。尝试事情要快很多,按 F5 或 Run Tests 并更改设置,直到正确为止。
  • 我过去曾尝试过相同的代码,并且在我收到电子邮件时它也有效。如果是 SSL 问题,那么为什么当时没有出现此错误。
  • 因为你这次有问题。密码错误,没有认证,设置错误。任何。顺便说一句,您还没有发布您的代码。无法编译图像。如果我想测试你的代码,我不能
  • 尝试将“UseDefaultCredentials”设置为 true。

标签: c# .net email smtp


【解决方案1】:

首先转到https://myaccount.google.com/lesssecureapps 并将状态更改为打开。 然后转到https://accounts.google.com/b/0/displayunlockcaptcha 并点击继续按钮。

请尝试以下代码。

string host = "smtp.gmail.com";
int port = 587;
bool ssl = true;
string fromAddress = "faseehyasin12@gmail.com";
string fromPassword = "your password here";
using (var mail = new MailMessage())
{
    string subject = "Test";
    string body = "Mail test";
    mail.From = new MailAddress(fromAddress);
    mail.Subject = subject;
    mail.IsBodyHtml = true;
    mail.Body = body;
    mail.To.Add("mail@domain.com");
    using (var smtpServer = new SmtpClient(host,port))
    {
        smtpServer.UseDefaultCredentials = false;
        smtpServer.Credentials = new System.Net.NetworkCredential(fromAddress, fromPassword);
        smtpServer.EnableSsl = ssl;
        smtpServer.Send(mail);
    }

}

【讨论】:

  • 我已经按照上面所说的做了这个,但它仍然给我同样的错误
  • 我添加了示例代码。该代码在我的项目中运行。
  • 您的帐户可能有问题。这段代码对我有用。我正在使用此代码通过 Google 帐户发送电子邮件。
猜你喜欢
  • 2012-01-07
  • 2023-03-19
  • 2016-06-03
  • 2016-09-26
  • 2011-06-01
  • 2018-03-21
相关资源
最近更新 更多