格式化电子邮件正文 HTML
我将如何使正文使用 HTML 格式.我需要添加什么以及需要添加哪一行?我试过 MailMessage.IsBodyHtml = true;但这对我不起作用.这是这样做的方法吗?该代码应该替换另一行还是应该单独一行?
How would I go about making the body work with HTML format. what do I need to add and what line would I need to add it? I have tried MailMessage.IsBodyHtml = true; but that did not work for me. Is this the way to do it? should that code be replacing another line or should it be on a line on its own?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Office.Interop;
using Microsoft.Office.Interop.Excel;
using System.Net;
using System.Net.Mail;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
const string subject = "ASSET RECOVERY";
listBox1.Items.Clear();
//1. Replace the password
var fromAddress = new MailAddress("", ""); //Email address then Name
const string fromPassword = ""; //Email Password
string body = "";
//2. Potentially replace any of the Host / Port combo if necessary
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
string path = "C:\\Users\\adrian.simonis\\Desktop\\VPN\\AdriansExcel3.xlsx ";
//3. Replace the above with the actual path that your excel file is.
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Workbook wb = excel.Workbooks.Open(path);
Worksheet excelSheet = wb.ActiveSheet;
int rows = excelSheet.Rows.Count;
int successfulSends = 0;
for (int i = 1; i < rows; i++)
{
string mySendAddress = "";
string myAsset = "";
try
{
body = <font size = "20" color = "red" style = "text-align:center;" > "ATTENTION\n\n" </ font >< br > +
"Company is collecting underutilized PCs and other surplus computing equipment. Retiring computers reduces a variety of annual costs, including corporate allocations, maintenance, licensing fees and labor associated with information protection and system patching.\n\n" +
"The following criteria is used to determine an underutilized device:\n\n" +
"Use Login Times and Keyboard / Mouse Activity, Load Average, CPU Utilization, Physical Memory Utilization, Software Usage, Disk Utilization\n\n" +
"All of these factors are viewed over time scales: one week, four weeks and 16 weeks to determine if this asset falls under a low usage threshold\n\n" +
"In order to support Aero IT Asset Reduction initiatives, this asset (ASSET TAG HERE) has been identified as underutilized and will be removed on.\n\n" +
"1 - 28 - 20\n\n" +
"If there is a critical business need to leave this device in place, please send an email justification to keep the asset to the following public folder\n\n" +
" | Sr.Desktop Technician\n\n" +
"CompanyAsset Recovery Support\n\n" +
"Email: \n\n" +
"Office: \n\n";
myAsset = excelSheet.Cells[i, 19].Value.ToString();
mySendAddress = excelSheet.Cells[i, 22].Value.ToString();
body = body.Replace("(ASSET TAG HERE)", myAsset); //his assetAssetTag1 ha
label2.Text = "Sending email to: " + mySendAddress + " with asset tag: " + myAsset;
}
catch
{
System.Threading.Thread.Sleep(3000);
label2.Text = "Finished: reached empty excel cell with no send to address";
break;
}
//Send email here!
var toAddress = new MailAddress(mySendAddress);
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
try
{
smtp.Send(message);
listBox2.Items.Add(toAddress);
}
catch (ArgumentOutOfRangeException ex)
{
listBox1.Items.Add(toAddress);
}
}
successfulSends++;
label1.Text = "Successful emails: " + successfulSends;
System.Threading.Thread.Sleep(3000);
}
wb.Close();
}
}
}
因此,在将其转换为 HTML 后,其发送绿色.
So, after getting it to HTML its sending green.
"<html><font size = 20, color = red, style =text - align:center;>ATTENTION </ font >\n\n" +
"<html><font size = 10>Company is collecting underutilized PCs and other surplus computing equipment. Retiring computers reduces a variety of annual costs, including corporate allocations, maintenance, licensing fees and labor associated with information protection and system patching.</ font >\n\n" +
"The following criteria is used to determine an underutilized device:\n\n" +
"Use Login Times and Keyboard / Mouse Activity, Load Average, CPU Utilization, Physical Memory Utilization, Software Usage, Disk Utilization\n\n" +
"All of these factors are viewed over time scales: one week, four weeks and 16 weeks to determine if this asset falls under a low usage threshold\n\n" +
"In order to support Aero IT Asset Reduction initiatives, this asset (ASSET TAG HERE) has been identified as underutilized and will be removed on.\n\n" +
"1 - 28 - 20\n\n" +
"If there is a critical business need to leave this device in place, please send an email justification to keep the asset to the following public folder\n\n" +
"| Sr.Desktop Technician\n\n" +
"CompanyAsset Recovery Support\n\n" +
"Email:\n\n" +
"Office: phone\n\n</html>";
您正在创建的 HTML 文档无效.例如.您正在打开两个标签,但永远不要关闭它们.此外,据我所知,您的内联样式无效(除非我在这里遗漏了某些东西).
The HTML document you are creating isn't valid. E.g. you are opening two tags, but never close them. Also as far as I can tell your inline-styles aren't valid (unless there is something I am missing here).
当您尝试运行程序时,这一行看起来也应该抛出错误:
This line also looks like it should throw an error, when you are trying to run the program:
body = <font size = "20" color = "red" style = "text-align:center;" > "ATTENTION\n\n" </ font >< br > +
不是使用容易出错且经常导致缺少结束标记和其他问题的字符串连接,我有时使用的一个简单解决方案是设置由占位符填充的有效 HTML 模板(例如在资源文件中):
Instead of using string concatenation which is error prone and often leads to missing closing tags and other issues, an easy solution I sometimes use is to set up a valid HTML-template (e.g. in a resource file) that is populated by placeholders:
<!DOCTYPE html>
<html>
<head>
<style>
.attention {
text-align: center;
font-size: 20px;
color: red;
}
.content {{
color: black;
font-size: 10px;
}}
</style>
</head>
<body>
<p class="attention">[PLACEHOLDER_TITLE]</p>
<p class="content">[PLACEHOLDER_CONTENT]</p>
<ol>
<li>[PLACEHOLDER_LIST_ITEM_1]</li>
<li>[PLACEHOLDER_LIST_ITEM_2]</li>
<li>[PLACEHOLDER_LIST_ITEM_3]</li>
</ol>
</body>
</html>
这些之后可以很容易地用实际内容替换,使代码更易于阅读:
These can then easily be replaced with the actual content later on and make the code much easier to read:
string body = (String)GetLocalResourceObject("EmailTemplate");
body.Replace("[PLACEHOLDER_TITLE]", title);
body.Replace("[PLACEHOLDER_CONTENT]", content);
...
需要明确的是:在您的实际应用程序中,您必须确保所有字符都被正确转义(在模板和您插入的替换字符串中).
Just to be clear: In your actual application you have to make sure that all characters are correctly escaped (in both the template and the replacement strings you are inserting into it).