在appsettings web.config中设置电子邮件设置

时间:2012-04-05 04:01:26

标签: asp.net-mvc-3

在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="MyEmail@live.co.uk" />
    <add key="smtpPass" value="mypasswordgoeshere" />
    <add key="adminEmail" value="no-reply@no-reply.com" />
  </appSettings>

我正在使用以下课程

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Mail;
using System.Net;
using System.Configuration;

namespace MVCcars.Utils
{
  public static class MailClient
  {
    private static readonly SmtpClient Client;
    static MailClient()
    {
      Client = new SmtpClient
      {
        Host =
          ConfigurationManager.AppSettings["SmtpServer"],
        Port =
          Convert.ToInt32(
            ConfigurationManager.AppSettings["SmtpPort"]),
        DeliveryMethod = SmtpDeliveryMethod.Network

      };
      Client.UseDefaultCredentials = false;
      Client.Credentials = new NetworkCredential(
      ConfigurationManager.AppSettings["SmtpUser"],
      ConfigurationManager.AppSettings["SmtpPass"]);
    }


    private static bool SendMessage(string from, string to,
      string subject, string body)
    {
      MailMessage mm = null;
      bool isSent = false;
      try
      {
        // Create our message
        mm = new MailMessage(from, to, subject, body);
        mm.DeliveryNotificationOptions =
        DeliveryNotificationOptions.OnFailure;
        // Send it
        Client.Send(mm);
        isSent = true;
      }
      // Catch any errors, these should be logged and
      // dealt with later
      catch (Exception ex)
      {
        // If you wish to log email errors,
        // add it here...
        var exMsg = ex.Message;
      }
      finally
      {
        mm.Dispose();
      }
      return isSent;
    }


    public static bool SendWelcome(string email)
    {
      string body = "Put welcome email content here...";
      return SendMessage(
        ConfigurationManager.AppSettings["adminEmail"],
          email, "Welcome message", body);
    }
  }
}

这是帐户控制器:

[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);   
}

web.config中的应用设置是否适用于enableSsl? 欢迎任何建议

2 个答案:

答案 0 :(得分:20)

使用.NET中的SmtpClient更简单的方法是使用system.net配置设置。这将允许您为任何创建的SmtpClient设置默认值,而无需编写代码来设置所有属性。这样,您可以轻松修改整个设置,而无需更改任何代码。

  <system.net>
    <mailSettings>
      <smtp from="no-reply@no-reply.com">
        <network host="smtp.live.com" password="mypasswordgoeshere" port="587" userName="MyEmail@live.co.uk"  enableSsl="true"/>
      </smtp>
    </mailSettings>
  </system.net>

然后在代码中

 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"])

     };
  .....
 } 

答案 1 :(得分:2)

除了上面的Nick Bork的回答,您可能需要对您的asp页面进行一些更改并使用

  

MailSettingsGroup

。希望这个链接很有帮助 How to use the Not-so-new MailSettingsSectionGroup