Add (custom) headers to MailMessage class

Photo of author
Written By Jan Reilink

Windows Server systems administrator & enthusiast.

How to add custom headers to System.Net.Mail? When sending an email using the MailMessage class (System.Net.Mail namespace) in an ASP.NET website, certain email headers like Message-ID are not always set. When a Message-ID header is missing, email might be blocked by the recipients SMTP server like Gmail. Therefore it is necessary to set such headers.

Add custom header in MailMessage class / System.Net.Mail Namespace

The System.Net.Mail Namespace allows you to send authenticated SMTP email over TLS. Unfortunately, System.Net.Mail leaves out the mandatory Message-ID header. Here is how you can add this important header to your email. You can set a Message-ID, or any other custom header with the Message.Headers property and .Add method:

Message.Headers.Add( "Message-Id", "<" + Guid.NewGuid().ToString() + "@example.com>" );
Code language: C# (cs)

Change example.com with your own domain name.

Custom headers
You can use this for other, custom headers as well, for example:

Message.Headers.Add( "X-Instance-ID", Convert.ToString( InstanceID[0] ) );
Code language: C# (cs)

Did you like: Add (custom) headers to MailMessage class

Then please, take a second to support Sysadmins of the North and donate!

Your generosity helps pay for the ongoing costs associated with running this website like coffee, hosting services, library mirrors, domain renewals, time for article research, and coffee, just to name a few.



Hi! Join the discussion, leave a reply!