System.Security.SecurityException:对类型'System.Net.Mail.SmtpPermission,System,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089'的权限的请求失败。
当我在可视工作室上的本地服务器上工作时,当我部署此代码并运行在线时他们没有问题然后面临这个问题
部署后服务器上的错误但在本地服务器上没有问题:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Net.Mail;
public partial class Index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void send_Click(object sender, EventArgs e)
{
string smtpAddress = "smtp.gmail.com";
int portNumber = 587;
bool enableSSL = true;
string emailfrom = "[email protected]";
string password = "*********";
string subject = "Contact Form Data";
string emailto = "[email protected]";
string name = n.Value;
string useremail = em.Value;
string phone = tel.Value;
string dept = dep.Value;
string dest = des.Value;
string adu = ad.Value;
string body = "Name: " + name + " ;" + " Email: " + useremail + " ;" + "Telephone: " + phone + " ;" + " Departure Place: " + dept + " ;" + "Destination Place: " + dest + " ;" + " Adults: " + adu + " ;" + " ;" + "Children: " + chil + " ;";
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress(emailfrom);
mail.To.Add(emailto);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
smtp.Credentials = new NetworkCredential(emailfrom, password);
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
}
}
}
}
有两种解决方案。
1)低安全级别不允许您指定smtp端口。默认为端口25.虽然我的ISP指定端口587,但使用端口25。
2)在Web.config中添加代码。
<configuration>
<system.web>
.....
<trust level="Full" originUrl=""/>
</system.web>
</configuration>
希望它的工作!!
快乐编码!!
尝试将SMTP端口更改为端口25.我认为它应该可以工作。
该错误是由服务器的信任配置引起的。通常,信任级别足以使此库工作,但可能是因为服务器上的特殊信任配置,或者您正在Linux服务器上部署。
好吧,没关系,但是你可以通过在Web.config
文件中添加这个节点来手动授予对该库的信任来解决它:
<system.web>
<securityPolicy>
<fullTrustAssemblies>
<add assemblyName="System.Net.Mail.SmtpPermission" version="4.0.0.0" publicKey="b77a5c561934e089"/>
</fullTrustAssemblies>
</securityPolicy>
</system.web>
请检查我使用的信息和错误数据。如果错误随其他程序集名称更改,也会添加它们。
有关更多信息,您可以看到以下两种资源: