How to fix exception thrown when sending mail message to multiple recipients?

好久不见. 提交于 2019-12-06 19:47:51

问题


In the code snippet below, I'm getting a FormatException on 'this.Recipients'. More specifically, the message is "An invalid character was found in the mail header: ';'".

Recipients is a string of three email addresses separated by semicolons (the ';' character). The list of recipients is read from an app.config and the data is making it into the Recipients variable.

How can I be getting this error when multiple recipients should be separated by a semicolon? Any suggestions? As always, thanks for your help!

public bool Send()
{
    MailMessage mailMsg = 
       new MailMessage(this.Sender, this.Recipients, this.Subject, this.Message);

    SmtpClient smtpServer = new SmtpClient(SMTP);
    smtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;

Edit #1 - This says use a semicolon.


回答1:


I can't see anything in the MailMessage constructor documentation to suggest you can specify multiple recipients like that. I suggest you create the MailMessage object and then add each email address separately.

Note that the MailAddressCollection.Add method is documented to accept comma-separated addresses... so it's possible that that would work in the constructor too.




回答2:


You have to use the .Add method to add these addresses. Here is some sample code that I use:

string[] toAddressList = toAddress.Split(';');

//Loads the To address field
foreach (string address in toAddressList)
{
    if (address.Length > 0)
    {
        mail.To.Add(address);
    }
}



回答3:


Reviving this from the dead, if you separate the recipient email addresses by a comma, it will work.

this.Recipients = "email1@test.com, email2@test.com";

var mailMsg = new MailMessage(this.Sender, this.Recipients, this.Subject, this.Message);
SmtpClient smtpServer = new SmtpClient(SMTP);
smtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpServer.Send(mailMsg);



回答4:


Try this

            string[] allTo = strTo.Split(';');
            for (int i = 0; i < allTo.Length; i++)
            { 
                if (allTo[i].Trim() != "")
                    message.To.Add(new MailAddress(allTo[i]));
            }                



回答5:


private string FormatMultipleEmailAddresses(string emailAddresses)
    {
      var delimiters = new[] { ',', ';' };

      var addresses = emailAddresses.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);

      return string.Join(",", addresses);
    }

Now you can use it like

var mailMessage = new MailMessage();
mailMessage.To.Add(FormatMultipleEmailAddresses("test@gmail.com;john@rediff.com,prashant@mail.com"));


来源:https://stackoverflow.com/questions/5914481/how-to-fix-exception-thrown-when-sending-mail-message-to-multiple-recipients

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!