2010-04-13 46 views
3

你好我們有一個業務邏輯層,它有一個電子郵件服務類。在這個類中,我們有一個方法將創建一個電子郵件(這部分工作和編譯好)。但是,當我們嘗試訪問應用程序配置文件以測試該方法時,我們得到一個錯誤說 - 無法檢索應用程序配置郵件設置,並表示所有值都爲空時,他們不是。下面是我們的代碼的應用程序配置部分:試圖訪問App.config文件的郵件設置,但無法工作


<mailSettings> 
    <smtp deliveryMethod="Network" from="[email protected]"> 
    <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); 

我們在這裏做錯了什麼?

+0

應用程序配置不顯示。請用4個空格縮進(以及代碼) – Marek 2010-04-13 10:24:27

+0

@Marek:我用正確的縮進/代碼大綱編輯了這個問題。 – 2010-04-13 10:29:22

+2

system.net標記中的郵件設置部分? 爲什麼你需要直接訪問它們?默認構造函數SmtpClient()應該自動選取它們 – adrianm 2010-04-13 10:36:29

回答

5

您的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); 
} 
+0

它似乎仍未使用此代碼找到它。 – 2010-04-13 10:48:29

+0

它在測試應用程序中爲我工作。 smtpSection是否爲空? – 2010-04-13 11:05:12

1
SmtpSection smtpSection = ConfigurationManager.GetSection("system.net/mailSettings/smtp") as SmtpSection; 
if (smtpSection != null) { 
    SmtpClient client = new SmtpClient(smtpSection.Network.Host, smtpSection.Network.Port); 
} 
1

<mailSettings> 

    <smtp> 

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

    </smtp> 

</mailSettings> 

然後 公共靜態布爾SendEmail(字符串發件人,收件人字符串,字符串主題,繩體)

{ 

     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; 

     } 
相關問題