3

您好,我们有一个具有电子邮件服务类的业务逻辑层。在这个类中,我们有一个创建电子邮件的方法(这部分工作和编译良好)。但是,当我们尝试访问应用程序配置文件以测试该方法时,我们会收到一条错误消息 - 无法检索应用程序配置邮件设置,并说所有值都不是空值。这是我们代码的应用程序配置部分:


<mailSettings>
  <smtp deliveryMethod="Network" from="info@example.com">
    <network host="localhost" port="25" defaultCredentials="true"/>
  </smtp>
</mailSettings>

这是我们用来连接到 app.config 的代码:


private System.Net.Configuration.MailSettingsSectionGroup mailSettings;

SmtpClient client = new SmtpClient(mailSettings.Smtp.Network.Host, mailSettings.Smtp.Network.Port);

我们在这里做错了什么?

4

3 回答 3

6

您的mailSettings变量未初始化为任何内容 - 它不会神奇地包含您的配置。

您需要使用ConfigurationManager该类来访问它(System.Configuration如果尚未这样做,请记住添加对的引用。)您还需要添加using System.Net.Configuration以下代码。

SmtpSection smtpSection = ConfigurationManager.GetSection("system.net/mailSettings/smtp") as SmtpSection;

if (smtpSection != null)
{
    SmtpClient client = new SmtpClient(smtpSection.Network.Host, smtpSection.Network.Port);
}
于 2010-04-13T10:37:11.223 回答
1
SmtpSection smtpSection = ConfigurationManager.GetSection("system.net/mailSettings/smtp") as SmtpSection;
if (smtpSection != null) {
    SmtpClient client = new SmtpClient(smtpSection.Network.Host, smtpSection.Network.Port);
} 
于 2012-05-07T13:11:32.267 回答
1

<mailSettings>

  <smtp>

    <network host="smtp.mailserver.com" password="password" userName="username"/>

  </smtp>

</mailSettings>

然后 public static bool SendEmail(string sender, string recipient, string subject, string body)

    {

        try

        {

            Configuration mConfigurationFile = ConfigurationManager.OpenExeConfiguration("D:\\Projects\\EmailSolution\\Email\\App.config");

            MailSettingsSectionGroup mMailSettings = mConfigurationFile.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;



            string mHost = string.Empty;



            if (mMailSettings != null)

            {

                //int mPort = mMailSettings.Smtp.Network.Port;

                mHost = mMailSettings.Smtp.Network.Host;

                //string mPassword = mMailSettings.Smtp.Network.Password;

                //string mUsername = mMailSettings.Smtp.Network.UserName;

            }

            //Allows applications to send e-mail by using the Simple Mail Transfer Protocol (SMTP).

            SmtpClient mailClient = new SmtpClient(mHost);



            //Sends an e-mail message to an SMTP server for delivery.

            mailClient.Send(EmailMessage.CreateEmailMessage(sender, recipient, subject, body));



            return true;

        }
于 2012-05-07T13:15:04.063 回答