Embed images in email by dynamic template

In general .net mail sending we are using image as url but this is not good if image is delete from server and path as been changed then our email comes with image not found.
So to avoid this we can embed image with email and then create cid and that cid we can use anywhere in email by image tag.

But if we have used email template and used images on that template then how can we handle, by generic class.
So for solution of this is that we can create add predefine image tags in email template and that will be passed by image class as below.

public class EmbedImages
    {
        public EmbedImages(string _ImagePlaceHolde, string _ImagePath, string _width, string _height)
        {
            this.ImagePlaceHolde = _ImagePlaceHolde;
            this.ImagePath = _ImagePath;
            this.width = _width;
            this.height = _height;
        }
        public string ImagePlaceHolde { get; set; }
        public string ImagePath { get; set; }
        public string width { get; set; }
        public string height { get; set; }
    }

This List of object of “EmbedImages” will be used in email send mail class where we are fetching the value and preparing image tag and replacing.

Actually we need to put any of the placeholder in email template and that will be replace by image tag.
As per below logic by embedding images.

 if (this.ImageParamers != null && this.ImageParamers.Count > 0)
 {
                    AlternateView View;
                    LinkedResource resource;
                    View = AlternateView.CreateAlternateViewFromString(message.Body, null, "text/html");
                    foreach (EmbedImages item in this.ImageParamers)
                    {
                        resource = new LinkedResource(item.ImagePath);
                        resource.ContentId = item.ImagePlaceHolde;
                        View.LinkedResources.Add(resource);
                        string ImageTag = "<img src=cid:" + item.ImagePlaceHolde + "width='" + item.width + "' and height='" + item.height + "px'/></p>";
                        message.Body = message.Body.Replace(item.ImagePlaceHolde, ImageTag);
                    }                    
                    message.AlternateViews.Add(View);
  }

We can actually fit this login in our common class for send an email with all other facilities.

