ConfigurationManager.AppSettings[“SMTP”];空异常
我用这个代码发送电子邮件。但我不明白该配置管理器的作用,以及为什么它给了我例外。这是完整的代码:
MailMessage mail = new MailMessage();
mail.To.Add("[email protected]");
mail.From = new MailAddress("[email protected]");
mail.Subject = "Test Email";
string Body = "Welcome to CodeDigest.Com!!";
mail.Body = Body;
SmtpClient smtp = new SmtpClient();
smtp.Host = ConfigurationManager.AppSettings["SMTP"];
smtp.Send(mail);
我还将最后几行更改为: smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
smtp.Send(mail);
但它仍然会显示一个错误,说它没有找到 IIS 服务器..或类似的东西
i took this code to send an email. But i dont understand what that configurationManager does, and why it gives me the exception. Here is the full code:
MailMessage mail = new MailMessage();
mail.To.Add("[email protected]");
mail.From = new MailAddress("[email protected]");
mail.Subject = "Test Email";
string Body = "Welcome to CodeDigest.Com!!";
mail.Body = Body;
SmtpClient smtp = new SmtpClient();
smtp.Host = ConfigurationManager.AppSettings["SMTP"];
smtp.Send(mail);
i also changed the last lines to this:
smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
smtp.Send(mail);
but it would still show a mistake, saying it didnt find IIS server..or something like that
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不应使用 AppSettings 和 ConfigurationManager 进行 SMTP 配置。首选方法是通过
配置 SMTP > web.config 中的
部分。例如,小型网站的配置可能如下所示:这将允许您新建一个
SmtpClient
并仅发送消息而无需进一步配置。You should not use AppSettings an the ConfigurationManager for SMTP configuration. The preferred way is to configure SMTP through the
<mailSettings>
section in web.config. For example, the configuration for a small website could look like this:This will allow you to new up an
SmtpClient
and just send the message without further configuration.ConfigurationManager 提供对客户端应用程序配置文件的访问。
我猜错误的原因是您的应用程序的配置文件在应用程序设置部分没有 SMTP 密钥。
ConfigurationManager provides access to configuration files for client applications.
I guess the reason of the error is that the config file of your application does not have a SMTP key in the application settings section.
原因是配置文件中没有这样的SMTP配置。我认为你最好检查你的
web.config
。为了使您的应用程序更强大,您需要添加默认主机,以防配置文件不正确。The reason is that there is no such SMTP configuration in the config file. I think you'd better check your
web.config
. And to make your application stronger, you need to add a default host in case of the config file is incorrect.