System.Net.Mail: The specified string is not in the form required for a subject

Having your ASP.NET error handling routine, which sends you emails when an error occurs on your site, itself fail is annoying. Especially when you think you’ve made the code robust enough. Anyway the error handler for one site I work on was failing with “ArgumentException: The specified string is not in the form required for a subject“.

So what is exactly “the form required for a subject”? Googling for this error message returns a lot of junk and misinformed forum posts. It turns out that setting the Subject on a System.Net.Mail.Message internally calls MailBnfHelper.HasCROrLF (thank you Reflector) which does exactly what it says on the tin. Therefore one forum poster’s solution of subject.Replace("\r\n", " ") isn’t going to work when your have either a carriage return or line feed in there.

So, obviously, the solution is:

message.Subject = subject.Replace('\r', ' ').Replace('\n', ' ');

Personally, I think that the MailMessage should to this for you or at least Microsoft should document what actually constitutes a “form required for a subject” in MSDN or, even better, in the actual error message itself!

6 comments so far

  1. Tom Gilkison on

    Thank you for taking the time to post the solution. If everyone did this, it would be much easier to do what already should have been done.

  2. davidabrahams on

    Thanks Duncan very helpful and well written post. I was able to fix the problem I was having

  3. sr216viper on

    I ran into the same problem today. Fortunately for me your web site was the first one that I looked at. Thanks so much for taking the time to post this.

  4. [...] Il problema è dovuto al fatto che il contenuto della proprietà Message può contente una nuova linea, quindi “rn”, che genera un errore nel metodo Send come spiegato qui. [...]

  5. bouquet on

    Good post!
    Actually, it’s better also to check subject on empty string to prevent ArgumentException on ‘replace’ function.

  6. Sami on

    Thank you for taking the time to post the solution. If everyone did this, it would be much easier to do what already should have been done.


Leave a reply