C#实现邮件添加HTML附件及Excel对应图片附件报错求助
解决C#邮件发送程序中“Illegal characters in path”附件错误
嘿,我瞅了你的代码,一眼就揪出导致「Illegal characters in path」错误的原因啦——你把邮件的HTML正文(body变量)直接传给了Attachment的构造函数!Attachment需要的是合法的文件路径或者文件流,而HTML正文里满是<>、{}这类文件路径里不允许的字符,不出错才怪呢。
另外,你本来是想把生成的二维码图片(路径存在image变量里)作为附件,那咱们一步步修正代码:
第一步:修正附件创建逻辑
把错误的附件创建代码替换成用图片路径生成附件:
// 原来错误的代码 // Attachment attachFile = new Attachment(body); // 替换成下面的正确代码 Attachment attachFile = new Attachment(image);
第二步:完善资源释放(避免内存泄漏)
你的StreamReader用完没释放资源,最好用using语句自动处理:
string body = ""; using (StreamReader reader = new StreamReader("HTMLPage1.html")) { string readfile = reader.ReadToEnd(); body = readfile; } // 后续替换模板变量的代码不变 body = body.Replace("{USERNAME}", mailname); body = body.Replace("{EMAILID}", mailemail); body = body.Replace("{CODE}", Code_new); // 这里你原来写的QRCode应该是笔误,改成Code_new吧? body = body.Replace("{IMAGE}", image);
第三步:额外的避坑建议
- 检查图片路径合法性:虽然你替换了制表符,但
Code_new里可能还有其他文件路径非法字符(比如/ \ : * ? " < > |),可以加个过滤逻辑:// 移除所有文件路径非法字符 string invalidChars = new string(Path.GetInvalidFileNameChars()); foreach (char c in invalidChars) { Code_new = Code_new.Replace(c.ToString(), ""); } - 验证文件是否存在:在创建附件前先检查图片文件是否存在,避免找不到文件的错误:
if (File.Exists(image)) { Attachment attachFile = new Attachment(image); Msg.Attachments.Add(attachFile); } else { Console.WriteLine($"警告:图片 {image} 不存在,跳过附件添加"); } - Gmail SMTP注意事项:现在Gmail默认禁用普通密码登录SMTP,你需要开启「两步验证」并创建应用专用密码来替代代码里的普通密码,否则会登录失败。
修正后的完整核心代码片段
DataTable dtValues = SQLHelper.ExecuteDataset("Stored Procedure").Tables[2]; if (dtValues.Rows.Count > 0) System.Console.Clear(); foreach (DataRow row in dtValues.Rows) { string mailname = Convert.ToString(row["row1"]); string mailemail = Convert.ToString(row["row2"]); string Code = Convert.ToString(row["row3"]); string Code_new = Code.Replace("\t", ""); // 过滤文件名非法字符 string invalidChars = new string(Path.GetInvalidFileNameChars()); foreach (char c in invalidChars) { Code_new = Code_new.Replace(c.ToString(), ""); } string Id = Convert.ToString(row["row4"]); string str = AppDomain.CurrentDomain.BaseDirectory; string image = Path.Combine(str, "Codes", $"{Code_new}.jpg"); // 用Path.Combine更安全,避免路径拼接错误 string body = ""; using (StreamReader reader = new StreamReader("HTMLPage1.html")) { string readfile = reader.ReadToEnd(); body = readfile; } body = body.Replace("{USERNAME}", mailname); body = body.Replace("{EMAILID}", mailemail); body = body.Replace("{CODE}", Code_new); body = body.Replace("{IMAGE}", image); MailMessage Msg = new MailMessage(); Msg.From = new MailAddress("xxx@gmail.com"); Msg.To.Add(mailemail); Console.WriteLine(Id + " : " + mailemail); Msg.Subject = "QR Code"; Msg.Body = body; // 把替换后的HTML正文设为邮件内容 Msg.IsBodyHtml = true; // 确保开启HTML模式 // 添加附件(先检查文件是否存在) if (File.Exists(image)) { Attachment attachFile = new Attachment(image); Msg.Attachments.Add(attachFile); } else { Console.WriteLine($"ID {Id}: 图片文件 {image} 不存在,未添加附件"); } SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com"); SmtpServer.Port = 587; SmtpServer.EnableSsl = true; SmtpServer.UseDefaultCredentials = false; // 注意:这里要用Gmail应用专用密码,不是普通密码 SmtpServer.Credentials = new System.Net.NetworkCredential("xxx2694@gmail.com", "你的应用专用密码"); try { SmtpServer.Send(Msg); Console.WriteLine($"ID {Id}: 邮件发送成功"); } catch (Exception ex) { Console.WriteLine($"ID {Id}: 邮件发送失败,错误信息:{ex.Message}"); } finally { // 释放MailMessage资源 Msg.Dispose(); } }
内容的提问来源于stack exchange,提问作者LINCY VARKEY
相关产品推荐
相关产品推荐

