c# - 安全异常 : Request for the permission of type 'System.Net.Mail.SmtpPermission'

标签 c# asp.net smtp

这是“在本地工作,在服务器上不工作”的帖子之一。

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

 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]

主机无法给我代码或 SMTP 客户端,这些客户端将用于从 Web 服务器发送 SMTP 消息。因此,我需要找到一种替代方式来发送它们,这将使我的网络服务器对严格的安全策略感到满意。

这是源代码:

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 端口并且它工作正常。

关于c# - 安全异常 : Request for the permission of type 'System.Net.Mail.SmtpPermission' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11992851/

相关文章:

c# - 为 ASP.NET 核心创建基础 Controller 来进行日志记录,但我的构造函数签名有问题吗?

c# - 如何在 FakeHttpContext 中设置 Request.Header 以进行单元测试

c# - 将图像转换为字节流

asp.net - 如何并排放置复选框?

c# - 如何检查收件人电子邮件地址域是否已实现 TLS?

networking - 解析 gmail.com 邮件服务器

c# - 货币正则表达式

c# - 我可以更改后编译器的顺序吗?

c# - 小Q谈js和sharepoint

ssl - 肯蒂科 SMTP : use TLS instead of SSL