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

Get Date & Time based on time zone in SQL Server

Problem:
SQL server is running in another time zone and application is launching for different time zone, like SQL server is established in USA, and Application is lunched for Indian user so we need to maintain all data in Indian times only. So all current date and time consider Indian time rather then consider USA time zone.
Also in some case SQL server moved to USA to Canada then also system is always consider proper Indian time. Or based on user’s demanded time zone’s time.

Also in some case SQL server moved to USA to Canada then also system is always consider proper Indian time. Or based on user’s demanded time zone’s time.

Solution:
So below are the sql function for that.

GO
/****** Object:  UserDefinedFunction [dbo].[GetLocalDateTime]    Script Date: 02/10/2012 15:16:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Created By : Amit Patel
Created Date : 11-Feb-2012
*/
------------------------------How to Executes--------------------------------------------------
-- select [dbo].[TimeZoneWiseTime](+5)
CREATE FUNCTION [dbo].[GetDateTimeByTimeZone]
(
	@TimeZoneDiff decimal(4,2)
)
RETURNS datetime
AS
BEGIN
	declare @utcdiff decimal(5,2)
set @utcdiff =  datediff(hh,GetUtcDate(), getdate())
declare @currDate datetime
set @currDate = DATEADD(Hour,@utcdiff,getdate())

return DATEADD(Hour,-(@TimeZoneDiff),@currDate )
END

In this example I have give example of select [dbo].[TimeZoneWiseTime](+5)
to consider Indian standard time (IST) as +5. So we can set it to take any country’s time.

In above logic I am first considering GetUtcDate() to get central time and based on that find difference of server’s date with central time, and finally after all I am adding uses requested timezone’s hours.

Let me know if you have any questions or feedback on this.

Thanks,
Amit Patel
Enjoy Programing

Follow

Get every new post delivered to your Inbox.

Join 239 other followers