我想将数据表中的所有电子邮件都添加到电子邮件的“收件人:”中-我尝试了以下代码,但是它在电子邮件地址中的每个字符之后添加了分号。我该如何重写它以便添加每个电子邮件地址?
foreach (DataRow dr in datatatblefirst.Rows)
{
foreach (char eadd in r["Email"].ToString())
{
Outlook.Application oApp = new Outlook.Application();
Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
oMsg.HTMLBody = "Body";
oMsg.Subject = "Your Subject will go here.";
Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
foreach (char email in r["Email"].ToString())
oRecips.Add(eadd.ToString());
oMsg.Save();
oRecip = null;
oRecips = null;
oMsg = null;
oApp = null;
}
}
答案 0 :(得分:1)
您似乎正在遍历电子邮件地址中的每个char
。
如果r["Email"]
包含一个电子邮件地址,则可以在数据行上循环。以下代码将为每个电子邮件地址创建一封电子邮件:
foreach (DataRow dr in datatatblefirst.Rows)
{
Outlook.Application oApp = new Outlook.Application();
Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
oMsg.HTMLBody = "Body";
oMsg.Subject = "Your Subject will go here.";
Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
string emailAddress = r["Email"].ToString();
Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add(emailAddress);
oRecip.Resolve();
oMsg.Save();
//oMsg.Send();
oRecip = null;
oRecips = null;
oMsg = null;
oApp = null;
}
要仅创建一封电子邮件并发送到多个地址,请在foreach
之前创建电子邮件:
Outlook.Application oApp = new Outlook.Application();
Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
oMsg.HTMLBody = "Body";
oMsg.Subject = "Your Subject will go here.";
Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
foreach (DataRow dr in datatatblefirst.Rows)
{
string emailAddress = r["Email"].ToString();
Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add(emailAddress);
oRecip.Resolve();
}
oMsg.Save();
//oMsg.Send();
oRecips = null;
oMsg = null;
oApp = null;
不需要行oRecip.Resolve();
。如果通讯录中存在该联系人,则会将电子邮件地址的格式设置为Some Name <somename@email.com>
。
只需使用oRecips.Add(emailAddress);
即可添加地址,而无需创建或解析Recipient
对象。