我将以下SMTP详细信息存储在web.config中

<system.net>
    <mailSettings>
      <smtp from="[email protected]">
        <network host="mail.domain.com" port="25" userName="username" password="password" defaultCredentials="true"/>
      </smtp>
    </mailSettings>
  </system.net>

如何从C#类中检索这些值。

最佳答案

Configuration configurationFile = WebConfigurationManager
    .OpenWebConfiguration("~/web.config");
MailSettingsSectionGroup mailSettings = configurationFile
    .GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;
if (mailSettings != null)
{
    int port = mailSettings.Smtp.Network.Port;
    string host = mailSettings.Smtp.Network.Host;
    string password = mailSettings.Smtp.Network.Password;
    string username = mailSettings.Smtp.Network.UserName;
}

10-07 16:48