Friday, October 18, 2013

Send HTML confirmation email with image part

CreateMail function:
        

        private MailMessage CreateMail(EmailArchive emailArchive, bool useCCAddress, bool isBodyHtml)
        {
            MailMessage mailMsg = new MailMessage();

            // From
            MailAddress mailAddress = new MailAddress(emailArchive.FromAddress, emailArchive.FromName);
            mailMsg.From = mailAddress;

            // Subject and Body
            mailMsg.Subject = emailArchive.Subject;

            //mailMsg.Body = emailArchive.Body;
            EmbedImages(mailMsg, emailArchive.Body);

            mailMsg.IsBodyHtml = isBodyHtml;

            // To

            if (useCCAddress)
            {
                if (string.IsNullOrEmpty(emailArchive.CCAddress))
                    mailMsg = null;
                else
                    mailMsg.To.Add(new MailAddress(emailArchive.CCAddress, emailArchive.CCName));

            }
            else
            {
                mailMsg.To.Add(new MailAddress(emailArchive.ToAddress, emailArchive.ToName));
            }

            return mailMsg;
        }

The following pattern will match all img tag in the html source code:
string pattern = "<img.+?src=\"(.+?)\".+?/?>";
EmbedImages function:

        /// 
        /// The function only deal with src like "/image/file.jpg"
        /// 
        /// 
        /// 
        public static void EmbedImages(MailMessage mailMessage, string body)
        {
            // Check config file
            string path = ConfigurationManager.AppSettings["WebSiteRootFolder"];
            AlternateView av;
            if (string.IsNullOrEmpty(path))
            {
                ShopLogging.Warn("Can not find [WebSiteRootFolder] setting in config file!!!");

                //path = "D:\\User\\up\\";
                av = AlternateView.CreateAlternateViewFromString(string.Format("{0}", body), null, MediaTypeNames.Text.Html);
                mailMessage.AlternateViews.Add(av);

                return;
            }


            if (path.Right(1) == "\\")
                path = path.Left(path.Length - 1);

            List links = new List();
            LinkedResource res;
            string file, id, ext, cid;
            int i = 1;

            // Find all image tag
            // 
            string pattern = "";

            body = Regex.Replace(body, pattern, delegate(Match tag)
            {
                string v = tag.Value;
                file = tag.Groups[1].Value;

                // The function only deal with src like "/image/file.jpg"
                // If the src is not absolute path to "/", skip
                if (file.Left(1) != "/")
                    return v;

                // Replace virtual path to physical path
                file = file.Replace('/', '\\');
                ext = Path.GetExtension(file);
                if (ext.Left(1) == ".")
                    ext = ext.Substring(1);

                // Generate mail path ID
                id = Path.GetFileName(file);
                id = i.ToString() + "_" + id.UrlClean().Replace('.', '_');

                // Add root folder
                if (file.Left(1) == "\\")
                    file = file.Substring(1);
                file = path + "\\" + file;
                cid = string.Format("cid:{0}", id);

                // Add Linked Recource
                res = new LinkedResource(file, string.Format("image/{0}", ext));
                res.ContentId = id;
                links.Add(res);

                //body = body.Replace(tag.Groups[1].Value, string.Format("cid:{0}", id));
                i++;
                v = v.Replace(tag.Groups[1].Value, cid);
                return v;
            });

            av = AlternateView.CreateAlternateViewFromString(string.Format("{0}", body), null, MediaTypeNames.Text.Html);
            links.ForEach(l => av.LinkedResources.Add(l));
            mailMessage.AlternateViews.Add(av);

        }

No comments: