System.Net.Mail FAQ

Complete FAQ Listing


3.3.4 How do I add custom headers to the MailMessage? Printer Friendly

Custom headers are useful for adding information to a MailMessage that may not be supported on standard properties. By adding custom headers, we can tag email messages with information that may not be visible to the end user, yet still might be important to us. This is especially useful in tracking bounced emails. By using custom headers, we can find our custom header in a bounced email, and perhaps tie it back to a record in the database.

Below is an example of adding two "X-" headers to a MailMessage. There isn't anything special about adding the prefix "X-" to a header. In the email world, the "X-" prefix has just come to mean "extra".

[ C# ]

static void CustomHeaders()
{
//create the mail message
MailMessage mail = new MailMessage();

//set the addresses
mail.From = new MailAddress("me@mycompany.com");
mail.To.Add("you@yourcompany.com");

//set the content
mail.Subject = "This is an email";
mail.Body = "this is the body content of the email.";

//to add custom headers, we use the Headers.Add(...) method to add headers to the
//.Headers collection
mail.Headers.Add("X-Company", "My Company");
mail.Headers.Add("X-Location", "Hong Kong");


//send the message
SmtpClient smtp = new SmtpClient("127.0.0.1");
smtp.Send(mail);
}



[ VB.NET ]
Sub CustomHeaders()
'create the mail message
Dim mail As New MailMessage()

'set the addresses
mail.From = New MailAddress("me@mycompany.com")
mail.To.Add("you@yourcompany.com")

'set the content
mail.Subject = "This is an email"
mail.Body = "this is the body content of the email."

'to add custom headers, we use the Headers.Add(...) method to add headers to the 
'.Headers collection
mail.Headers.Add("X-Company", "My Company")
mail.Headers.Add("X-Location", "Hong Kong")


'send the message
Dim smtp As New SmtpClient("127.0.0.1")
smtp.Send(mail)
End Sub 'CustomHeaders