我编写了下面的程序来向该表中的演示用户发送 HTML 电子邮件:
我只想发送一封电子邮件并列出每个客户的所有信息。目前,如果客户有 10 本书逾期,那么根据表结构,客户将收到 10 封电子邮件,因为每笔图书借阅都是单独的记录。
例如:
亲爱的 Jim Carey: 以下书籍到期:
- 如何修理汽车
- 詹姆斯邦德回归
有没有一种方法可以让每个客户只发送一封电子邮件,但在电子邮件中列出每个项目。例如列出所有到期的书籍?
Fox 示例:使用上表发送一封电子邮件,Jim Carey 将收到 2 封电子邮件,而不是 1 封。我想只发送一封,但列出两本到期的书。
class Program
{
static DataSet dtProfile = Database.AcquireData();
static DataTable table = dtProfile.Tables[0];
static string CustFName;
static string CustLName;
static string CheckoutDate;
static string DueDate;
static string BookName;
public static void SendEmail()
{
foreach (DataRow row in table.Rows)
{
CustFName = row["CustFName"].ToString();
CustLName = row["CustLName"].ToString();
CheckoutDate = row["CheckoutDate"].ToString();
DueDate = row["DueDate"].ToString();
BookName = row["BookName"].ToString();
string body = PopulateBody(CustFName, CustLName, CheckoutDate, DueDate, BookName);<br />
SendHtmlFormattedEmail("Email", "Subject", body);
}
}
public static string PopulateBody(string custFName, string custLName,
string checkoutDate, string dueDate, string bookName)
{
string body = string.Empty;
using (StreamReader reader =
new StreamReader(Path.GetFullPath(@"Z:\folder\email.html")))
{
body = reader.ReadToEnd();
}
body = body.Replace("{#First Name#}", custFName);
body = body.Replace("{#Last Name#}", custLName);
body = body.Replace("{#Checkout Date#}", checkoutDate);
body = body.Replace("{#Due Date#}", dueDate);
body = body.Replace("{#Book Name#}", bookName);
return body;
}
public static void SendHtmlFormattedEmail(string recepientEmail, string subject, string body)
{
using (MailMessage mailMessage = new MailMessage())
{
mailMessage.From = new MailAddress(ConfigurationManager.AppSettings["UserName"]);
mailMessage.Subject = subject;
mailMessage.Body = body;
mailMessage.IsBodyHtml = true;
mailMessage.To.Add(new MailAddress(recepientEmail));
SmtpClient smtp = new SmtpClient();
smtp.Host = ConfigurationManager.AppSettings["Host"];
smtp.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]);
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = ConfigurationManager.AppSettings["UserName"];
NetworkCred.Password = ConfigurationManager.AppSettings["Password"];
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = int.Parse(ConfigurationManager.AppSettings["Port"]);
smtp.Send(mailMessage);
}
}
static void Main(string[] args)
{
SendEmail();
}
}