C# 发送模板邮件并嵌入N张图片(优化) 以模版img标签为驱动

        public ServiceResult SendMail_imgTest(string toEmail)
        {
            var result = new ServiceResult()
            {
                Success = false,
                Message = ""
            };
            try
            {
                var smtp = new SmtpClient();
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtp.Host = mailServer;
                smtp.Port = port;
                smtp.EnableSsl = ssl;
                smtp.Credentials = new System.Net.NetworkCredential(mailUserName, mailPassword);
                NameValueCollection myCol = new NameValueCollection();
                string timeNow = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                CultureInfo cultureInfo = new CultureInfo("zh-CN");
                string DayOfWeek = cultureInfo.DateTimeFormat.GetAbbreviatedDayName(DateTime.Today.DayOfWeek);
                myCol.Add("TaskName", "测试图片邮件");
                myCol.Add("NowTime", timeNow);
                myCol.Add("DayOfWeek", getWeek(DateTime.Now));
                myCol.Add("TitleTime", DateTime.Now.ToString("yyyy年MM月dd日"));
                string mailBody = BulidByFile(Server.MapPath("/template/test.htm"), myCol);
                //替换img标签src属性  返回替换后html
                var str_html = RegexHtml(mailBody);
                //处理所有img标签
                var htmlBody = GetHtmlImageUrlList(mailBody, str_html);
                
                MailMessage msg = new MailMessage();
                // sender
                msg.From = new MailAddress("111@11.com.cn");
                msg.AlternateViews.Add(htmlBody);
                msg.To.Add(toEmail);

                // if error, smtp server will be send notification
                msg.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

                // subject 主题
                msg.Subject = "测试图片邮件";

                // subject encoding  编码
                msg.SubjectEncoding = Encoding.UTF8;

                // format is html
                msg.IsBodyHtml = true;

                // body encoding  
                msg.BodyEncoding = Encoding.UTF8;

                // body 
                msg.Body = str_html;
                smtp.Send(msg);
                result.Success = true;
                result.Message = str_html;
                return result;
            }
            catch (Exception e)
            {
                return result;
            }
        }

        public AlternateView GetHtmlImageUrlList(string sHtmlText, string str_html)
        {
            AlternateView htmlBody = AlternateView.CreateAlternateViewFromString(str_html, Encoding.UTF8, "text/html");
            Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r

\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);
            MatchCollection matches = regImg.Matches(sHtmlText);
            foreach (Match match in matches)
            {
                var src = match.Groups["imgUrl"].Value;
                if (!src.Contains("http://www"))//绝对路径图片不处理
                {
                    var fileName_index = src.LastIndexOf('/');
                    var cid = src.Substring(fileName_index + 1, src.Length - fileName_index - 5);
                    LinkedResource lrImage = new LinkedResource(Server.MapPath("template/" + src), "image/gif");
                    lrImage.ContentId = cid;
                    htmlBody.LinkedResources.Add(lrImage);
                }
            }
            return htmlBody;
        }

        /// <summary>
        /// 替换img标签的sec属性
        /// </summary>
        /// <param name="htmltext">html</param>
        /// <returns></returns>
        public string RegexHtml(string htmltext)
        {
            Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r

\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);
            MatchCollection matches = regImg.Matches(htmltext);
            foreach (Match match in matches)
            {
                var src = match.Groups["imgUrl"].Value;
                if (!src.Contains("http://spimg"))
                {
                    var fileName_index = src.LastIndexOf('/');
                    var cid = src.Substring(fileName_index + 1, src.Length - fileName_index - 5);
                    htmltext = Regex.Replace(htmltext, src, "cid:" + cid, RegexOptions.None);
                }
            }
            return htmltext;
        }

        public static string BulidByFile(string templatePath, NameValueCollection values)
        {
            return BulidByFile(templatePath, values, "[$", "]");
        }

        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;
        }

        public class ServiceResult
        {
            public bool Success { get; set; }
            public string Message { get; set; }
        }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>审核通过</title>
    <style>
        body, div, p, h1, ul, li, table, tr, td
        {
            margin: 0;
            padding: 0;
            border: none;
            list-style: none;
        }
        html, body
        {
            font-size: 12px;
            line-height: 24px;
            font-family: " 微软雅黑 " , " 宋体 " , " 黑体 " ,Arial, Helvetica, sans-serif;
        }
        a
        {
            font-size: 12px;
            font-weight: normal;
            text-decoration: none;
        }
    </style>
</head>
<body>
    <table border="0" cellspacing="0" cellpadding="0" width="520" bgcolor="#ededef" style="margin: 0px auto;">
        <tr>
            <td height="78" valign="middle" width="220" align="right">
                    <img border="0" alt="" src="mailimg/logo1.gif" />
            </td>
            <td width="300" align="right" valign="middle" style="font-family: 微软雅黑; color: #666666;
                font-size: 14px">
                <span style="color: #000; font-size: 16px">[$TitleTime] [$DayOfWeek] <!--模板替换标签-->     </span><br />
                [$city] [$temp1]~[$temp2] [$weather]        
            </td>
        </tr>
    </table>
    <table width="520" border="0" cellspacing="0" cellpadding="0" bgcolor="#FFFFFF" style="margin: 0px auto;">
        <tr>
            <td width="28" valign="top" bgcolor="#ededef">
                <img src="mailimg/mail_l_01.gif" width="28" height="343" />
            </td>
            <td width="43" valign="top" bgcolor="#FFFFFF">
                <img src="mailimg/mail_l_02.gif" width="43" height="343" />
            </td>
            <td width="378" valign="top" style="line-height: 24px; color: #6c6c6c; font-size: 12px;">
                
                
                
            </td>
            <td width="43" valign="top">
                <img src="mailimg/mail_r_01.gif" width="43" height="343" />
            </td>
            <td width="28" valign="top" bgcolor="#ededef">
                <img src="mailimg/mail_r_02.gif" width="28" height="343" />
            </td>
        </tr>
    </table>
</body>
</html>


此次优化放弃了xml配置部分  虽然配置也比较简单  但还是不理想
现在主要是用正则查找到img标签然后再替换src属性   页面有多少个img标签都不需要对程序进行修改  
希望还能再次优化  有什么意见和建议 希望大家能够提出来 大家一起进步 真心感谢..!!!




阅读更多
个人分类: C#
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