2012-04-05 69 views
6

在web.config中設置電子郵件詳細信息 - 但沒有發送電子郵件!在appsettings中設置電子郵件設置web.config

<appSettings> 
    <add key="webpages:Version" value="1.0.0.0" /> 
    <add key="ClientValidationEnabled" value="true" /> 
    <add key="UnobtrusiveJavaScriptEnabled" value="true" /> 
    <add key="smtpServer" value="smtp.live.com" /> 
    <add key="EnableSsl" value = "true"/> 
    <add key="smtpPort" value="587" /> 
    <add key="smtpUser" value="[email protected]" /> 
    <add key="smtpPass" value="mypasswordgoeshere" /> 
    <add key="adminEmail" value="[email protected]" /> 
    </appSettings> 

我使用下面的類

這帳戶控制:

[HttpPost] 
public ActionResult Register(RegisterModel model) 
{ 
    if (ModelState.IsValid) 
    { 
     // Attempt to register the user 
     MembershipCreateStatus createStatus; 
     Membership.CreateUser(model.UserName, 
      model.Password, model.Email, null, null, 
      true, null, out createStatus); 
     if (createStatus == 
      MembershipCreateStatus.Success) 
     { 
      // Send welcome email 
      MailClient.SendWelcome(model.Email); 
      FormsAuthentication.SetAuthCookie(
      model.UserName, 
      false /* createPersistentCookie */); 
      return RedirectToAction("create", "Customer"); 
     } 
     else 
     { 
      ModelState.AddModelError("", 
      ErrorCodeToString(createStatus)); 
     } 
    } 
    // If we got this far, something failed, 
    // redisplay form 
    return View(model); 
} 

都在爲在enableSsl web.config中正確應用程序的設置? 歡迎任何建議

+0

你有什麼會讀這些appSettings並將它們設置在你的SMTP對象? – 2012-04-05 04:04:27

+0

隨着你添加的代碼,你會得到一個異常?發生什麼事?我沒有看到你在代碼中設置了啓用SSL的位置,也許我忽略了它。您需要在代碼中使用Client.EnableSsl = bool.parse(ConfigurationManager.AppSettings [「EnableSsl」]) – 2012-04-05 04:16:35

+0

代碼:Client.EnableSsl = bool.parse(ConfigurationManager.AppSettings [「EnableSsl」])你會把它放在哪裏類 – 2012-04-05 04:48:06

回答

20

在.NET中使用SmtpClient更簡單的方法是使用system.net配置設置。這將允許您爲任何創建的SmtpClient設置默認值,而不必編寫代碼來設置所有屬性。通過這種方式,您可以輕鬆修改整個設置而無需更改任何代碼。

然後在代碼

System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(); 
smtp.Send(mailMessage); 

編輯這裏是原單的代碼,我貼在下面:

static MailClient() 
{ 
    Client = new SmtpClient 
    { 
     Host = ConfigurationManager.AppSettings["SmtpServer"], 
     Port = Convert.ToInt32(ConfigurationManager.AppSettings["SmtpPort"]), 
     DeliveryMethod = SmtpDeliveryMethod.Network, 
     EnableSsl = bool.Parse(ConfigurationManager.AppSettings["EnableSsl"]) 

    }; 
    ..... 
} 
2

除了尼克·博克的回答上面,你可能需要做一些修改到您的asp頁面並使用

MailSettingsGroup

。希望這個鏈接是有幫助的 How to use the Not-so-new MailSettingsSectionGroup

+2

您不應該需要使用該配置代碼命名空間,因爲SmtpClient的默認構造函數應該爲您處理....但如果您因爲任何原因需要讀取應用程序中的設置(包括如果需要發送電子郵件) – 2012-04-05 04:44:57