public class SentMail
    {
        public SentMail()
        {

        }
        private string _SMTPAddress;
        public string SMTPAddress 
        {
            get
            {
                if(string.IsNullOrEmpty(_SMTPAddress))
                    return ConfigurationManager.AppSettings["SMTPSERVER"].ToString();
                else
                    return _SMTPAddress;
            }
            set
            {
                _SMTPAddress = value;
            }
        }
        public bool isMailSent {get;set;}
        private string _FromDisplayName;
        public string FromDisplayName
        {
            get
            {
                if (string.IsNullOrEmpty(_FromDisplayName))
                    return ConfigurationManager.AppSettings["FROMDISPLAY"].ToString();
                else
                    return _FromDisplayName;
            }
            set
            {
                _FromDisplayName = value;
            }
        }
        private string _FromAddress;
        public string FromAddress
        {
            get
            {
                if (string.IsNullOrEmpty(_FromAddress))
                    return ConfigurationManager.AppSettings["FROMADDRESS"].ToString();
                else
                    return _FromAddress;
            }
            set
            {
                _FromAddress = value;
            }
        }
        /// <summary>
        /// To Address if multiple then add ; in between each address
        /// </summary>
        public string ToDisplayName { get; set; }
        public string ToAddress { get; set; }
        /// <summary>
        /// CC Address if multiple then add ; in between each address
        /// </summary>
        public string CCAddress { get; set; }
        /// <summary>
        /// BCC Address if multiple then add ; in between each address
        /// </summary>
        public string BCCAddress { get; set; }
        public string Body { get; set; }
        public string Subject { get; set; }
        public List<string> SubjectParameter { get; set; }
        public List<string> Attachment { get; set; }
        public bool HighPriority { get; set; }
        public List<string> DynamicParameter { get; set; }
        public string TemplateFile { get; set; }
        public List ImageParamers { get; set; }

        public bool Sent()
        {
            bool bReturn = true;
            try
            {
                string user = System.Configuration.ConfigurationManager.AppSettings["SMTP_USERNAME"];
                string pass = System.Configuration.ConfigurationManager.AppSettings["SMTP_PASSWORD"];

                SmtpClient oSMTLClient = new SmtpClient();
                oSMTLClient.Host = this.SMTPAddress;
                
                oSMTLClient.Port = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SMTP_PORT"]);
                oSMTLClient.UseDefaultCredentials = false;
                oSMTLClient.Credentials = new System.Net.NetworkCredential(user, pass);
                oSMTLClient.DeliveryMethod = SmtpDeliveryMethod.Network;


                MailMessage message = new MailMessage();
                message.From = new MailAddress(this.FromAddress, this.FromDisplayName);
                if (!string.IsNullOrEmpty(this.ToAddress))
                {
                    string[] ToAddress = this.ToAddress.Trim().Split(";".ToCharArray());
                    foreach (string itemTo in ToAddress)
                    {
                        message.To.Add(itemTo);
                    }
                }
                // CC address
                if (!string.IsNullOrEmpty(this.CCAddress))
                {
                    string[] CCAddress = this.CCAddress.Trim().Split(";".ToCharArray());
                    foreach (string itemCC in CCAddress)
                    {
                        message.CC.Add(itemCC);
                    }
                }
                
                // BCC address
                if (!string.IsNullOrEmpty(this.BCCAddress))
                {
                    string[] BCCAddress = this.BCCAddress.Trim().Split(";".ToCharArray());
                    foreach (string itemBCC in BCCAddress)
                    {
                        message.Bcc.Add(itemBCC);
                    }
                }

                if (this.DynamicParameter != null && DynamicParameter.Count > 0)
                    message.Body = string.Format(this.MailBodystring(), this.DynamicParameter.ToArray());
                else
                    message.Body = this.MailBodystring();
                
                
                message.IsBodyHtml=true;
                if (this.HighPriority)
                {
                    message.Priority = MailPriority.High;
                }

                if (this.Attachment != null && this.Attachment.Count > 0)
                {
                    
                    foreach (string itemAttachFile in this.Attachment)
	                {
                        System.Net.Mail.Attachment oAttachment = new Attachment(itemAttachFile);
                        message.Attachments.Add(oAttachment);
	                }

                    
                }
                if (this.SubjectParameter != null && SubjectParameter.Count > 0)
                    message.Subject = string.Format(this.Subject, this.SubjectParameter.ToArray());
                else
                    message.Subject = this.Subject;
                //oSMTLClient.SendCompleted += SendCompletedCallback;
                if (this.ImageParamers != null && this.ImageParamers.Count > 0)
                {
                    AlternateView View;
                    LinkedResource resource;
                    View = AlternateView.CreateAlternateViewFromString(message.Body, null, "text/html");
                    foreach (EmbedImages item in this.ImageParamers)
                    {
                        resource = new LinkedResource(item.ImagePath);
                        resource.ContentId = item.ImagePlaceHolde;
                        View.LinkedResources.Add(resource);
                        string ImageTag = "<img src=cid:" + item.ImagePlaceHolde + "width='" + item.width + "' and height='" + item.height + "px'/></p>";
                        message.Body = message.Body.Replace(item.ImagePlaceHolde, ImageTag);
                    }                    
                    message.AlternateViews.Add(View);
                }


                
                var userState = message;
                oSMTLClient.Send(message);

                bReturn = true;
            }
            catch (Exception ex)
            {
                bReturn = false;
            }

            return bReturn;
           
            //message.CC = this.CCAddress

        }
        private void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
        {
            this.isMailSent=true;
        }
        private string MailBodystring()
        {
            string MailBody = "";
            if (File.Exists(this.TemplateFile))
            {
                StreamReader SR = new StreamReader(this.TemplateFile);
                MailBody = SR.ReadToEnd();
                SR.Close();
                SR.Dispose();
            }
            return MailBody;
        }
    }

So now when we want to use this class we use by below way.


 SentMail oMail = new SentMail();
            oMail.DynamicParameter = new List<string> { "Amit", "Password" };

            oMail.HighPriority = false;
            oMail.ToAddress = "amitpatel.it@gmail.com";
            oMail.Subject = "Password change";

            oMail.TemplateFile = System.Web.HttpContext.Current.Server.MapPath("~/EmailTemplate/ChangePassord.htm");
	    List lstImage = new List()
	    lstImage.add("ComapnyLogo","<path>","100","50") // for dynamic apporach we can fetch this details from database and ser can attach each placeholder in email template by any WYSWYG editor.
	    oMail.ImageParamers = lstImage
            
            oMail.Sent();

So in this way we can send an email with dynamically embed images.

Please feel free to contact me for any other assistance at amitpatel.it@gmail.com

Thanks,
“Enjoy Programming”
amitpatel.it@gmail.com

About these ads

About amitpatelit
Having more than 9 years of experience in IT industry. - Strong knowledge and experience on various technologies and tools like ASP.NET, MVC, Entity framework, Razor,VB.NET, C#, WCF,WPF, MVC, Silver light, ASP, XML ,Java Script, HTML, CSS, AJAX, COM/DCOM,MS SQL Server, Enterprise Library, MSMQ, SQL Server Reporting Service, Crystal Reports. - Achieved 7800 points (Star level) in the official Microsoft ASP.NET forum. - MCPD and MCTS in Web, Window and distributed application.

2 Responses to Embed images in email by dynamic template

  1. Nilesh says:

    good one mate
    its helpful

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 239 other followers

%d bloggers like this: