Sending E-mail from ASP.NET

Sending e-mail from ASP.net is not as hard as it could be. You just need to know all the information that you'd normally need to know for setting up a SMTP client…like Outlook Express. I had read that you need to set up an SMTP server on the IIS server that you're running in order to be able to e-mail from that server. That's not true. I was able to set up, in a test ASP.NET file, code that logs into our exchange e-mail client and sends mail through it. The only drawback is that the username and password are stored in the code, but that doesn't post a huge security risk, as the user doesn't have meaningful privelages. So, here's the code (slightly edited to take out the juicy bits)…
System.Net.Mail.MailMessage mail_message = new 
   System.Net.Mail.MailMessage();
mail_message.From = new 
   System.Net.Mail.MailAddress("my@email.com", 
   "User's Real Name");
mail_message.To.Add("them@there.com");
mail_message.Subject = "Subject";
mail_message.Body = "Message";
System.Net.Mail.SmtpClient mail_client = new 
   System.Net.Mail.SmtpClient("mail.myserver.com");
mail_client.Credentials = new 
   System.Net.NetworkCredential("myuser@myserver.com", 
   "mypassword");
mail_client.Send(mail_message);
mail_message.Dispose();
Very nice. Very easy. Only nine lines of code (and I could probably make it less).

Leave a Reply

Your email address will not be published.