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("makovetskiyd@yahoo.开发者_如何学运维co.uk");
mail.From = new MailAddress("makovetskiyd@yahoo.co.uk");
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
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:
<system.net>
<mailSettings>
<smtp from="info@example.com">
<network host="localhost" port="25" defaultCredentials="false">
</smtp>
</mailSettings>
</system.net>
This will allow you to new up an SmtpClient
and just send the message without further configuration.
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.
<appSettings>
<add key="SMTP" value="..." />
</appSettings>
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.
string defaultHost = "www.foo.com";
smtp.Host = ConfigurationManager.AppSettings["SMTP"] ?? defaultHost;
精彩评论