samesite


【译】MVC3 20个秘方-(5)发送欢迎邮件

场景
很多网站要求人们先注册再去访问内容或者发表评论.网站如牛毛,怎么可能让人们记住每个他们注册过的网站。在注册的过程中,可以发送一个电子邮件来提醒用户他们刚刚注册了,这样,他们可能一会还会返回到你的网站。

解决方案

在用户注册之后使用SmtpClient和MailMessage发送邮件通知。

讨论

发送一个邮件之前,你需要配置一个SMTP服务器,端口,用户名和密码。为了使配置简单化,我建议你在web.config的appsetting中配置。

<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>


必要时可以去更新这些value 去反射你的SMTP server,port,username 和password

提示:你也可以使用Visual studio的ASP.NET配置工具去配置。

选择应用程序-> 配置 SMTP 电子邮件设置

为了便于组织项目的结构,我们需要创建一个新的文件夹和新的类去包含必要的发送邮件函数。

右击项目,添加->新建文件夹并且命名问Uitls。右击新建一个类命名为MailClient.cs.

MailClient类及其函数将被定义成static便于使用。日后他被整合到新的功能里时,也不需要为它创建新的实例。下边是一个完整的MailClient 类:

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

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

一开始,通过webconfig的配置创建一个新的SmtpClient 实例。然后创建一个SendMessage的函数。这个函数是私有的,不应该直接调用这个函数。这个函数在实际执行发送的时候调用。它创建了一个新的MailMessage对象,并通过前边歘构建的SmtpClient对象发送它。最后SendWelcome函数是创建接受电子邮件的地址。它生成一个通用的消息去发送你的电子邮件。它通过SendMessage函数发送。

为了在注册之后发送邮件通知。在Account controller中的register action必须在用户成功创建账户后调用SendWelcome方法。

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

前边的代码是一个基本的例子。在当今社会,以自动化的形式处理存在的应用程序是一个好主意。

你可以进一步扩展这个例子。在你发送的欢迎邮件中附带一个验证消息。这样可以验证用户电子邮件地址的有效性。让他点击在欢迎邮件的链接。然后他才可能登陆。

另请参阅

SmtpClient and MailMessage

译者注:在.NET 4.0中,微软有提供了一个新的helper “Webmail”。更加方便。

感兴趣的朋友可以看看WebMail

posted @ 2011-11-23 20:25  技术弟弟  阅读(3487)  评论(4编辑  收藏  举报