使用带有图像的html模板发送电子邮件到gmail,交换

时间:2016-11-27 08:43:27

标签: c# asp.net html-email

我使用附加代码发送电子邮件和图片。它正在使用gmail。 现在,我想使用html模板发送到电子邮件。如何使用附加代码执行此操作?



private void SendEmail1()
        {
            string strMailContent = "Welcome new user";
            string fromAddress = "xxx";
            string toAddress = "xxx";
            string contentId = "image1";
            string path = Server.MapPath(@"Images/ml2.png"); // my logo is placed in images folder
            MailMessage mailMessage = new MailMessage(fromAddress, toAddress);
            mailMessage.Subject = "Welcome new User";

            LinkedResource logo = new LinkedResource(path,"image/png");
            logo.ContentId = "companylogo";
            // done HTML formatting in the next line to display my logo
            AlternateView av1 = AlternateView.CreateAlternateViewFromString("<html><body><img src=cid:companylogo/><br></body></html>" + strMailContent, null, "text/html");
            av1.LinkedResources.Add(logo);

            mailMessage.AlternateViews.Add(av1);
            mailMessage.IsBodyHtml = true;

                       
            SmtpClient smtp = new SmtpClient();
            smtp.Host = ConfigurationManager.AppSettings["Host"];
            smtp.UseDefaultCredentials = true;
            smtp.Port = int.Parse(ConfigurationManager.AppSettings["Port"]);


            smtp.Send(mailMessage);
        }
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

看起来你的html格式不正确

AlternateView av1 = AlternateView.CreateAlternateViewFromString("<html><body><img src=cid:companylogo/><br></body></html>" + strMailContent, null, "text/html");

应该是

AlternateView av1 = AlternateView.CreateAlternateViewFromString($"<html><body><img src=cid:companylogo/><br>{strMailContent}</body></html>", "text/html");

答案 1 :(得分:0)

看起来你的html格式不正确而且你传递的是null编码。

        AlternateView av1 = AlternateView.CreateAlternateViewFromString("<html><body><img src=cid:companylogo/><br></body></html>" + strMailContent, null, "text/html");

应该是

        AlternateView av1 = AlternateView.CreateAlternateViewFromString($"<html><body><img src=cid:companylogo/><br>{strMailContent}</body></html>", "text/html");