MailBee. NET Objects Tutorials

Add and remove custom headers

To add a custom header to a new message you can use the following code:

C#

// Create a MailMessage object.
MailMessage msg = new MailMessage();

// Add a header.
msg.Headers.Add("MyHeader", "Some value for my own header", false);

VB.NET

' Create a MailMessage object.
Dim msg As New MailMessage()
 
' Add a header.
msg.Headers.Add("MyHeader", "Some value for my own header", False)

You can specify the name and the value of the header, and also specify whether the header value should be overwritten if the header already exists in the message. When overwrite argument is set to true and the header with the same name already exists, it will be overwritten; otherwise, another header with the same name will be added.

The developer can also easily remove all custom headers from the message:

C#

// Remove the non-standard headers from the message.
msg.Headers.RemoveCustomHeaders();

VB.NET

' Remove the non-standard headers from the message.
msg.Headers.RemoveCustomHeaders()

This method removes all headers except standard ones. You can find the list of standard headers in RemoveCustomHeaders method description. Another way is to use Remove or RemoveAt methods, thus, you will be able to specify the headers to be deleted:

C#

// Remove the specified header.
msg.Headers.Remove("X-Special-Header"); 

// Remove the first header.
msg.Headers.RemoveAt(0);

VB.NET

' Remove the specified header.
msg.Headers.Remove("X-Special-Header") 
 
' Remove the first header.
msg.Headers.RemoveAt(0)