2015-07-01 40 views
2

我使用System.Net.Mail發送電子郵件在我的應用程序,但我有一個例外,我不知道什麼/問題在哪裏,以及如何解決它。在郵件頭中找到無效字符:';'在C#

的問題說,我有一些無效的字符:

An invalid character was found in the mail header: ';'. 

我試圖谷歌沒有成功。

與電子郵件地址字符串是:

[email protected]; [email protected]; [email protected]; [email protected]; 

這裏是我的電子郵件發送代碼:

SmtpClient smtpClient = new SmtpClient("smtp........."); 
    System.Net.Mail.MailMessage mailMessagePlainText = new System.Net.Mail.MailMessage(); 

    mailMessagePlainText.IsBodyHtml = true; 
    mailMessagePlainText.From = new MailAddress("[email protected]", "admin"); 

    mailMessagePlainText.Subject = "test"; 
    mailMessagePlainText.Body = "test"; 

    mailMessagePlainText.To.Add(new MailAddress(List1.ToString(), "")); 
    mailMessagePlainText.Bcc.Add(new MailAddress("[email protected]", "")); 

    try 
    { 
     smtpClient.Send(mailMessagePlainText); 
    } 
    catch (Exception ex) 
    { 
     throw (ex); 
    } 
+0

可能的重複[發送電子郵件到多個收件人MailMessage](http://stackoverflow.com/questions/23484503/sending-email-to-multiple-recipients-with-mailmessage) – PMerlet

+0

List1的值是什麼?它是你提到的電子郵件地址字符串嗎? – MeanGreen

+0

@MeanGreen:是的,先生List1的值是電子郵件地址字符串:[email protected]; [email protected]; [email protected]; [email protected]; –

回答

2
foreach (var address in List1.split(';')) { 
    mailMessagePlainText.To.Add(new MailAddress(address.Trim(), "")); 
} 

因爲這裏上面根據你的字符串,在這個循環中的每個地址上面會產生如下:

"[email protected]" 
" [email protected]" 
" [email protected]" 
" [email protected]" 

因此,通過添加.Trim()來解決會讓你的代碼工作。

+0

參數「地址」不能是空字符串。 參數名稱:地址 –

+0

「空字符串」錯誤的原因是電子郵件地址字符串後綴爲分號。如果'Split()'方法會將分號後面的空格看作完全有效的空字符串。然而,當它被傳遞給'MailAddress'的構造函數時(在'foreach'循環的最後一個元素中),它不能驗證電子郵件地址。修復 - 刪除結尾的分號。我知道這是一箇舊帖子,但任何遇到此問題的人都可能會發現上述答案不足以解決此問題。 –

0

它看起來就像是增加了地址作爲一個MailAddress,將在您需要一次添加1個。我不知道還有哪些重載可用,但以下內容可能會起作用。

我分割字符串;並分別添加每個地址。

更換

mailMessagePlainText.To.Add(new MailAddress(List1.ToString(), "")); 

foreach (var address in List1.split(';')) { 
    mailMessagePlainText.To.Add(new MailAddress(address , "")); 
} 
+0

謝謝,但現在我有新的例外:指定的字符串不是電子郵件地址所需的格式。 –

+0

Hans Kesting在他的回答中提到(我現在無法訪問API),角色應該是a,而不是a; – MeanGreen

1

一個MailAddressCollection(如您的mailMessagePlainText.To)具有接受包含用逗號分隔郵件地址列表,一個字符串的Add method

所以要使用它,您需要將;更改爲,,並可能刪除多餘的空格。

+2

我沒有在字符串中的空格,我已經替換';'與','。問題是字符串中的最後一個字符... –