[英]Problem sending mail to mlutiple users in C#
你好
我正在嘗試開發一個wpf應用程序,以便使用Microsoft Outlook應用程序發送批量電子郵件。 我正在使用一個datagridview,將從中提取cc和附件。 此外,每封郵件都會有多個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!!");
}
等待專家的幫助。 提前致謝。
此致 Subrata
Regex.Split
的第二個參數應為正則表達式模式。 如此匹配,
或;
作為分隔符,您可以使用\\s*[,;]\\s*
( \\s*
允許在分隔符周圍使用空白):
string[] tos = Regex.Split(to, @"\s*[,;]\s*");
請注意,這會在字符串上使用@
符號來保留轉義符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.