我正在尝试使用我的 mvc 应用程序中的 gmail 发送电子邮件。我收到以下异常
无法从传输连接读取数据:现有连接被远程主机强行关闭。
这是发送电子邮件的代码
string tn = "EmailVerification.htm";
string fileName = Path.GetFileName(tn);
string templatePath = Path.Combine(Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/EmailTemplates")), fileName);
System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage();
mailMessage.From = new MailAddress(EmailFrom, "Email");
mailMessage.To.Add(new MailAddress(To));
mailMessage.Subject = "subject";
mailMessage.IsBodyHtml = true;
MailDefinition mailDef = new MailDefinition();
mailDef.BodyFileName = templatePath;
mailDef.IsBodyHtml = true;
mailDef.Subject = "mailDefsubject";
mailDef.From = mailMessage.From.ToString();
ListDictionary replacements = new ListDictionary();
replacements.Add("<%FIRSTNAME%>", FirstName);
replacements.Add("<%USERNAME%>", "asd");
replacements.Add("<%VERIFICATIONLINK%>", VerificationLink);
replacements.Add("<%WEBSITE%>", "http://www.mysite.com");
MailMessage msgHtml = mailDef.CreateMailMessage(To, replacements, new System.Web.UI.Control());
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(msgHtml.Body, null, "text/html");
AddLinkedResources(templatePath, ref htmlView);
mailMessage.AlternateViews.Add(htmlView);
SmtpClient smtpClient = new SmtpClient();
Object userState = mailMessage;
smtpClient.Credentials = new System.Net.NetworkCredential("myaddress@gmail.com", "1234567");
smtpClient.EnableSsl = true;
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587;
//Attach event handler for async callback
smtpClient.SendCompleted += new SendCompletedEventHandler(smtpClient_SendCompleted);
try
{
smtpClient.Send(mailMessage);
EmailStatus = true;
}
catch (SmtpException smtpEx)
{
EmailStatus = false;
}
catch (Exception ex)
{
//HttpContext.Current.Response.Write(ex.InnerException);
EmailStatus = false;
}
在 web.config 我有
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="noreply@asd.com">
<network host="smtp.gmail.com" port="587"
userName="asd@gmail.com"
password="asd" />
</smtp>
</mailSettings>
</system.net>