首页 > 代码库 > C#之发送邮件【模板】+【封装】ZJ版

C#之发送邮件【模板】+【封装】ZJ版

PS: 为了弥补上篇博客的不足,正好周六闲着没事。所有进行优化下,来个终结版

功能实现:模板发送+自指定邮箱发送+解耦

总体预览如下:

技术分享

 

各代码如下:(代码略多,所以都折叠了)

前台;

技术分享
@{    Layout = null;}<!DOCTYPE html><html><head>    <meta name="viewport" content="width=device-width" />    <title>Index</title></head><body>    <div>        请输入您的邮箱:<input type="text" id="email" /> <input type="button" value=http://www.mamicode.com/"获取验证码" id="getYZM" /><br />        返回信息:<input type="text" id="yzm" />    </div></body></html><script src=http://www.mamicode.com/"~/Scripts/jquery-1.8.2.min.js"></script><script>        $("#getYZM").click(function () {            var emailName = $("#email").val().trim();            if (emailName.length <= 0) {                alert("请输入邮箱"); return;            }            $.post(@Url.Action("SendYanZhengMa","Home"), { recEmail: emailName }, function (_data) {                if (_data=http://www.mamicode.com/="no") {                    alert("发送失败!");                } else {                    $("#yzm").val(_data);                }            })        });</script>
View Code

 后台;(简单调用Helper类轻松搞定,哈哈)

