Dec 142012

Using 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 or AspEmail from 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.  \r\n\r\nWith 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 application. \r\n\r\n

//create the mail message\r\nMailMessage mail = new MailMessage();\r\n\r\n//set the addresses\r\nmail.From = new MailAddress("");\r\nmail.To.Add("");\r\n\r\n//set the content\r\nmail.Subject = "This is an email";\r\nmail.Body = "this is a sample body";\r\n\r\n//send the message\r\nSmtpClient smtp = new SmtpClient("localhost");\r\nsmtp.Send(mail);

\r\n\r\nThis 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.\r\n\r\nIn 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 Well here’s a bit a code that shows you how to do just that. \r\n\r\n

string strTo = "";\r\nstring strFrom="";\r\nstring strSubject="Mail Test Using SMTP Auth";\r\nstring strBody="This is the body of the message";\r\n\r\nstring userName = "xxx"; //remote mail server username\r\nstring password = "xxx"; //remote mail server pasword\r\n\r\nMailMessage mailObj = new MailMessage(strFrom, strTo, strSubject, strBody);\r\nSmtpClient SMTPServer = new SmtpClient(""); //remote smtp server\r\nSMTPServer.Credentials = new System.Net.NetworkCredential(userName, password);\r\ntry \r\n{ \r\nSMTPServer.Send(mailObj); \r\nResponse.Write("Sent!"); \r\n}\r\n \r\ncatch (Exception ex) \r\n{\r\nResponse.Write(ex.ToString()); \r\n}\r\n

For additional examples check out the wonderful resource at I hope this helps. Thanks for reading.

Peter Viola

Creative, customer focused, results oriented, Senior Web Systems Engineer who enjoys providing the highest level of customer service supporting complex Windows hosting solutions. MCITP, MCSA, MCTS

More Posts - Website