HomeASP.NET Sending Mail with the ASP.NET Web Matrix
Sending Mail with the ASP.NET Web Matrix
The MS ASP.NET Web Matrix application has a number of code wizards, covered in previous articles. This one covers the EMAIL message code generator. It is surprisingly useful for adding contact page functionality to a website; your visitors will appreciate being able to interact with you in this manner. Dan Wellman explains how to set it up.
Contributed by Dan Wellman Rating: / 10 December 12, 2005
The previous articles looked at the built-in code wizards that come with the MS ASP.NET Web Matrix application. (You can find the most recent of these articles here). These code generators are included to make performing basic database operations with ASP.NET extremely easy to do and can simplify the learning process or cut down on design time. We’ve covered all four of the basic database operations in the previous four articles, but there remains one code wizard that has not yet been used: the EMAIL message code generator.
Many websites feature a contact page that will let a user enter a message into the page and then have the application send the email to the address specified in the email function parameters. This may be for technical support, help and advice, or to request information. Whatever the reason, the ASP.NET Web Matrix makes adding this functionality to a site extremely easy, and is exactly what we’re going to do.
For conclusive testing of this feature, you are going to need to have and use IIS (5.1 ideally). If you have Norton, or another application able to scan all email for viruses, you will know it has worked when you get a popup advising that the mail is being scanned, but to be able to receive an email in your domain and view it, IIS is required.
This part is simple, so let’s get it out of the way first; open IIS, expand the Default SMTP Virtual Server and select Domains. There should be a default domain already set up, but you can create a new one for the purpose of this article by right-clicking anywhere in the right-hand pane of IIS and selecting New > Domain.
This action will generate an instance of the New SMTP Domain wizard. Set the radio to Alias and then click Next. Choose a name for your domain, dudemail.com will be sufficient, and click Finish. Your domain will now appear in the domain list of IIS. That is it. All incoming mail for this domain will be stored in a folder called Drop, which resides in the mailroot folder of Inetpub.
Now to create the page, which will again be basic; we’ll add the necessary form elements and code for the page to work, then I’ll leave it up to you to add whatever design elements and decoration as required. Open the MS Web Matrix and create a new ASP.NET page in your private folder. Placing the new file in the private folder will, as you know, make sure that only users that have logged in can use it.
Drag a label and a textbox onto the first line of the page, another label and another text box onto the second line. Finally drag a button element onto the third line and line it up with the right-hand edge of the text boxes.
Using the properties pane at the bottom right of the application window, change the text of the first label to Subject: the text of the second label to Message: and remove the text value of the final label.
At this point, you can set the ID of the first text box to txtSubject and the ID of the second text box to txtMessage. As the message may be of any length, you can also set the TextMode to MultiLine. You should now increase the height of this text box to a respectable size. Doing this will put the label to the bottom of the text box, so to counter this, you should increase the height of the label element to that of the text box.
Our work in the Design view is done (for now), so switch to the Code view and drag a Send Email Message function control onto the page. This will open the code wizard associated with the function, which will prompt you for some input. The application helpfully pre-fills the text fields with examples of the information it is looking for, namely To, From and Subject information along with the format of the mail and the name of the SMTP server.
Change the To: field to techsupport@dudemail.com. You can use elements from the page for the From: and Subject: fields; set From: to HttpContext.Current.User.Identity.Name and set Subject: to subject. Leave the rest at the defaults and click Finish.
This will add a block of code to the page, but you will still need to tweak it slightly to get it working. A comment reminds you to set the mailMessage.Body property, which is what we are going to do now. Before that however, set a couple of variables to hold the information from the page before it is turned into the email:
Dim subject As String subject = txtSubject.Text Dim message As String message = txtMessage.Text
Now add the following line to the end of the mailMessage code:
mailMessage.Body = message
To create a caller for the message function, go back to the Design page and double-click the Send button. Make sure the message function is within the btnSend_Click event handler.
Now test the page and send an email; it should appear in your Drop folder, and appear as intended.
As I mentioned in a previous article, the built-in web server of the MS Web Matrix is good, but it’s not perfect. If you get an authorization error when trying to view the page, try right-clicking on the web server icon that appears in the system tray when the server is running and selecting Open in Web Browser. This will give you a directory listing style overview of you application. Simply navigate to the contactUs.aspx file a click it. You’ll need to sign in of course, but the page will then display as expected.
The page works, but there is no way of letting the visitor know that their message has been sent. Also, what happens if the message field is left blank? The message will still be emailed, but it will be a complete waste of the resource. We can implement a very basic method of informing the user of a success or error (not error as such, but an indication that a message has not been entered) very easily.
Add a label on its own on the fourth line and change its color to green and the ID to lblSuccess. Now drag a label onto the line next to the message text box. Set the color of this one to Red and the ID to lblError. Don’t forget to increase the height of this label to the same as the text box it is next to.
Switch back to the Code view and at the top of the function, just below the btn_Click call right at the top, add the following:
lblError.Text = "" lblSuccess.Text = ""
This will simply reset the labels on the click of the button so that if it takes a second attempt to send the email, both the error and success labels are not displayed at once. You can create a simple flag that will be incremented on each occasion that the Message text box is empty; add the following code beneath the existing Dim’s:
Dim flag As Integer flag = 0
Now directly below this, add the following If statement:
If txtMessage.Text = "" Then lblError.Text = "You have not entered a message" flag += 1 End If
To complete our message output system, enclose the Send method invocation in the following If statement, to make it look like:
If flag = 0 Then System.Web.Mail.SmtpMail.Send(mailMessage) lblSuccess.Text = "Message sent" End If
All this does is check that the flag remains at zero, and if it does, sends the email and displays the success message. The whole code page should now appear thus:
Sub btnSend_Click(sender As Object, e As EventArgs) lblError.Text = "" lblSuccess.Text = ""
Dim subject As String subject = txtSubject.Text Dim message As String message = txtMessage.Text Dim flag As Integer flag = 0
If txtMessage.Text = "" Then lblError.Text = "You have not entered a message" flag += 1 End If
Dim mailMessage As System.Web.Mail.MailMessage = New System.Web.Mail.MailMessage mailMessage.From = HttpContext.Current.User.Identity.Name mailMessage.To = "techsupport@dudemail.com" mailMessage.Subject = subject mailMessage.BodyFormat = System.Web.Mail.MailFormat.Text mailMessage.Body = message System.Web.Mail.SmtpMail.SmtpServer = "localhost"
If flag = 0 Then System.Web.Mail.SmtpMail.Send(mailMessage) lblSuccess.Text = "Message sent" End If
End Sub
So now you have another page to add to your growing collection, all created with a minimum amount of exertion. But this email capability can also be easily added to pages you have already created. How about, for example, collecting a user’s email address on the registration page, and then using this to send a confirmation email that an account has been created?
Or perhaps you would like to use this to send confirmation that a password has been reset. In fact, it would be pretty easy to allow an account password to be randomly generated and then emailed to the user's email address in the event that the stored password is forgotten. There are many uses for this function and that makes it not only desirable but almost essential in any serious web application project, and it is not only possible, but easy with just a few clicks and the indispensable MS Web Matrix.