Sending Mail through SMTP with Authentication

If you have looked at the process of sending emails from within .NET, odds are pretty good that you have stumbled across the SmtpServer class.  To send email, you create a MailMessage object, assign the necessary properties and then use the Send method on SmtpServer.  The SmtpServer class can be pointed to any mail server that you would like. 

MailMessage message = new MailMessage();

message.From = "bjohnson@objectsharp.com";
message.To = "who@ever.com";
message.Subject = "Testing";
message.Body = "This is a test";

SmtpServer.Server = "mail.server.com";
SmtpServer.Send(message);

So all is well and good right?  Well maybe not so much.  What happens if your email server, like all good servers, doesn't allow relays.  Instead, it requires that a user id and password be provided.  What I found strange is that the SmtpServer class doesn't include properties like UserId or Password to handle the authentication.  So how is this accomplished.

The answer is to utilize a newly added feature(new to .NET 1.1, that is).  The MailMessage class has a Fields collection.  The necessary authentication information gets added to the fields in the message that is being sent out. Certainly not where I expected it to be, but smarter people than I designed the class, so I'm sure there was a reason for this approach.  Regardless, it's knowledge that needs to be easily Googlable, hence the post. An example of the code that adds the three fields follows.

message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate",
  
"1"); //basic authentication
message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername",
   "userid");
//set your username here
message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword",
   "password");
//set your password here