你好,
我正在尝试开发一个 wpf 应用程序,用于使用 Microsoft Outlook 应用程序发送批量电子邮件。我正在使用一个 datagridview,从中提取 to、cc 和附件。此外,对于每封邮件,将有多个 to(s) 和 cc(s)。如果 to 和/或 cc 字段包含单个邮件地址,它可以工作。但是当添加多个 to 或 cc 时,会出现以下错误。
System.Runtime.InteropServices.COMException: 'Outlook 无法识别一个或多个名称。'
我认为这是邮件分离的问题,并付出了一些努力来解决它。
这是发送邮件的代码。
private void BtnSendMail_Click(object sender, RoutedEventArgs e)
{
foreach (DataRowView rows in dgdData.ItemsSource)
{
try
{
Outlook.Application oApp = new Outlook.Application();
Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
Outlook.Recipients oRecips = oMsg.Recipients;
List<string> sTORecipsList = new List<string>();
List<string> sCCRecipsList = new List<string>();
var to = rows.Row.ItemArray[1].ToString();
var cc = rows.Row.ItemArray[2].ToString();
var attachment = rows.Row.ItemArray[3].ToString();
//var status = rows.Row.ItemArray[0] ="Sending";
if (to.Contains(",") || to.Contains(";") || to.Contains(" "))
{
string[] tos = Regex.Split(to, ",; ");
// string[] lines = Regex.Split(value, "\r\n");
for (int i = 0; i < tos.Length; i++)
{
//mail.To.Add(new MailAddress(tos[i]));
sTORecipsList.Add(tos[i]);
}
}
else
{
sTORecipsList.Add(to);
}
if (cc.Contains(",") || cc.Contains(";") || cc.Contains(" "))
{
string[] ccs = Regex.Split(cc, ",; ");
// string[] lines = Regex.Split(value, "\r\n");
for (int i = 0; i < ccs.Length; i++)
{
//mail.To.Add(new MailAddress(tos[i]));
sCCRecipsList.Add(ccs[i]);
}
}
else
{
sCCRecipsList.Add(cc);
}
oMsg.Body = "Sample Text";///rtbBody.Text.ToString();
string sDisplayName = "MyAttachment";
int iPosition = oMsg.Body.Length + 1;
int iAttachType = (int)Outlook.OlAttachmentType.olByValue;
Outlook.Attachment oAttach = oMsg.Attachments.Add(attachment, iAttachType, iPosition, sDisplayName);
oMsg.Subject = txtSubject.Text.ToString();
foreach (string t in sTORecipsList)
{
Outlook.Recipient recipTo = oMsg.Recipients.Add(t);
recipTo.Type = (int)Outlook.OlMailRecipientType.olTo;
}
foreach (string c in sCCRecipsList)
{
Outlook.Recipient recipCc = oMsg.Recipients.Add(c);
recipCc.Type = (int)Outlook.OlMailRecipientType.olCC;
}
oMsg.Recipients.ResolveAll();
Thread.Sleep(2000);
oMsg.Send();
rows.Row.ItemArray[0] = "Sent";
sTORecipsList = null;
sCCRecipsList = null;
//recipTo = null;
oRecips = null;
oAttach = null;
oMsg = null;
oApp = null;
Thread.Sleep(2000);
}
catch (Exception)
{
throw;
}
}
MessageBox.Show("All message sent!!");
}
等待专家帮助。提前致谢。
问候, 苏布拉塔