[英]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.