2026-07-15

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

Stefan Bogdanescu

Stefan Bogdanescu

Founder & Senior Architect

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

An Invalid Character in Mail Headers: Solving the C# SMTP Headache

Sending emails programmatically is a fundamental task in almost every application, and using classes like System.Net.Mail in C# simplifies the process significantly. However, as you’ve discovered, sometimes the underlying communication protocols—in this case, the SMTP headers—have very strict rules about what characters are allowed.

If you encounter an error like "An invalid character was found in the mail header: ';'", it signals that a delimiter used within your message content is being misinterpreted by the mail server before the email can be delivered. As a senior developer, understanding this isn't just about fixing an error; it’s about respecting the protocol structure.

This post will dive into why this happens and provide a robust solution for handling complex recipient lists and message content in C#.

Understanding the Mail Header Constraint

The error you are seeing is not an issue with your C# code syntax itself, but rather an issue with how the SMTP server parses the message headers. Email standards (like RFCs) dictate specific rules for characters allowed within header fields (such as To, Subject, or custom headers).

In many cases, delimiters like the semicolon (;) are used to separate multiple values within a single field, but they are strictly forbidden in the main header structure where they cause parsing failures. Your input string: john@mydomain.org; beth@mydomain.org; ... contains these semicolons, which the mail client interprets as an invalid character in the message header itself.

The C# Solution: Separating Data from Headers

The key to fixing this is to ensure that your data (the list of email addresses) is processed and added to the MailMessage object in a structured way, ensuring only valid address objects are passed to the system, rather than passing raw, delimited strings.

Instead of concatenating addresses with semicolons directly into a string intended for a header field, you must use the dedicated collection methods provided by the .NET framework.

Correcting the Code Implementation

Let's look at how to correctly populate the To and Bcc collections, ensuring each recipient is handled as an individual MailAddress object:

using System.Net.Mail;
using System.Collections.Generic;

// Assume List1 contains the raw string data for demonstration
string emailListString = "john@mydomain.org; beth@mydomain.org; alfred@mydomain.org; barbie@mydomain.org;";
var recipients = emailListString.Split(';', StringSplitOptions.RemoveEmptyEntries);

SmtpClient smtpClient = new SmtpClient("smtp.example.com");
MailMessage mailMessagePlainText = new MailMessage();

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

// Fix: Build the To and Bcc collections correctly using individual MailAddress objects
var toAddresses = new List<MailAddress>();
foreach (var email in recipients)
{
    // Ensure we handle potential whitespace if present, though Split handles most cases
    toAddresses.Add(new MailAddress(email.Trim(), "Recipient Name")); 
}

mailMessagePlainText.To.AddRange(toAddresses);
mailMessagePlainText.Bcc.Add(new MailAddress("vincent@mydomain.org", "Admin"));


mailMessagePlainText.Subject = "Test Email"; // No semicolon here!
mailMessagePlainText.Body = "This is the message body."; // No semicolon here!

try
{
    smtpClient.Send(mailMessagePlainText);
    Console.WriteLine("Email sent successfully!");
}
catch (Exception ex)
{
    // Detailed error handling is crucial for debugging SMTP issues.
    Console.WriteLine($"Error sending email: {ex.Message}");
}

Best Practices for Robust Email Delivery

When building systems that rely on external communication, like sending emails, robustness is paramount. Just as in modern application architecture, separating concerns—data input from presentation logic—is critical. Consider how you handle external data before it touches the mail client:

  1. Input Validation: Always validate any string input (like email lists) immediately upon receipt. Use regular expressions or dedicated validation libraries to ensure the strings are valid email formats before attempting to construct MailAddress objects.
  2. Structured Data First: Never feed raw, delimited strings directly into header fields if you can avoid it. Process your data into structured collections (like List<MailAddress>) first, and then use those structures to populate the mail message object. This prevents accidental inclusion of illegal characters.

For developers building large-scale, reliable systems, adopting clean, well-structured data handling principles is key. Think about how frameworks like Laravel manage request/response cycles cleanly; this principle applies universally—ensure your data structures are valid before attempting external operations. For more insight into robust system design, you can explore resources on laravelcompany.com.

Conclusion

The error "An invalid character was found in the mail header: ';'" is a classic example of protocol adherence failing in application logic. By moving from concatenating raw string data to using the structured MailAddress objects provided by .NET, you ensure that your message conforms to SMTP standards. Always validate and structure your input data before attempting to send any external communication. Happy coding!

Tags:

Enhance your marketing setup with your own email marketing platform.

Join the growing number of SaaS platforms using Laravel Mail to offer email marketing solutions to their customers.