繁体   English   中英

SMTP 服务器需要来自服务器上的 MVC 应用程序的安全连接

[英]The SMTP server requires a secure connection from MVC App on server

我正在使用以下代码从我的 MVC 5 应用程序发送 email,并且在从 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

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

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

有2个方面。

一是代码本身。 我这样创建一个 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 托管服务提供商上的应用程序发送电子邮件,没有问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM