修改邮件发送代码时莫名其妙报错,原因是net的邮件发送封装未自动指向Tls12,显示邮件发送异常,如下图所示
我的解决方法是在邮件发送方法的最前方加入以下代码
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
下面附整段邮件发送代码
public bool SendEmail(string email)//收件人 { System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;//配置ssl string Email = WebConfigurationManager.AppSettings["Email"].ToString();//发送邮件的邮箱 string Emailpwd = WebConfigurationManager.AppSettings["Emailpwd"].ToString();//邮箱密码 string Host = WebConfigurationManager.AppSettings["HostEmail"].ToString();//邮箱服务器 string Port = WebConfigurationManager.AppSettings["Port"].ToString();//服务器端口号 // 邮件服务设置 SmtpClient smtpClient = new SmtpClient(); smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;//指定电子邮件发送方式 smtpClient.Host = Host; //指定SMTP服务器 smtpClient.Port = Convert.ToInt32(Port); smtpClient.EnableSsl = true; smtpClient.Credentials = new System.Net.NetworkCredential(Email, Emailpwd);//用户名和密码 // 发送邮件设置 MailMessage mailMessage = new MailMessage(Email, email); // 发送人和收件人 mailMessage.Subject = "test1111";//主题 mailMessage.Body = "test1111";//内容 mailMessage.BodyEncoding = Encoding.UTF8;//正文编码 mailMessage.IsBodyHtml = true;//设置为HTML格式 mailMessage.Priority = MailPriority.Low;//优先级 try { smtpClient.Send(mailMessage); // 发送邮件 return true; } catch (Exception ex) { return false; }