【譯】MVC3 20個秘方-(5)發(fā)送歡迎郵件
場景
很多網站要求人們先注冊再去訪問內容或者發(fā)表評論.網站如牛毛,怎么可能讓人們記住每個他們注冊過的網站。在注冊的過程中,可以發(fā)送一個電子郵件來提醒用戶他們剛剛注冊了,這樣,他們可能一會還會返回到你的網站。
解決方案
在用戶注冊之后使用SmtpClient和MailMessage發(fā)送郵件通知。
討論
發(fā)送一個郵件之前,你需要配置一個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 電子郵件設置

為了便于組織項目的結構,我們需要創(chuàng)建一個新的文件夾和新的類去包含必要的發(fā)送郵件函數。
右擊項目,添加->新建文件夾并且命名問Uitls。右擊新建一個類命名為MailClient.cs.
MailClient類及其函數將被定義成static便于使用。日后他被整合到新的功能里時,也不需要為它創(chuàng)建新的實例。下邊是一個完整的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的配置創(chuàng)建一個新的SmtpClient 實例。然后創(chuàng)建一個SendMessage的函數。這個函數是私有的,不應該直接調用這個函數。這個函數在實際執(zhí)行發(fā)送的時候調用。它創(chuàng)建了一個新的MailMessage對象,并通過前邊歘構建的SmtpClient對象發(fā)送它。最后SendWelcome函數是創(chuàng)建接受電子郵件的地址。它生成一個通用的消息去發(fā)送你的電子郵件。它通過SendMessage函數發(fā)送。
為了在注冊之后發(fā)送郵件通知。在Account controller中的register action必須在用戶成功創(chuàng)建賬戶后調用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);
}
前邊的代碼是一個基本的例子。在當今社會,以自動化的形式處理存在的應用程序是一個好主意。
你可以進一步擴展這個例子。在你發(fā)送的歡迎郵件中附帶一個驗證消息。這樣可以驗證用戶電子郵件地址的有效性。讓他點擊在歡迎郵件的鏈接。然后他才可能登陸。
另請參閱
譯者注:在.NET 4.0中,微軟有提供了一個新的helper “Webmail”。更加方便。
感興趣的朋友可以看看WebMail

浙公網安備 33010602011771號