SecurityException:请求“System.Net.Mail.SmtpPermission”类型的权限

这是“在本地工作,在服务器上不起作用”的post之一。

我有一个发送电子邮件的简单联系表单。 在服务器上,我得到以下exception:

Security Exception Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file. Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Net.Mail.SmtpPermission, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed. Source Error: [No relevant source lines] 

主机无法向我提供用于从Web服务器发送SMTP邮件的代码或SMTP客户端。 因此,我需要找到一种替代方式来发送它们,这将使我的Web服务器满意的是一种限制性的安全策略。

这是源代码:

 private void SendMessage (string returnAddress, string textSubject, string messageText) { config config = new config(); System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(); message.To.Add(config.toEmailAddress); message.Subject = "Website Contact Form Message: " + textSubject; message.From = new System.Net.Mail.MailAddress(returnAddress); message.Body = messageText; message.IsBodyHtml = false; System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.naturalcarpetcompany.com"); smtp.Credentials = new System.Net.NetworkCredential(config.fromEmailAddress, config.fromEmailPassword); smtp.Port = 587; try { smtp.Send(message); } catch (Exception ex) { Exception ex2 = ex; string errorMessage = string.Empty; while (ex2 != null) { errorMessage += ex2.ToString(); ex2 = ex2.InnerException; } HttpContext.Current.Response.Write(errorMessage); } } 

较低的安全级别不允许您指定smtp端口。 默认是端口25.虽然我的ISP指定端口587,但我可以使用端口25,它工作正常。

我遇到了类似的问题,我只是在Web.config文件中添加了以下代码,它对我有用

   .....    

我在共享主机服务器上遇到了这个问题。 尝试创建SMTP客户端对象然后为其分配端口号时出现错误。 提高信任度对我来说非常好。 我只是详细说明了细节,以确保它也能帮助其他人。 非常感谢解决方案! 由于我无法发表评论,因此在此感谢原作者。