在DataTable中向多个收件人发送电子邮件

问题描述 投票:1回答:1

我想将我的数据表中的所有电子邮件添加到我的电子邮件的收件人:我已经尝试了以下代码,但它在电子邮件地址中的每个字符后面添加了一个分号。如何重新编写此代码以便添加每个电子邮件地址?

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; 
  }
}
c# outlook office-interop
1个回答
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 <[email protected]>

可以使用oRecips.Add(emailAddress);简单地添加地址,而无需创建或解析Recipient对象。

© www.soinside.com 2019 - 2024. All rights reserved.