场景 很多网站要求人们先注册再去访问内容或者发表评论.网站如牛毛,怎么可能让人们记住每个他们注册过的网站。在注册的过程中,可以发送一个电子邮件来提醒用户他们刚刚注册了,这样,他们可能一会还会返回到你的网站。
解决方案
在用户注册之后使用SmtpClient和MailMessage发送邮件通知。
讨论
发送一个邮件之前,你需要配置一个SMTP服务器,端口,用户名和密码。为了使配置简单化,我建议你在web.config的appsetting中配置。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <appSettings><addkey="webpages:Version"value="1.0.0.0"/><addkey="ClientValidationEnabled"value="true"/><addkey="UnobtrusiveJavaScriptEnabled"value="true"/><addkey="smtpServer"value="localhost"/><addkey="smtpPort"value="25"/><addkey="smtpUser"value=""/><addkey="smtpPass"value=""/><addkey="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 类:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | 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方法。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | [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);        } | 
前边的代码是一个基本的例子。在当今社会,以自动化的形式处理存在的应用程序是一个好主意。
你可以进一步扩展这个例子。在你发送的欢迎邮件中附带一个验证消息。这样可以验证用户电子邮件地址的有效性。让他点击在欢迎邮件的链接。然后他才可能登陆。
 
                    
                     
                    
                 
                    
                 

 
        
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号