none
Email generated in c# won't embed images RRS feed

  • Question

  • I'm generating an email in c# and I want to have the body in html with embedded images.

    The images only show when I view the email on my iphone. They don't show in gmail or in outlook.

    Here is the code for the email. In gmail I get an attachment called "noname" with the image. In outlook I get nothing at all.

        public static void SendWelcomeEmail()
        {
            //Holds message information.
            using (var mailMessage = new System.Net.Mail.MailMessage())
            {
                //Add basic information.
                mailMessage.From = new System.Net.Mail.MailAddress("test2@test.com");
                mailMessage.To.Add("test@test.com");
                mailMessage.IsBodyHtml = true;
                mailMessage.Subject = "subject";
    
                //Create two views, one text, one HTML.
                var plainTextView = AlternateView.CreateAlternateViewFromString("body", null, "text/plain");
                var htmlView = AlternateView.CreateAlternateViewFromString(GenerateEmailHTML(), null, "text/html");
                //Add image to HTML version
                var imageResource = new LinkedResource(HttpContext.Current.Server.MapPath("../Images/logo.jpg"), MediaTypeNames.Image.Jpeg)
                    {
                        ContentId = "HDIImage"
                    };
                htmlView.LinkedResources.Add(imageResource);
                //Add two views to message.
                mailMessage.AlternateViews.Add(plainTextView);
                mailMessage.AlternateViews.Add(htmlView);
                //Send message
                var smtpClient = new SmtpClient()
                smtpClient.Send(mailMessage);
            }
        }
        private static string GenerateEmailHTML()
        {
            var htmlString = @"<html>
            <body>
            <div>
            <div>
            Hello World!  Thank you for registering with us today!
            </div>
            <image src='cid:HDIImage' alt='logo' />
            <span>more text</span>
            <br />
            <a href='http://www.google.com'>google</a>
            </div>
            </body></html>";
            return htmlString;
        }
    • Moved by Mike Feng Wednesday, May 22, 2013 9:02 AM
    Monday, May 20, 2013 4:03 PM

Answers