MVC发送邮件

来源:互联网 发布:nes30 pro软件 编辑:程序博客网 时间:2024/06/05 05:35

邮件帮助类

using System;using System.Collections.Generic;using System.Configuration;using System.Linq;using System.Net;using System.Net.Mail;using System.Text;namespace TEAMAX.Framework.Utility{   public class EmailHelper    {        #region [ 属性(发送Email相关) ]        private string _SmtpHost = string.Empty;        private int _SmtpPort = -1;        private string _FromEmailAddress = string.Empty;        private string _FormEmailPassword = string.Empty;        private string _ToEmailListString = string.Empty;        private string _CcEmailListString = string.Empty;        private string _BccEmailListString = string.Empty;        /// <summary>        /// smtp 服务器         /// </summary>        public string SmtpHost        {            get            {                if (string.IsNullOrEmpty(_SmtpHost))                {                    _SmtpHost = ConfigurationManager.AppSettings["SmtpHost"];                }                return _SmtpHost;            }        }        /// <summary>        /// smtp 服务器端口  默认为25        /// </summary>        public int SmtpPort        {            get            {                if (_SmtpPort == -1)                {                    if (!int.TryParse(ConfigurationManager.AppSettings["SmtpPort"], out _SmtpPort))                    {                        _SmtpPort = 25;                    }                }                return _SmtpPort;            }        }        /// <summary>        /// 发送者 Eamil 地址        /// </summary>        public string FromEmailAddress        {            get            {                if (string.IsNullOrEmpty(_FromEmailAddress))                {                    _FromEmailAddress = ConfigurationManager.AppSettings["FromEmailAddress"];                }                return _FromEmailAddress;            }        }        /// <summary>        /// 发送者 Eamil 密码        /// </summary>        public string FormEmailPassword        {            get            {                if (string.IsNullOrEmpty(_FormEmailPassword))                {                    _FormEmailPassword = ConfigurationManager.AppSettings["FormEmailPassword"];                }                return _FormEmailPassword;            }        }        #endregion        #region [ 属性(邮件相关) ]        /// <summary>        /// 收件人 Email 列表,多个邮件地址之间用 半角逗号“,”或者分号“;”,或者竖线“|” 等符号分隔开        /// </summary>        public string ToEmailListString        {            get            {                if (string.IsNullOrEmpty(_ToEmailListString))                {                    return ConfigurationManager.AppSettings["ToEmailListString"];                }                return _ToEmailListString;            }            set            {                this._ToEmailListString = value;            }        }        /// <summary>        /// 邮件的抄送者,支持群发,多个邮件地址之间用 半角逗号“,”或者分号“;”,或者竖线“|” 等符号分隔开        /// </summary>        public string CcEmailListString        {            get            {                if (string.IsNullOrEmpty(this._CcEmailListString))                {                    return ConfigurationManager.AppSettings["CcEmailListString"];                }                return _CcEmailListString;            }            set            {                this._CcEmailListString = value;            }        }        /// <summary>        /// 邮件的密送者,支持群发,多个邮件地址之间用 半角逗号“,”或者分号“;”,或者竖线“|” 等符号分隔开        /// </summary>        public string BccEmailListString        {            get            {                if (string.IsNullOrEmpty(_BccEmailListString))                {                    return ConfigurationManager.AppSettings["BccEmail"];                }                return _BccEmailListString;            }            set            {                this._BccEmailListString = value;            }        }        /// <summary>        /// 邮件标题        /// </summary>        public string Subject { get; set; }        /// <summary>        /// 邮件正文        /// </summary>        public string EmailBody { get; set; }        private bool _IsBodyHtml;        /// <summary>        /// 邮件正文是否为Html格式        /// </summary>        public bool IsBodyHtml        {            get { return _IsBodyHtml; }            set { _IsBodyHtml = value; }        }        /// <summary>        /// 附件列表        /// </summary>        public List<Attachment> AttachmentList { get; set; }        #endregion        #region [ 构造函数 ]        /// <summary>        /// 构造函数(EmailBody默认为html格式)        /// </summary>        /// <param name="subject">邮件标题</param>        /// <param name="emailBody">邮件正文</param>        public EmailHelper(string subject, string emailBody)        {            this.Subject = subject;            this.IsBodyHtml = true;            this.EmailBody = emailBody;        }        /// <summary>        /// 构造函数        /// </summary>        /// <param name="subject">邮件标题</param>        /// <param name="isBodyHtml">邮件正文是否为Html格式</param>        /// <param name="emailBody">邮件正文</param>        public EmailHelper(string subject, bool isBodyHtml, string emailBody)        {            this.Subject = subject;            this.IsBodyHtml = IsBodyHtml;            this.EmailBody = emailBody;        }        /// <summary>        /// 构造函数(EmailBody默认为html格式)        /// </summary>        /// <param name="subject">邮件标题</param>        /// <param name="emailBody">邮件正文</param>        /// <param name="attachmentList">附件列表</param>        public EmailHelper(string subject, string emailBody, List<Attachment> attachmentList)        {            this.Subject = subject;            this.EmailBody = emailBody;            this.AttachmentList = attachmentList;            this.IsBodyHtml = true;        }        /// <summary>        /// 构造函数        /// </summary>        /// <param name="subject">邮件标题</param>        /// <param name="emailBody">邮件正文</param>        /// <param name="isBodyEmail">邮件正文是否为Html格式</param>        /// <param name="attachmentList">附件列表</param>        public EmailHelper(string subject, string emailBody, bool isBodyEmail, List<Attachment> attachmentList)        {            this.Subject = subject;            this.EmailBody = emailBody;            this.AttachmentList = attachmentList;        }        /// <summary>        /// 构造函数 (EmailBody默认为html格式)        /// </summary>        /// <param name="toList">收件人列表字符串</param>        /// <param name="subject">邮件标题</param>        /// <param name="emailBody">邮件正文</param>        public EmailHelper(string toEmailListString, string subject, string emailBody)        {            this.ToEmailListString = toEmailListString;            this.Subject = subject;            this.EmailBody = emailBody;            this.IsBodyHtml = true;        }        /// <summary>        /// 构造函数        /// </summary>        /// <param name="toList">收件人列表字符串</param>        /// <param name="subject">邮件标题</param>        /// <param name="isBodyHtml">邮件正文是否为Html格式</param>        /// <param name="emailBody">邮件正文</param>        public EmailHelper(string toEmailListString, string subject, bool isBodyHtml, string emailBody)        {            this.ToEmailListString = toEmailListString;            this.Subject = subject;            this.IsBodyHtml = isBodyHtml;            this.EmailBody = emailBody;        }        /// <summary>        /// 构造函数        /// </summary>        /// <param name="toEmailListString">收件人列表字符串</param>        /// <param name="ccEmailListString">抄送人列表字符串</param>        /// <param name="subject">邮件标题</param>        /// <param name="isBodyHtml">邮件正文是否为Html格式</param>        /// <param name="emailBody">邮件正文</param>        public EmailHelper(string toEmailListString, string ccEmailListString, string subject, bool isBodyHtml, string emailBody)        {            this.ToEmailListString = toEmailListString;            this.CcEmailListString = ccEmailListString;            this.Subject = subject;            this.IsBodyHtml = isBodyHtml;            this.EmailBody = emailBody;        }        /// <summary>        /// 构造函数        /// </summary>        /// <param name="toEmailListString">收件人列表字符串</param>        /// <param name="ccEmailListString">抄送人列表字符串</param>        /// <param name="subject">邮件标题</param>        /// <param name="isBodyHtml">邮件正文是否为Html格式</param>        /// <param name="emailBody">邮件正文</param>        /// <param name="attachmentList">附件列表</param>        public EmailHelper(string toEmailListString, string ccEmailListString, string subject, bool isBodyHtml, string emailBody, List<Attachment> attachmentList)        {            this.ToEmailListString = toEmailListString;            this.CcEmailListString = ccEmailListString;            this.Subject = subject;            this.IsBodyHtml = isBodyHtml;            this.EmailBody = emailBody;            this.AttachmentList = attachmentList;        }        /// <summary>        /// 构造函数        /// </summary>        /// <param name="toEmailListString">收件人列表字符串</param>        /// <param name="ccEmailListString">抄送人列表字符串</param>        /// <param name="bccEmailListString">密送人列表字符串</param>        /// <param name="subject">邮件标题</param>        /// <param name="isBodyHtml">邮件正文是否为Html格式</param>        /// <param name="emailBody">邮件正文</param>        public EmailHelper(string toEmailListString, string ccEmailListString, string bccEmailListString, string subject, bool isBodyHtml, string emailBody)        {            this.ToEmailListString = toEmailListString;            this.CcEmailListString = ccEmailListString;            this.BccEmailListString = bccEmailListString;            this.Subject = subject;            this.IsBodyHtml = isBodyHtml;            this.EmailBody = emailBody;        }        /// <summary>        /// 构造函数        /// </summary>        /// <param name="toEmailListString">收件人列表字符串</param>        /// <param name="ccEmailListString">抄送人列表字符串</param>        /// <param name="bccEmailListString">密送人列表字符串</param>        /// <param name="subject">邮件标题</param>        /// <param name="isBodyHtml">邮件正文是否为Html格式</param>        /// <param name="emailBody">邮件正文</param>        /// <param name="attachmentList">附件列表</param>        public EmailHelper(string toEmailListString, string ccEmailListString, string bccEmailListString, string subject, bool isBodyHtml, string emailBody, List<Attachment> attachmentList)        {            this.ToEmailListString = toEmailListString;            this.CcEmailListString = ccEmailListString;            this.BccEmailListString = bccEmailListString;            this.Subject = subject;            this.IsBodyHtml = isBodyHtml;            this.EmailBody = emailBody;            this.AttachmentList = attachmentList;        }        #endregion        #region [ 发送邮件 ]        /// <summary>        /// 发送邮件        /// </summary>        /// <returns></returns>        public bool SendEmail()        {            try            {                MailMessage mm = new MailMessage(); //实例化一个邮件类                mm.Priority = MailPriority.Normal; //邮件的优先级,分为 Low, Normal, High,通常用 Normal即可                mm.From = new MailAddress(this.FromEmailAddress, "管理员", Encoding.GetEncoding("GB2312"));                //收件人                if (!string.IsNullOrEmpty(this.ToEmailListString))                {                    string[] toEmailArray = this.ToEmailListString.Split(new char[] { ';', ',', '|', ' ' }, StringSplitOptions.RemoveEmptyEntries);                    foreach (string toEmail in toEmailArray)                    {                        mm.To.Add(toEmail.Trim());                    }                }                //抄送人                if (!string.IsNullOrEmpty(this.CcEmailListString))                {                    string[] CcEmailArray = this.CcEmailListString.Split(new char[] { ';', ',', '|', ' ' }, StringSplitOptions.RemoveEmptyEntries);                    foreach (string ccEmail in CcEmailArray)                    {                        mm.CC.Add(ccEmail.Trim());                    }                }                //密送人                if (!string.IsNullOrEmpty(this.BccEmailListString))                {                    string[] BccEmailArray = this.BccEmailListString.Split(new char[] { ';', ',', '|', ' ' }, StringSplitOptions.RemoveEmptyEntries);                    foreach (string bccEmail in BccEmailArray)                    {                        mm.Bcc.Add(bccEmail.Trim());                    }                }                mm.Subject = this.Subject;                            //邮件标题                mm.SubjectEncoding = Encoding.GetEncoding("GB2312");  //这里非常重要,如果你的邮件标题包含中文,这里一定要指定,否则对方收到的极有可能是乱码。                mm.IsBodyHtml = this.IsBodyHtml;                      //邮件正文是否是HTML格式                mm.BodyEncoding = Encoding.GetEncoding("GB2312");     //邮件正文的编码, 设置不正确, 接收者会收到乱码                                mm.Body = this.EmailBody;                             //邮件正文                //邮件附件                if (this.AttachmentList != null && this.AttachmentList.Count > 0)                {                    foreach (Attachment attachment in this.AttachmentList)                    {                        mm.Attachments.Add(attachment);                    }                }                SmtpClient smtp = new SmtpClient();                 //实例化一个SmtpClient                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;   //将smtp的出站方式设为 Network                smtp.EnableSsl = false;                             //smtp服务器是否启用SSL加密                smtp.Host = this.SmtpHost;                          //指定 smtp 服务器地址                //smtp.Port = this.SmtpPort;                        //指定 smtp 服务器的端口,默认是25,如果采用默认端口,可省去                //smtp.UseDefaultCredentials = true;                //如果你的SMTP服务器不需要身份认证,则使用下面的方式,不过,目前基本没有不需要认证的了                smtp.Credentials = new NetworkCredential(this.FromEmailAddress, this.FormEmailPassword);    //如果需要认证,则用这种方式                //发送邮件,如果不返回异常, 则大功告成了。                smtp.Send(mm);                return true;            }            catch (Exception e)            {                return false;            }        }        #endregion    }}

controller中的方法

 public ActionResult Send(FormCollection collection)        {            var model = new QuanlityPushHistory();            string strzny = "";                   foreach (var i in collection["zny"])            {                strzny += i;            }            model.zny = strzny;            model.wzx = collection["wzx"];            model.zqx = collection["zqx"];            model.zlpf = collection["zlpf"];            model.yzx = collection["yzx"];            model.yxx = collection["yxx"];            model.wyx = collection["wyx"];            model.CreateTime = DateTime.Now;            string sendContent = "";            sendContent += "完整性:" + model.wzx;            sendContent += "准确性:" + model.zqx;            sendContent += "一致性:" + model.yzx;            sendContent += "有效性:" + model.yxx;            sendContent += "唯一性:" + model.wyx;            sendContent += "质量评分:" + model.zlpf;            sendContent += "数据质量生成时间:" + model.CreateTime;            this.SysTablesService.SaveQuanlityReport(model);            List<Attachment> list = new List<Attachment>();            Attachment att = new Attachment(Server.MapPath(ReportToExcel())); ;            list.Add(att);            EmailHelper eh = new EmailHelper(strzny, null, DateTime.Now + "数据质量报告", true, sendContent, list);            if (eh.SendEmail())            {                //return true;                return this.RefreshParent("邮件发送成功");            }            else            {                return this.RefreshParent("邮件发送失败");                //return false;            }        }

其中调用的发送邮件的方法是包含附件的方法,如下:
 /// <summary>        /// 构造函数        /// </summary>        /// <param name="toEmailListString">收件人列表字符串</param>        /// <param name="ccEmailListString">抄送人列表字符串</param>        /// <param name="subject">邮件标题</param>        /// <param name="isBodyHtml">邮件正文是否为Html格式</param>        /// <param name="emailBody">邮件正文</param>        /// <param name="attachmentList">附件列表</param>        public EmailHelper(string toEmailListString, string ccEmailListString, string subject, bool isBodyHtml, string emailBody, List<Attachment> attachmentList)        {            this.ToEmailListString = toEmailListString;            this.CcEmailListString = ccEmailListString;            this.Subject = subject;            this.IsBodyHtml = isBodyHtml;            this.EmailBody = emailBody;            this.AttachmentList = attachmentList;        }
生成附件的方法是返回一个路径,附件是一个生成的Excel文件 ,先生成保存在服务器 ,然后从服务器路径访问,并发送到邮件

 /// <summary>        /// 发送邮件附件        /// </summary>        /// <param name="request"></param>        /// <returns></returns>        public string ReportToExcel()        {            DataTable dt = new DataTable();            dt.Columns.Add("检核名称");            dt.Columns.Add("检核纬度");            dt.Columns.Add("阀值");            dt.Columns.Add("检核数");            dt.Columns.Add("不通过检核数");            dt.Columns.Add("质量评分");            dt.Columns.Add("检核时间");            QuanlityRequest re = new QuanlityRequest();            List<QuanlityReport> dataList = this.SysTablesService.GetQuanlityReport(re).ToList();            //List<SysTableColumns> dataList = this.SysTablesService.GetListByKeywordArray(request);//请写自己的获取List方法            foreach (var item in dataList)            {                DataRow dr = dt.NewRow();                dr["检核名称"] = item.jhmc;                dr["检核纬度"] = item.jhwd;                dr["阀值"] = item.fz;                dr["检核数"] = item.jhs;                dr["不通过检核数"] = item.btgjhs;                dr["质量评分"] = item.zlpf;                dr["检核时间"] = item.jhsj;                dt.Rows.Add(dr);            }            NPOIExcel npoiexel = new NPOIExcel();            string fileDir = DateTime.Now.ToString("yyyyMMdd");            // string fileName = "监测点数据_" + Guid.NewGuid().ToString("N") + ".xls";              string fileName = "数据质量报告_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls";            string destDir = Server.MapPath(@"/XlsTemp") + "\\" + fileDir + "\\";            if (!Directory.Exists(destDir))            {                Directory.CreateDirectory(destDir);            }            npoiexel.ToExcel(dt, "数据质量报告", "Sheet1", destDir + fileName);            return "/XlsTemp/" + fileDir + "/" + fileName;        }

在配置文件中设置好邮箱相关的参数webconfig文件的appSettings节点下:

   <!-- Smtp 服务器 -->    <add key="SmtpHost" value="smtp.163.com" />    <!-- Smtp 服务器端口 -->    <add key="SmtpPort" value="25" />    <!--发送者 Email 地址-->    <add key="FromEmailAddress" value="admin@163.com" />    <!--发送者 Email 密码,163邮箱中设置的秘钥。不是账号的登录密码-->    <add key="FormEmailPassword" value="123456" />    <add key="ToEmailListString" value="ttt@qq.com"/>    <add key="CcEmailListString" value="ttt@qq.com"/>    <add key="BccEmailListString" value="ttt@qq.com"/>
上面的ToEmailListString是接受者邮箱,CcEmailListString是抄送,BccEmailListString是密件抄送,可以在这里设置或者后台传递参数,可传多个接受者邮箱,以“,”、“;”等隔开均可


163邮箱设置:账户管理,找到客户端授权密码页面,点击开启,自己设置授权秘钥,也就是配置文件中的发送者的密码


然后前台调用发送邮件的方法,传入相关的参数就可以发送邮件了,点击测试:



原创粉丝点击