Surendra Sharma

Surendra Sharma

Search This Blog

Wednesday, June 5, 2013

Send email with image in Sitecore and C#

Send email with image

public static bool SendEmailWithImage(string mailTo, string mailFrom, string subject, string mailBody, bool isHtml) {
            bool response = false;
            string emailStatus = string.Empty;
            //string from = Convert.ToString(ConfigurationManager.AppSettings["EmailReminder.FromAddress"]);
            string to = mailTo;
            try {
                using (MailMessage mail = new MailMessage()) {
                    #region Mail setting
                    mail.From = new MailAddress(mailFrom, mailFrom);
                    mail.To.Add(new MailAddress(mailTo, mailTo));
                    mail.IsBodyHtml = isHtml;
                    mail.Subject = subject;
                    mail.Body = mailBody;
                    #endregion

                    EmbedCompanyLogo(mail);

                    Sitecore.MainUtil.SendMail(mail);
                }

                response = true;
            } catch (Exception ex) {
                Sitecore.Diagnostics.Log.Error(ex.Message + " : ", ex);
                response = false;
            }
            return response;

        }


        /// <summary> 
        /// Embeds the company logo into the given mail message 
        /// </summary> 
        /// <param name="message">Message in which the logo should be embedded</param> 
        public static void EmbedCompanyLogo(MailMessage message) {
            AlternateView av1 = AlternateView.CreateAlternateViewFromString(message.Body, null, System.Net.Mime.MediaTypeNames.Text.Html);
            string strImageUrl = System.Web.HttpContext.Current.Server.MapPath("~/Images/dealer/logo_menu.jpg");
            LinkedResource logo = new LinkedResource(strImageUrl, System.Net.Mime.MediaTypeNames.Image.Jpeg);
            logo.ContentId = "logo_menu";
            //To refer to this image in the html body, use <img src="cid:companylogo"/> 
            av1.LinkedResources.Add(logo);
            message.AlternateViews.Add(av1);

        }

No comments:

Post a Comment