C# 通过Cef.CefSharp实现网页截图,并发送邮件
1、需求与目的
需实现效果为,将一个网页内容截图保存文件,最后通过邮件发送
2、界面实现
private void button1_Click(object sender, EventArgs e) { var to = "";//接收人邮箱 var bodyUrl = "";//需要截图的网页地址 //图片保存路径 string destPath = "C:\\Users\\lwk123456\\Desktop\\图片\\"; //生成图片名称 var subject = "截图生成图片" + DateTime.Today.ToString("yyyy-MM-dd"); string imageName = $"{subject}.jpeg"; string extName = Path.GetExtension(imageName).ToLower(); WebScreenshot screenshot = new WebScreenshot(); screenshot.createImg(bodyUrl, destPath, imageName, 895, 3800); //由于需要通过邮件发送所以这里将图片转base64,方便加载 //或者也可直接转为网络路径 var picByte = screenshot.PictureTurnByte(Path.Combine(destPath, imageName)); var picByteStr = Convert.ToBase64String(picByte); //邮件发送内容主体 var body = $"<img src='data:image/{extName};base64,{picByteStr}' alt='{subject}' />"; bool res = sendEmail.Send(to, "", subject, body, false); MessageBox.Show($"截图成功,图片路径:{Path.Combine(destPath, imageName)}"); }
3、截图具体实现
/// <summary> /// 网页截图帮助类 /// </summary> public class WebScreenshot { /// <summary> /// 生成图片 /// </summary> /// <param name="url"></param> /// <param name="destPath"></param> /// <param name="imageName"></param> /// <param name="width"></param> /// <param name="height"></param> public void createImg(string url, string destPath, string imageName, int width = 0, int height = 0) { AsyncContext.Run(async delegate { try { if (!Directory.Exists(destPath)) { Directory.CreateDirectory(destPath); } //加载CefSharp var cefSharplog = Path.Combine(Environment.CurrentDirectory, "CefSharp\\Cache"); var settings = new CefSettings() { //默认情况下,CefSharp将使用内存缓存,您需要指定缓存文件夹来持久化数据 CachePath = cefSharplog }; //执行依赖项检查以确保所有相关资源都在我们的输出目录中。 var success = await Cef.InitializeAsync(settings, performDependencyCheck: true, browserProcessHandler: null); if (!success) { throw new Exception("无法初始化CEF,请检查日志文件."); } // 创建ChromiumWebBrowser实例 using (var browser = new ChromiumWebBrowser(url)) { if (height > 0 && width > 0) { Size size = new Size(width, height); browser.Size = size; } var initialLoadResponse = await browser.WaitForInitialLoadAsync(); if (!initialLoadResponse.Success) { throw new Exception($"页面加载失败,错误代码为:{initialLoadResponse.ErrorCode}, HttpStatusCode:{initialLoadResponse.HttpStatusCode}"); } //等待浏览器渲染 await Task.Delay(500); // 截屏 var bitmapAsByteArray = await browser.CaptureScreenshotAsync(); if (!Directory.Exists(destPath)) { Directory.CreateDirectory(destPath); } // 要保存屏幕截图的文件路径 var screenshotPath = Path.Combine(destPath, imageName); File.WriteAllBytes(screenshotPath, bitmapAsByteArray); } //关闭cef if (!Cef.IsShutdown) { Cef.Shutdown(); } } catch (Exception e) { //关闭cef if (!Cef.IsShutdown) { Cef.Shutdown(); } } }); } //图片转base64 public byte[] PictureTurnByte(string url) { //图片转二进制流 FileStream stream = new FileStream(url, FileMode.OpenOrCreate, FileAccess.ReadWrite); BinaryReader binaryReader = new BinaryReader(stream); binaryReader.BaseStream.Seek(0, SeekOrigin.Begin); byte[] bytes = binaryReader.ReadBytes(Convert.ToInt32(stream.Length.ToString())); binaryReader.Close(); return bytes; } }
4、发送邮件帮助类
/// <summary> /// 发送邮件帮助类 /// </summary> public class sendEmail { /// <summary> /// 发送邮件 /// </summary> /// <param name="tos">收件人</param> /// <param name="cc">抄送人</param> /// <param name="subject">标题</param> /// <param name="body">内容</param> /// <returns></returns> public static bool Send(string tos, string cc, string subject, string body, bool isEnableSsl = false) { try { System.Configuration.AppSettingsReader appSetting = new System.Configuration.AppSettingsReader(); ///smtp服务器 string mailDomain = "smtp.exmail.qq.com"; //发送端口 int mailPort = 25; //发件人账号 string mailFrom = ""; //密码 string mailPassword =""; MailMessage message = new MailMessage() { SubjectEncoding = Encoding.UTF8, BodyEncoding = Encoding.UTF8, //设置发件人地址姓名 From = new MailAddress(mailFrom, mailFrom, Encoding.UTF8), }; //收件人 string[] mailToList = tos.Split(';'); List<string> mailList = new List<string>(); for (int i = 0; i < mailToList.Length; i++) { if (mailToList[i].Length > 0) { message.To.Add(new MailAddress(mailToList[i], mailToList[i], Encoding.UTF8)); } } //抄送人 if (!string.IsNullOrEmpty(cc)) { string[] mailToCCList = cc.Split(';'); for (int i = 0; i < mailToCCList.Length; i++) { if (mailToCCList[i].Length > 0) { message.CC.Add(new MailAddress(mailToCCList[i], mailToCCList[i], Encoding.UTF8)); } } } message.IsBodyHtml = true;//邮件内容是否为html message.Subject = subject; message.Priority = MailPriority.High; message.Body = body; SmtpClient smtp = new SmtpClient(mailDomain, mailPort) { Timeout = 60000, UseDefaultCredentials = true, EnableSsl = isEnableSsl, //设置发件人用户密码 Credentials = new System.Net.NetworkCredential(mailFrom, mailPassword), DeliveryMethod = SmtpDeliveryMethod.Network }; smtp.Send(message); return true; } catch (Exception ex) { return false; throw ex; } }}
5、具体效果
本文来自博客园,作者:流纹,转载请注明原文链接:https://www.cnblogs.com/lwk9527/p/17373984.html