首页 > 解决方案 > 将 Selenium 图像读入字节数组并作为内联图像附件发送到电子邮件

问题描述

我想阅读网页截图并将其发送到 C# 中的电子邮件而不将其保存为文件。现在我的电子邮件正文只显示这条消息:“这是 WebDriver 服务器的初始起始页”,没有图像。显示图像的解决方案是什么?谢谢。

主要的:

 static void Main(string[] args)
    {

        //FOR IE
        InternetExplorerOptions options = new InternetExplorerOptions();
        options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
        IWebDriver driver = new InternetExplorerDriver(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), options);
        // end of IE driver
             driver.Navigate().GoToUrl("https://www.google.com");
            var screenshot = (driver as ITakesScreenshot).GetScreenshot();
           //send email
            SendEmail(screenshot.AsByteArray, "google", DateTime.Now);   
        driver.Close();
        driver.Quit();
    }

发送邮件方法

//write byte[] to email
        static void SendEmail(byte[] stream, string pageName, DateTime screenshotTime)
        {
            byte[] image = stream;

            Attachment att = new Attachment(new MemoryStream(stream), pageName);
            att.ContentDisposition.Inline = true;

            att.ContentId = Guid.NewGuid().ToString();
            att.ContentType.MediaType = "image/png";

            //send mail
            SmtpClient client = new SmtpClient(myMailServer);

            MailMessage mailMessage = new MailMessage();


            mailMessage.IsBodyHtml = true;

            mailMessage.From = new MailAddress(from);

            mailMessage.To.Add(new MailAddress(to));

            //send message

            mailMessage.Subject = "Website Screenshot";
            mailMessage.Body += "Website Name: " + pageName + Environment.NewLine + Environment.NewLine;
            mailMessage.Body += "Screenshot Time: " + screenshotTime + Environment.NewLine + Environment.NewLine;
            mailMessage.Body = String.Format( "<h3>Screenshot</h3>" + @"<img src=""cid:{0}"" />", att.ContentId);
            mailMessage.Attachments.Add(att);

            try
            {
                client.Send(mailMessage);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

标签: c#selenium-webdriver

解决方案


推荐阅读