在DataTable中向多个收件人发送电子邮件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在DataTable中向多个收件人发送电子邮件相关的知识,希望对你有一定的参考价值。
我想将我的数据表中的所有电子邮件添加到我的电子邮件的收件人:我已经尝试了以下代码,但它在电子邮件地址中的每个字符后面添加了一个分号。如何重新编写此代码以便添加每个电子邮件地址?
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;
}
}
答案
看起来你正在迭代电子邮件地址中的每个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
对象。
以上是关于在DataTable中向多个收件人发送电子邮件的主要内容,如果未能解决你的问题,请参考以下文章
使用 Python smtplib 从 .txt 文件向多个收件人发送电子邮件