Resolving 'The specified string is not in the form required for a subject.'

C#asp.netMailmessage

C# Problem Overview


I have a class that sends an Email (MailMessage) but I get the following error:

> "The specified string is not in the form required for a subject."

Is there a handy dandy method to sanitize the strings or do I have to write my own?

C# Solutions


Solution 1 - C#

I haven't personally tried it, but according to this, you only need:

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

or something equivalent.

Internally, the MailMessage class will check the subject with:

if (value != null && MailBnfHelper.HasCROrLF(value)) 
{
   throw new ArgumentException(SR.GetString(SR.MailSubjectInvalidFormat));
}

So the only limitation (for now) happens to be the presence of CR or LF.

Solution 2 - C#

Also there is a limit of 168 characters so you should check for that too.

UPDATE: sorry this is complete bullshit :) It must have been a line break in my case.

Solution 3 - C#

For VB.NET

subject = subject.Replace(vbNewLine, "")

Solution 4 - C#

I know this has already answered, but it goes:

First, you need to trim the subject then account for the subject max length (https://stackoverflow.com/questions/1592291/what-is-the-email-subject-length-limit):

subject = subject.Trim();
subject = subject.Substring(0, Math.Min(subject.Length, 78));

This will remove any new lines or empty spaces at the beginning and the end. Then Substring is used to restrict the subject length.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMattView Question on Stackoverflow
Solution 1 - C#Christian.KView Answer on Stackoverflow
Solution 2 - C#mike nelsonView Answer on Stackoverflow
Solution 3 - C#Clarice BouwerView Answer on Stackoverflow
Solution 4 - C#WeggoView Answer on Stackoverflow