Authenticated SMTP Using System.Net.Mail

Using system.net.mail to send email messages from your web site makes life so easy.  In the old days of Classic ASP you often had to rely on 3rd party components such as AspMail from serverobjects.com or AspEmail from persists.com. While they were very capable products and are still widely used today it added an additional layer of complexity to your programming. If you ever had to move a site from one server to another there was always a risk the components were not in place which would cause problems for your users.  With system.net.mail you know as long as .Net is installed on the server hosting your site, your code will always work no matter how many times you move your web site or change hosting providers. In it’s simplest form the snippet below is the bare minimum of code you need to send a plain text message from your asp.net application.

//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 a sample body";

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

This works great when you are sending mail using the local SMTP server. However in certain situations you may need to send mail through a remote SMTP server. In most cases that remote server will have quite a bit of security enabled to prevent relaying and blocking spammers so the above code will not be enough for your application to send mail. In this case you will need to send your message by authenticating on the remote server with a username and password. So how does one go about doing that with system.net.mail? Well here’s a bit a code that shows you how to do just that.

string strTo = "test@gdomain-y.com";
string strFrom="test@domain-x.com";
string strSubject="Mail Test Using SMTP Auth";
string strBody="This is the body of the message";

string userName = "xxx"; //remote mail server username
string password = "xxx"; //remote mail server pasword

MailMessage mailObj = new MailMessage(strFrom, strTo, strSubject, strBody);
SmtpClient SMTPServer = new SmtpClient("mail.mydomain.com"); //remote smtp server
SMTPServer.Credentials = new System.Net.NetworkCredential(userName, password);
try 
{ 
SMTPServer.Send(mailObj); 
Response.Write("Sent!"); 
}
 
catch (Exception ex) 
{
Response.Write(ex.ToString()); 
}


For additional examples check out the wonderful resource at http://www.systemnetmail.com. I hope this helps. Thanks for reading.

No Comments