简体   繁体   English

在邮件标题中发现无效字符:';' 在 C# 中

[英]An invalid character was found in the mail header: ';' in c#

I'm using System.Net.Mail to send email in my application but I get an exception and I can't figure out what/where the problem is and how to fix it.我正在使用System.Net.Mail在我的应用程序中发送电子邮件,但出现异常,我无法弄清楚问题是什么/在哪里以及如何解决它。

The error says I have some invalid char:错误说我有一些无效的字符:

An invalid character was found in the mail header: ';'.在邮件标题中发现无效字符:';'。

I tried google without success.我试过谷歌没有成功。

The string with email address is:带有电子邮件地址的字符串是:

john@mydomain.org; beth@mydomain.org; alfred@mydomain.org; barbie@mydomain.org; 

Here is my email sending code:这是我的电子邮件发送代码:

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

    mailMessagePlainText.IsBodyHtml = true;
    mailMessagePlainText.From = new MailAddress("vincent@mydomain.org", "admin");

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

    mailMessagePlainText.To.Add(new MailAddress(List1.ToString(), ""));
    mailMessagePlainText.Bcc.Add(new MailAddress("vincent@mydomain.org", ""));

    try
    {
        smtpClient.Send(mailMessagePlainText);
    }
    catch (Exception ex)
    {
        throw (ex);
    }
foreach (var address in List1.split(';')) {
    mailMessagePlainText.To.Add(new MailAddress(address.Trim(), ""));
}

Because according to your string here above, each address in this loop above would produce following:因为根据上面的字符串,上面这个循环中的每个地址都会产生以下结果:

"john@mydomain.org"
" beth@mydomain.org"
" alfred@mydomain.org"
" barbie@mydomain.org"

So by adding .Trim() to address would make your code work.因此,通过将.Trim()添加到地址将使您的代码工作。

A MailAddressCollection (like your mailMessagePlainText.To ) has an Add method that accepts a string containing a list of mail addresses, separated by a comma . MailAddressCollection (就像你的mailMessagePlainText.To )有一个Add方法,它接受一个包含邮件地址列表的字符串,用逗号分隔

So to use that, you will need to change the ;因此,要使用它,您需要更改; into a , and possibly remove the extra spaces.进入 a ,并可能删除多余的空格。

It looks like you're adding the addresses as a single MailAddress, where you need to add them 1 at a time.看起来您将地址添加为单个 MailAddress,您需要一次添加 1 个。 I don't know what other overloads are available, but the following will probably work.我不知道还有哪些其他重载可用,但以下可能会起作用。

I split the string by ;我将字符串拆分为; and add each address separately.并分别添加每个地址。

replace代替

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

with

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM