向Email插入<Table>时出现赋值错误,如何修复?
修复邮件HTML拼接中的赋值错误
你遇到的这个编译错误,根源是字符串拼接时错误混用了赋值运算符。在C#里,+=是用来给变量追加内容的赋值操作,左边必须是一个可以被赋值的目标(比如变量、属性),但你把它直接写在了htmlBody = "..." + ... += "..."这种链式表达式里,编译器根本不知道该把值赋给谁,所以就报了"The left-hand side of an assignment must be a variable, property or indexer"这个错。
直接修复方案:用+串联所有字符串部分
把所有要拼接的HTML片段用+连接起来,不要混用=和+=,代码修改后如下:
MailMessage errorOutStanDev = new MailMessage(); errorOutStanDev.IsBodyHtml = true; SmtpClient SmtpServerThree = new SmtpClient("smtp.xxxx.xxx"); errorOutStanDev.From = new System.Net.Mail.MailAddress("PerformanceUpdate@xxx.xxx"); errorOutStanDev.To.Add(new System.Net.Mail.MailAddress("xxxxxx@xxxx.xxx")); string htmlBody = "<body>" + "<p><b> The following errors have occurred more often than others</b></p>" + avgErrorOutStDev + // 拼接预先生成的表格开头部分 "<tr>" + "<td>" + sitename + "</td>" + "<td>" + avg + "</td>" + "</tr>" + "</table>" + "</body>";
更清晰的分步拼接方式(推荐)
如果HTML内容比较长,分步用+=追加会更易读,也不容易出错:
MailMessage errorOutStanDev = new MailMessage(); errorOutStanDev.IsBodyHtml = true; SmtpClient SmtpServerThree = new SmtpClient("smtp.xxxx.xxx"); errorOutStanDev.From = new System.Net.Mail.MailAddress("PerformanceUpdate@xxx.xxx"); errorOutStanDev.To.Add(new System.Net.Mail.MailAddress("xxxxxx@xxxx.xxx")); string htmlBody = "<body>"; htmlBody += "<p><b> The following errors have occurred more often than others</b></p>"; htmlBody += avgErrorOutStDev; // 加入你之前生成的<table>起始部分 htmlBody += "<tr>"; htmlBody += "<td>" + sitename + "</td>"; htmlBody += "<td>" + avg + "</td>"; htmlBody += "</tr>"; htmlBody += "</table>"; htmlBody += "</body>";
额外注意点
要确保你的avgErrorOutStDev变量已经包含了<table>的起始标签(比如<table border="1">这类),否则最后加</table>会导致HTML结构不完整,邮件里的表格可能显示不正常。
内容的提问来源于stack exchange,提问作者Pens_Cup87
相关产品推荐
相关产品推荐

