Tuesday, January 1, 2008

Sending automated email with ASP.NET

This is something I had to do a bit of digging. Since I am not a linux, php, or cgi script guru, I use ASP.NET to do all my scripting and programming. Finding solutions in ASP.NET are sometimes straight forward, but the odd time it isn't. With sending automated emails I didn't think it would be too much a problem, which it isn't if your ISP doesn't block outgoing SMTP servers transmissions. But if your ISP does, then it's a bit more of a hassle.

For an ISP that doesn't block SMTP, you can install the SMTP Server that comes with Windows Server 2003 or XP. It is a component of IIS. This is of course if you don't have MS Exchange. Many users tend to use the namespace System.Web.Mail for the classes used for sending email, this is fine when it comes to having an ISP that doesn't block SMTP transmissions. But still why use something that is now a bit outdated? Namespace System.Net.Mail which was introduced in ASP.NET 2.0 has more functionality and flexibility when it comes to sending emails. One of the more important features being able to supply credentials to a specified SMTP server. This will then allow you to utilize your ISP's SMTP Server and send emails.

So lets take a look at
some simple code that will get you on your way. The following code would ideally be put under the function that handles a button click (i.e. submit button). You will have to have the namespaces System.Net and System.Net.Mail imported.

MailMessage instance used for defining the attributes and content of the email<%@ Page Language="C#" ContentType="text/html" ResponseEncoding="utf-8" %>
MailMessage message = new MailMessage(txtFrom.Text, txtTo.Text, txtSubject.Text, txtBody.Text);

SmtpClient instance used for defining the SMTP Server to be used for sending the email
SmtpClient emailClient = new SmtpClient(txtSMTPServer.Text);

Part of the System.Net namespace : NetworkCredential instance defines the user name and password used for accessing the SMTP Server in order to the send email
NetworkCredential SMTPUserInfo = new NetworkCredential(txtSMTPUser.Text, txtSMTPPass.Text);

Explicitly defines emailClient instance not to use default credentials when sending the email
emailClient.UseDefaultCredentials = false;

Set the credentials for emailClient instance with those defined by SMTPUserInfo instance
emailClient.Credentials = SMTPUserInfo;

Sends the email

You can then setup ASP.NET form that will allow the user to enter in the relevant information using related ASP.NET controls.

Reference Material

ASP .NET 2.0

No comments: