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.  \r\n\r\nWith 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. \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("me@mycompany.com");\r\nmail.To.Add("you@yourcompany.com");\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 system.net.mail? Well here’s a bit a code that shows you how to do just that. \r\n\r\n

string strTo = "test@gdomain-y.com";\r\nstring strFrom="test@domain-x.com";\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("mail.mydomain.com"); //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

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

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