[翻译]ASP.NET MVC 3 开发的20个秘诀(五)[20 Recipes for Programming MVC 3]:发送欢迎邮件

议题

许多网站在访问内容或者发表评论的时候 要求用户注册或登录。这样的网站越来越多,用户非常难以记住每个他注册过的站点以及信息。而在用户提交注册信息的时候,网站可以发送邮件,提醒用户他们刚刚签署过注册信息,方便他们稍后访问时查询。

 

解决方案

实现SmtpClient类和MailMessage类在用户注册后发送欢迎邮件。

 

讨论

发送一份电子邮件,你需要配置SMTP服务器地址、端口、用户名和密码。为了让配置更加简单,建议将这些信息存储到Web.config的AppSettings节点里。

    <appSettings>

<add key="webpages:Version" value="1.0.0.0" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="smtpServer" value="localhost" />
<add key="smtpPort" value="25" />
<add key="smtpUser" value="" />
<add key="smtpPass" value="" />
<add key="adminEmail" value="no-reply@no-reply.com" />

</appSettings>

在smtpServer、smtpPort、smtpUser和smtpPass的Value中输入可用的参数。 

为了更好的组织项目,我们将创建一个新的文件夹来包含这些发送邮件的类。右键单击项目选择“添加”->“新建文件夹”并将其命名为“Utils”。现在,右键单击新创建的“Utils”文件夹,选择“添加”->"类"并命名为“MailClient.cs”。 

为了方便访问,MailClient类被定义为静态类,未来在与其他系统集成使用时,不需要实例化新的对象,直接使用即可。下面是MailClient类的完整代码:

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

namespace MvcApplication4.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);
}
}
}

在类开始的时候,从Web.Config中引用值并创建SmtpClient类实例。下面定义的SendMessage方法是私有方法,不能从类外部直接调用,此方法的是实际执行发送功能的方法。这个方法创建一个新的MailMessage实例,并通过先前创建SmtpClient对象发送。最后,创建了一个SendWelcome功能来接受用户的电子邮件地址参数,通过调用SendMessage方法来发送欢迎邮件。 

在Account控制器中,用户通过Register方法注册或更新之后立即调用SendWelcome方法发送电子邮件:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using MvcApplication4.Models;
using MvcApplication4.Utils;

namespace MvcApplication4.Controllers
{
public class AccountController : Controller
{

//
// POST: /Account/Register
[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("Index", "Home");
}
else
{
ModelState.AddModelError("",
ErrorCodeToString(createStatus));
}
}
// If we got this far, something failed,
// redisplay form
return View(model);
}

}
}

上面的代码是一个基本的例子,实现了用户在注册过程中向用户发送一封欢迎邮件。在现代社会中,自动处理表单是非常棒的点子,在以后的使用,我们可以在邮件中加入“确认您的电子邮件地址”的链接消息,并要求用户必须通过点击欢迎电子邮件中的链接激活账户之后,才可以登录。

 

参考

StmpClient MailMessage 原书地址 书籍源代码

posted on 2011-12-09 09:32  O2DS  阅读(3014)  评论(9编辑  收藏  举报

导航