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="获取验证码" id="getYZM" /><br />
- 返回信息:<input type="text" id="yzm" />
- </div>
- </body>
- </html>
- <script src="~/Scripts/jquery-1.8.2.min.js"></script>
- <script>
- $("#getYZM").click(function () {
- var emailName = $("#email").val().trim();
- if (emailName.length <= ) {
- alert("请输入邮箱"); return;
- }
- $.post('@Url.Action("SendYanZhengMa","Home")', { recEmail: emailName }, function (_data) {
- if (_data=="no") {
- alert("发送失败!");
- } else {
- $("#yzm").val(_data);
- }
- })
- });
- </script>
后台;(简单调用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);
- }
- }
- }
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;
- }
- }
- }
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;
- }
- }
- }
irupoint.txt(自定义模板,这里简单定义就行了,别忘了,格式要直接html里面才起作用哦,具体原因尚未确定)
- <div style="background-color:pink;font-size:25px;">
- hi [$ename]:<br/>
- 您收到的是来自[$from]的邮件。 您还好么?<br/>
- 详情:<a href='[$link]' target="_blacnk">点击</a>
- </div>
Web.config(这里只抽取了邮件配置部分)
- <appSettings>
- <!--发送邮件配置开始-->
- <add key="sendFrom" value="techblog@yeah.net"/><!--发送邮件地址,及要发送邮件所在的域名-->
- <add key="sendUserName" value="RYJ"/><!--发送人的名字-->
- <add key="recEmail" value="2636922684@qq.com"/><!--收件人地址-->
- <add key="recUserName" value="一明"/><!--收件人姓名-->
- <add key="sendTitle" value="帅7的标题"/><!--发送邮件标题-->
- <add key="username" value="techblog"/><!--发送邮箱用户名-->
- <add key="passwd" value="2436chao"/><!--发送邮箱密码-->
- <!--发送邮件配置结束-->
- </appSettings>
好了,就这么多,大家来看下效果吧(●'◡'●)
看,收到了!
zj。。。。。。
C#之发送邮件【模板】+【封装】ZJ版的更多相关文章
- 使用requireJS,backboneJS,和underscoreJS完成自定义模板封装
使用requireJS,backboneJS,和underscoreJS完成自定义模板封装 原来的代码 当我们进行一个列表的数据填充的时候,是这样做的: //获取美食列表 function getFo ...
- 瞎j8封装第二版之数据层的封装
看了以前写的代码,对就是下面这个 手把手封装数据层之DataUtil数据库操作的封装 觉得以前写的代码好烂啊!!!,重新理了一下思路,写得更规范和简练,应该效率也会高很多,用了一下下午写的连接池(半废 ...
- BZOJ 2243 染色 | 树链剖分模板题进阶版
BZOJ 2243 染色 | 树链剖分模板题进阶版 这道题呢~就是个带区间修改的树链剖分~ 如何区间修改?跟树链剖分的区间询问一个道理,再加上线段树的区间修改就好了. 这道题要注意的是,无论是线段树上 ...
- jenkins 发送邮件模板
jenkins 发送邮件模板 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> ...
- JavaWeb_(session和application)用户登录注册模板_进阶版
用户登录注册模板_基础版 传送门 用户登录注册模板进阶版 添加了获得获得当前登录用户信息及存储登录人数 用户登录后,在首页.注册页.登录页显示登录用户信息和存储登录人数信息 目录结构 <%@pa ...
- 分享几套bootstrap后台模板【TP5版】
分享几套bootstrap后台模板[TP5版],模板来源于网络,需要的拿走.1.AdminLTE 链接: http://pan.baidu.com/s/1o7BXeCM 密码: zfhy 2.Boot ...
- 【RTOS】基于V7开发板的uCOS-III,uCOS-II,RTX4,RTX5,FreeRTOS原版和带CMSIS-RTOS V2封装层版全部集齐
RTOS模板制作好后,后面堆各种中间件就方便了. 1.基于V7开发板的最新版uCOS-II V2.92.16程序模板,含MDK和IAR,支持uC/Probe https://www.cnblogs.c ...
- JavaWeb_(request和response)用户登录注册模板_基础版
用户登录注册模板进阶版 传送门 用户登录注册模板基础版 登录:当用户登录成功时,跳转到personCenter.jsp,当用户登录失败时,跳转到login.jsp并给出提示 注册:当用户注册成功时,跳 ...
- C++模板封装Win32 API 动态调用
起因 花两周通读了一遍<C++ Primer>,积攒的疑惑一扫而光. 前因 利用C++11可变模板,封装调用dll导出函数 本以为已经很好用了,最近抽时间巩固下知识体系,发现自己道行不够! ...
随机推荐
- WebAPI接收JSON参数注意事项
运行环境:ASP.NET 4.5.2. 当我们向GlobalConfiguration.Configuration.MessageHandlers添加一个DelegatingHandler派生类后,很 ...
- 制作CAB包
制作CAB包 inf文件 INF是Device INFormation File的英文缩写,是Microsoft公司为硬件设备制造商发布其驱动程序推出的一种文件格式,INF文件中包含硬件设备的信息或脚 ...
- ASP.NET MVC——CodeFirst开发模式
Entity Framework框架提供了几种开发模式,比如Database First,Model First,Code First.Database First是最老也是应用得最广泛的一种设计方式 ...
- Bonobo创建新库出错,解决方案
创建新库出错如下: Native library pre-loader is trying to load native SQLite library "D:\wwwroot\localho ...
- HashMap与HashTable的区别
HashMap和HashSet的区别是Java面试中最常被问到的问题.如果没有涉及到Collection框架以及多线程的面试,可以说是不完整.而Collection框架的问题不涉及到HashSet和H ...
- java中动态代理的实现
动态代理的实现 使用的模式:代理模式. 代理模式的作用是:为其他对象提供一种代理以控制对这个对象的访问.类似租房的中介. 两种动态代理: (1)jdk动态代理,jdk动态代理是由Java内部的反射机制 ...
- Mysql性能优化一
下一篇:Mysql性能优化二 mysql的性能优化无法一蹴而就,必须一步一步慢慢来,从各个方面进行优化,最终性能就会有大的提升. Mysql数据库的优化技术 对mysql优化是一个综合性的技术,主要包 ...
- 释放Android的函数式能量(I):Kotlin语言的Lambda表达式
原文标题:Unleash functional power on Android (I): Kotlin lambdas 原文链接:http://antonioleiva.com/operator-o ...
- UITabBarController 升级定制
UITabBarController 定制 特点 用法 1.准备工作: 加入你的相关图片,放入了Assets.xcassets; 导入Categroy文件夹(这个里面的文件,在这里不详细说明了,有疑问 ...
- 安装cocoapods遇到两大坑-Ruby版本升级和Podfile的配置
今天安装cocoapods #移除原有ruby源 $ gem sources --remove https://rubygems.org/ #使用可用的淘宝网 $ gem sources -a htt ...