技术分享
using System;using System.Collections.Generic;using System.Collections.Specialized;using System.Linq;using System.Web;using System.Web.Mvc;using 发送邮件ZJ.Helpers;namespace 发送邮件ZJ.Controllers{    public class HomeController : Controller    {        //        // GET: /Home/        public ActionResult Index()        {            return View();        }        [HttpPost]        public ActionResult SendYanZhengMa(string recEmail)        {                                 //调用模板文件 并进行占位符替换            string templetpath = Server.MapPath("../mailtemplate/irupoint.txt");            NameValueCollection myCol = new NameValueCollection();            myCol.Add("ename", "一明");            myCol.Add("from", "地狱之门");            myCol.Add("link", "http://shuai7boy.cn/");            string mailBody = TemplateHelper.BulidByFile(templetpath, myCol);            string result= MailHelper.SendNetMail(recEmail, mailBody, true);                    return Content(result);        }    }}
View Code

MailHelper.cs(发送邮件封装类)

技术分享
using System;using System.Collections.Generic;using System.Configuration;using System.Linq;using System.Net;using System.Net.Mail;using System.Text;using System.Web;namespace 发送邮件ZJ.Helpers{    /// <summary>    /// 发送邮件帮助类    /// </summary>    public class MailHelper    {        /// <summary>        ///         /// </summary>        /// <param name="recEmail">收件地址</param>        /// <param name="mailBody">发送内容:这里可以传递过来普通内容或模板内容</param>        ///  <param name="IsBodyHtml">设置是否以html格式发送</param>        /// <returns></returns>        public static string SendNetMail(string recEmail, string mailBody, bool IsBodyHtml)        {            string result = "no";//返回结果            string sendFrom = ConfigurationManager.AppSettings["sendFrom"]; //生成一个发送地址            string sendUserName = ConfigurationManager.AppSettings["sendUserName"];//发送人的名字                      string recUserName = ConfigurationManager.AppSettings["recUserName"];//收件人名字            string sendTitle = ConfigurationManager.AppSettings["sendTitle"];//发送邮件标题            string username = ConfigurationManager.AppSettings["username"];//发送邮箱用户名            string passwd = ConfigurationManager.AppSettings["passwd"];//发送邮箱密码            try {             //确定smtp服务器地址。实例化一个Smtp客户端            System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("smtp.yeah.net");                                 //构造一个发件人地址对象            MailAddress from = new MailAddress(sendFrom, sendUserName, Encoding.UTF8);//发送地址,发送人的名字            //构造一个收件人地址对象            MailAddress to = new MailAddress(recEmail,recUserName, Encoding.UTF8);//收件地址,收件人的名字            //构造一个Email的Message对象            MailMessage message = new MailMessage(from, to);            //添加邮件主题和内容            message.Subject = sendTitle;            message.SubjectEncoding = Encoding.UTF8;            message.Body = mailBody;            message.BodyEncoding = Encoding.UTF8;            //设置邮件的信息            client.DeliveryMethod = SmtpDeliveryMethod.Network;            message.IsBodyHtml = IsBodyHtml;//设置是否为html格式的值            //如果服务器支持安全连接,则将安全连接设为true。            //gmail支持,163不支持,如果是gmail则一定要将其设为true                           client.EnableSsl = true;            //设置用户名和密码。                         client.UseDefaultCredentials = false;            //用户登陆信息            NetworkCredential myCredentials = new NetworkCredential(username, passwd);            client.Credentials = myCredentials;            //发送邮件            client.Send(message);            //提示发送成功            result = "ok";            }            catch            {                result = "no";            }            return result;        }    }}
View Code

TemplateHelper.cs(发送模板替换类)

技术分享
using System;using System.Collections;using System.Collections.Generic;using System.Collections.Specialized;using System.IO;using System.Linq;using System.Web;namespace 发送邮件ZJ.Helpers{    public class TemplateHelper    {        /// <summary>        /// 私有构造方法,不允许创建实例        /// </summary>        private TemplateHelper()        {            // TODO: Add constructor logic here        }        /// <summary>        /// Template File Helper         /// </summary>        /// <param name="templatePath">Templet Path</param>        /// <param name="values">NameValueCollection</param>        /// <returns>string</returns>        public static string BulidByFile(string templatePath, NameValueCollection values)        {            return BulidByFile(templatePath, values, "[$", "]");        }        /// <summary>        ///         /// </summary>        /// <param name="template"></param>        /// <param name="values">NameValueCollection obj</param>        /// <param name="prefix"></param>        /// <param name="postfix"></param>        /// <returns></returns>        public static string Build(string template, NameValueCollection values, string prefix, string postfix)        {            if (values != null)            {                foreach (DictionaryEntry entry in values)                {                    template = template.Replace(string.Format("{0}{1}{2}", prefix, entry.Key, postfix), entry.Value.ToString());                }            }            return template;        }        /// <summary>        ///         /// </summary>        /// <param name="templatePath"></param>        /// <param name="values"></param>        /// <param name="prefix"></param>        /// <param name="postfix"></param>        /// <returns></returns>        public static string BulidByFile(string templatePath, NameValueCollection values, string prefix, string postfix)        {            StreamReader reader = null;            string template = string.Empty;            try            {                reader = new StreamReader(templatePath);                template = reader.ReadToEnd();                reader.Close();                if (values != null)                {                    foreach (string key in values.AllKeys)                    {                        template = template.Replace(string.Format("{0}{1}{2}", prefix, key, postfix), values[key]);                    }                }            }            catch            {            }            finally            {                if (reader != null)                    reader.Close();            }            return template;        }    }}
View Code

irupoint.txt(自定义模板,这里简单定义就行了,别忘了,格式要直接html里面才起作用哦,具体原因尚未确定)

技术分享
<div style="background-color:pink;font-size:25px;">hi [$ename]:<br/> &nbsp;&nbsp;&nbsp;&nbsp;您收到的是来自[$from]的邮件。 您还好么?<br/> &nbsp;    详情:<a href=http://www.mamicode.com/[$link] target="_blacnk">点击</a></div>
View Code

 

Web.config(这里只抽取了邮件配置部分)

技术分享
<appSettings>    <!--发送邮件配置开始-->    <add key="sendFrom" value=http://www.mamicode.com/"techblog@yeah.net"/><!--发送邮件地址,及要发送邮件所在的域名-->    <add key="sendUserName" value=http://www.mamicode.com/"RYJ"/><!--发送人的名字-->    <add key="recEmail" value=http://www.mamicode.com/"2636922684@qq.com"/><!--收件人地址-->    <add key="recUserName" value=http://www.mamicode.com/"一明"/><!--收件人姓名-->    <add key="sendTitle" value=http://www.mamicode.com/"帅7的标题"/><!--发送邮件标题-->    <add key="username" value=http://www.mamicode.com/"techblog"/><!--发送邮箱用户名-->    <add key="passwd" value=http://www.mamicode.com/"2436chao"/><!--发送邮箱密码-->   <!--发送邮件配置结束--></appSettings>
View Code

 

好了,就这么多,大家来看下效果吧(●‘?‘●)

 技术分享

看,收到了!

技术分享

代码下载

zj。。。。。。

C#之发送邮件【模板】+【封装】ZJ版