1

使用这篇读得很好的帖子中的代码时

var smtp = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    UseDefaultCredentials = false,
    Credentials = new NetworkCredential("my email", "my password")
};

我经常收到 System.Security.SecurityException: Request for the permission of type 'System.Net.Mail.SmtpPermission.

这段代码是否必须在某些特殊的托管环境中使用,或者我是否遗漏了一些明显的东西?

谢谢!

4

1 回答 1

0

发送电子邮件取决于 SMTP 服务器的配置方式。

According to gmail confiruged You need to remove this line of code

UseDefaultCredentials = false;

只需评论此行,您的消息就会被发送。

 var smtp = new SmtpClient
        {
            Host = "smtp.gmail.com",
            Port = 587,
            EnableSsl = true,
            DeliveryMethod = SmtpDeliveryMethod.Network,
            // do not use this command
           // UseDefaultCredentials = false,
            Credentials = new NetworkCredential("username", fromPassword)
        };

Microsoft 建议尽可能不要使用 defaultcredentials。请参阅链接以进行说明。

于 2012-06-05T17:40:56.987 回答