• ASP.NET学习之向邮箱发邮件


    准备工作:

    1、在项目的文件夹App_Data下建立一个html文件,该文件的作用是等会发送的邮件的内容。

    2、在Models文件夹中建立一个实体类:UserInfo

    3、建立控制器和相应的视图

    具体内容:

    1、创建作为发送的邮件的内容的html文件,具体代码如下:【可以在任意文件夹下建立这个文件,不一定一定要在这个文件夹中创建,如果一定要将html文件放在这个文件中。要是直接在App_Data文件夹下不能建立html文件,可以在其他文件夹中创建好之后拖到这个文件夹下来。

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title></title>
    </head>
    <body>
        <h1>会员注册</h1>
        <p>亲爱的{{Name}}您好:</p>
        <p>
            由于你在{{RegisterOn}}注册成为本站会员,为了完成会员注册程序,我们请您点击以下链接用以确定您的Email地址是有效的:<br />
            <a href="{{AUTH_URL}}" target="_blank">{{AUTH_URL}}</a>
        </p>
        <p>
            谢谢!
        </p>
        <p>
            "ASP.NET MVC 4 开发实战-电子商务演示"
        </p>
    </body>
    </html>

    2、在Models下建立UserInfo类:代码如下所示:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace SendEmail.Models
    {
        [Bind(Exclude = "LoginTime")]    //表示在数据绑定的时候不绑定LoginTime字段
        public class UserInfo
        {
            public int Id { get; set; }
            [DisplayName("会员邮箱")]
            [Required]
            public string Email { get; set; }
    
            [DisplayName("会员密码")]
            [Required]
            public string Password { get; set; }
    
            [DisplayName("会员名称")]
            [Required]
            public string Name { get; set; }
    
            public string LoginTime { get; set; }
        }
    }

    3、创建控制器和相对应的视图页面:代码如下所示:

    【控制器代码:】

    using SendEmail.Models;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Mail;
    using System.Text;
    using System.Web;
    using System.Web.Mvc;
    
    namespace SendEmail.Controllers
    {
        public class SendEmailController : Controller
        {
            /// <summary>
            /// 主要是显示页面用的
            /// </summary>
            /// <returns></returns>
            public ActionResult Index()
            {
                return View();
            }
    
            /// <summary>
            /// 点击注册按钮执行的代码
            /// </summary>
            /// <param name="user"></param>
            /// <returns></returns>
            [HttpPost]
            public ActionResult Index(UserInfo user)
            {
                if (user != null)
                {
                    if (ModelState.IsValid)
                    {
                        SendEmailToUser(user);
                    }
                    return RedirectToAction("Result");    //页面跳转
                }
                else
                {
                    return View();
                }
            }
    
            /// <summary>
            /// 注册成功过后跳转到的页面
            /// </summary>
            /// <returns></returns>
            public ActionResult Result()
            {
                return View();
            }
    
            /// <summary>
            /// 发送邮件的核心代码
            /// </summary>
            /// <param name="user">接收到的页面注册的用户</param>
            private void SendEmailToUser(UserInfo user)
            {
                user.LoginTime = DateTime.Now.ToString();
                string mailBody = System.IO.File.ReadAllText(Server.MapPath("~/App_Data/EmailContent.html"));   //获得html文件
                mailBody = mailBody.Replace("{{Name}}", user.Name);               //填充页面上的占位符的内容
                mailBody = mailBody.Replace("{{RegisterOn}}", user.LoginTime.ToString());
                var auth_url = new UriBuilder(Request.Url)
                {
                    Path = Url.Action("Index"),
                    Query = ""
                };
                mailBody = mailBody.Replace("{{AUTH_URL}}", auth_url.ToString());
                try
                {
                    MailMessage myMail = new MailMessage();                       //创建邮件实例对象
    
                    myMail.From = new MailAddress("jun1n2u3j@sina.com");          //发送者【发送邮件的用户的邮箱地址】
                    myMail.To.Add(user.Email);                                    //接收者【接收邮件的用户的邮箱地址】
    
                    myMail.Subject = "我的电子商务网站,会员注册确认信息";          //邮件标题
                    myMail.SubjectEncoding = Encoding.UTF8;            //标题编码
    
                    myMail.Body = mailBody;                   //邮件内容
                    myMail.BodyEncoding = Encoding.UTF8;          //邮件内容编码
                    myMail.IsBodyHtml = true;               //邮件内容是否支持html
    
                    SmtpClient smtp = new SmtpClient();   //创建smtp实例对象
                    smtp.Host = "smtp.sina.com";             //邮件服务器SMTP
                    smtp.Credentials = new NetworkCredential("jun1n2u3j", "jun1n2u3j");   //发送邮件的用户的邮箱名称和密码【这里一定要写对】
                    smtp.Send(myMail);   //发送邮件
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
    }

    【视图页面之Index页面】

    @model SendEmail.Models.UserInfo
    
    @{
        ViewBag.Title = "Index";
    }
    
    <h2>会员注册</h2>
    
    @using (Html.BeginForm()) {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)
        <fieldset>
            <legend>请输入用户注册信息</legend>
    
            <div class="editor-label">
                @Html.LabelFor(model => model.Email)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Email)
                @Html.ValidationMessageFor(model => model.Email)
            </div>
    
            <div class="editor-label">
                @Html.LabelFor(model => model.Password)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Password)
                @Html.ValidationMessageFor(model => model.Password)
            </div>
    
            <div class="editor-label">
                @Html.LabelFor(model => model.Name)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Name)
                @Html.ValidationMessageFor(model => model.Name)
            </div>
    
            <p>
                <input type="submit" value="注册" />
            </p>
        </fieldset>
    }
    
    @section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
    }

    【视图页面之Result页面】

    @{
        ViewBag.Title = "Result";
    }
    
    <h2>注册结果</h2>
    <strong>恭喜你,注册成功!</strong>
    <mark>Congratulation! *_*</mark>

    4、效果展示

    5、该过程中遇到的错误以及解决方法:

    问题一:

    解决方法:

    检查

    myMail.From = new MailAddress("jun1n2u3j@sina.com");

     myMail.To.Add(member.Email); 

    这两句话里面的值是否符合邮件的格式。如果不符合格式就会抛出这样的错误!

    问题二:

    解决方法:

    检查

    邮件的收发方的smtp服务是否都开启了。

    发邮件方的用户名和密码是否正确:smtp.Credentials = new NetworkCredential("jun1n2u3j", "jun1n2u3j");这里的用户名和密码一定要正确

    问题三:

    解决方法:

    换个邮箱发送。

    我之前用的是QQ邮箱做测试,但是就是出现这个问题。于是改换成新浪的邮箱。就成功了!具体导致这样的原因是什么,我也不清楚。希望知道的可以给我留言。谢谢

    写写博客,方便自己也方便有需要的人!*_*!

     

  • 相关阅读:
    nginx反向代理
    遇到的好玩的mvc路由
    有意思的OWIN,附脱离iis的webapi
    nginx转发配置
    SQL 2016安装中遇到的问题
    3级级联 国家--城市
    box.css
    common.css
    节假日设置
    Order_Leave.aspx
  • 原文地址:https://www.cnblogs.com/Yisijun/p/4696400.html
Copyright © 2020-2023  润新知