【问题标题】:The SMTP server requires a secure connection from MVC App on serverSMTP 服务器需要来自服务器上的 MVC 应用程序的安全连接
【发布时间】:2020-05-12 11:25:28
【问题描述】:

我使用下面的代码从我的 MVC 5 应用程序发送电子邮件,并且在从 Visual Studio 本地运行时发送电子邮件,但当我尝试从服务器发送时不发送邮件(共享 Windows 托管)

 public ActionResult TestMail()
    {
        try
        {
            string email_from = "email_from@gmail.com";
            string email_to = "email_to@gmail.com";
            using (MailMessage mail = new MailMessage())
            {
                mail.From = new MailAddress(email_from);
                mail.To.Add(email_to);

                mail.Subject = "Reference form Id:" ;
                mail.Body = "<h1>Test Body </h1>";
                mail.IsBodyHtml = true;
                Attachment data = new Attachment(
                               Server.MapPath("~/JsonData/privacystatement.pdf"),
                               System.Net.Mime.MediaTypeNames.Application.Octet);
                mail.Attachments.Add(data);

                using (SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587))
                {
                    smtp.UseDefaultCredentials = false;
                    smtp.Credentials = new System.Net.NetworkCredential("email_from@gmail.com", "passcode");
                    smtp.EnableSsl = true;
                    smtp.Send(mail);
                }
                ViewBag.Message = "Email sent.";
            }
        }
        catch (Exception ex)
        {
            ViewBag.Message = "Email not sent Error." + ex.Message;
        }

        return View("Finish");
    }

我从服务器收到此错误

    Email not sent Error.The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Authentication Required. 

我当前的帐户设置:

    Less secure app access ON 
    Two factor Authentication (SMS on phone etc) DISABLED

在本地运行时,此代码正在工作并且电子邮件已成功发送,但在将代码上传到服务器时,只有我收到此错误

我是否应该添加更多属性以确保它也能在服务器(共享 Windows 托管)上运行

【问题讨论】:

  • 您的问题解决了吗?
  • @PK 否,现在我选择了使用 Sendgrid 发送的解决方案 \

标签: c# asp.net-mvc smtp gmail


【解决方案1】:

有两个方面。

一个是代码本身。我这样创建了一个 SmtpClient:

new SmtpClient
{
    Port = 587,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    UseDefaultCredentials = false,
    EnableSsl = true,
    Host = "smtp.gmail.com",

    Credentials = new NetworkCredential(mailFrom, password)
};

其次是设置 Gmail 帐户以允许此类操作。您必须在该 Gmail 帐户中进行设置。 请参考此资源https://support.google.com/accounts/answer/6010255?hl=en

它包含一个简单的分步说明。

在此之后,我的代码通过 Gmail 从托管在标准 Windows 托管服务提供商上的应用程序发送电子邮件,没有问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-18
    • 2018-04-23
    • 2018-10-09
    • 2015-08-27
    • 2023-03-27
    • 2021-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多