Creating a Simple Page to Send E-Mail Messages


Once you ve configured the SMTP virtual server on your computer, sending e-mail messages from your Web pages is actually quite simple. Let s start by creating a page that lets you or your users compose an e-mail message and send it. When the page is running, it will look like Figure 15-2.

click to expand
Figure 15-2: A Web page that allows you to send e-mail messages.

Create the  SendEmail.aspx page

  1. In Web Matrix, create a new page and name it  SendEmail.aspx.

  2. Type the text Send an E-mail Message, and set the block format of the text to Heading 1.

  3. From the Web Controls tab of the Toolbox, drag the following controls onto the page and set their properties as indicated. Use Figure 15-2 as a guide to laying out the controls.

    Control

    Property Settings

    Label

    ID: labelFrom

    Text: (your e-mail address)

    TextBox

    ID: textTo

    RequiredFieldValidator

    ControlToValidate: textTo

    ErrorMessage: You must enter a recipient!

    RegularExpressionValidator

    ControlToValidate: textTo

    ErrorMessage: Invalid e-mail address!

    TextBox

    ID: textSubject

    TextBox

    ID: textMessage

    TextMode: MultiLine

    RequiredFieldValidator

    ControlToValidate: textMessage

    ErrorMessage: You must enter a message!

    Button

    ID: buttonSend

    Text: Send

    Button

    ID: buttonNewMessage

    Text: New Message

    Label

    ID: labelStatus

    Text: (empty)

    Font.Bold: True

    ForeColor: Red

Note 

The validator controls aren t required for the page to run properly, but I recommend that you add them to the page.

  • Select the RegularExpressionValidator control, and in the Properties window, click the ellipsis button for the ValidationExpression property to display the Regular Expression Editor dialog box. From the Standard Expressions lists, select Internet E-mail Address to fill in the Validation Expression box, as shown here:

  • After you ve selected the validation expression, click OK.

  • Using Figure 15-2 as a guide, type text into the page for captions.

  • With the controls in place to collect the information for an e-mail message, let s write the code that will send the e-mail message.

    Creating Code to Send E-Mail Messages

    To send e-mail messages, you work with objects in a .NET Framework namespace (library) named System.Web.Mail. Web Matrix doesn t automatically include the System.Web.Mail namespace with Web pages. Before you write code to send e-mail messages, therefore, you ll need to add a namespace reference to your page, as you learned in Chapter 6. In the  SendEmail.aspx page, switch to All view, and add the following line just after the <%@ Page %> declaration:

    <%@ import Namespace="System.Web.Mail" %>

    The import declaration includes the System.Web.Mail namespace with your page so that you can use the objects in that namespace. You can now use the objects you need, so let s write the code to send a message.

    Note 

    Web Matrix includes a code builder for creating the code you need to send an e-mail message. You won t use the code builder in this chapter because the builder hard-codes most of the values for the e-mail message sender, recipient, and subject. The code you ll create in this chapter instead reads these values from controls on the page at run time, so you would need to modify the generated code by hand. Moreover, the code required to send an e-mail message is fairly simple, so I m just going to spell it out. If you re curious about the e-mail code builder, create a new Web page, switch to Code view, and drag the Send Email element from the Toolbox onto the page.

    Switch to Design view, and double-click the Send button to create a Click handler for the button. Web Matrix switches to Code view. In the buttonSend_Click handler, add the following code, which reads information from the page, configures an e-mail message, and sends it:

    Sub buttonSend_Click(sender As Object, e As Ev entArgs     Dim emailMessage As MailMessag     emailMessage = New MailMessag     emailMessage.From = labelFrom.Tex     emailMessage.To = textTo.Tex     emailMessage.Subject = textSubject.Tex     emailMessage.Body = textMessage.Tex     SmtpMail.SmtpServer="localhost     Tr         SmtpMail.Send(emailMessage         labelStatus.Text = "Message sent!         buttonSend.Enabled = Fals     Catch ex As Exceptio         labelStatus.Text = "Unable to send e- mail message.     End Tr End Sub 

    The core of the code segment consists of only about eight lines; the remaining lines are for error checking and for changing the user interface of the page. To start with, you create an e-mail message as an object of type MailMessage. In the code, I declared a variable named emailMessage and used it to hold an instance of the MailMessage object. To create the contents of the e-mail message, you set the To, From, Subject, and Body properties of the emailMessage object. I retrieved the values of most of these properties from the text boxes on the page. The From property is set to the value of the labelFrom control that contains your e-mail name. I didn t use a text box for the From portion of the message because in this page, all e-mail messages come from you. If you wanted to, you could easily change labelFrom to a text box and allow users to enter their own e- mail address as the From value.

    When retrieving the values of the text boxes, I didn t apply HTML encoding to the values (via the Server.HtmlEncode method), as I taught you to do in previous chapters. The user s input is not going to be formatted as HTML. Instead, the e-mail format will be plain text, so HTML elements won t have any effect when the e-mail message is displayed. A little later, I ll show you how to create an e-mail message that s formatted with HTML, and in that case, you will need to apply HTML encoding.

    After you ve constructed your message, you need to send it. To send the message, you use the SmtpMail object. You start by specifying the SMTP server to use for sending your e-mail. You want to use the SMTP virtual server running on your own computer, so you set the server name to localhost. To actually send the message, you call the Send method of the SmtpMail object. Because sending e-mail messages is subject to various types of errors, always call the SmtpMail.Send method in a Try-Catch block. In this example, I display error and status messages using the labelStatus control. In the Try block, I display a message indicating success because users find it helpful to know that their message has been sent. In the Catch block, I display a generic error message. While you re testing the page, you might want to display the Message property of the ex exception object in the Catch block, but for security reasons, in the final version of your page, don t pass error messages through so users can see them. Finally, I disable the Send button if the message was sent successfully; that way, users don t inadvertently resend the message by clicking the Send button again.

    If users want to send another message, they can click the New Message button that you ve provided. The New Message button, as you can guess, resets the text boxes and reenables the Send button. In Design view, double-click the New Message button and then add the following boldfaced code to the button s Click handler:

    Sub buttonNewMessage_Click(sender As Object, e  As EventArgs     textTo.Text = ""     textSubject.Text = ""     textMessage.Text = ""     buttonSend.Enabled = True     labelStatus.Text = "" End Sub

    Run the page by pressing F5. For the recipient, fill in your own e- mail address that is, send an e-mail message to yourself. Fill in a subject and a message, and then click Send. If all goes well, the page will display Message sent! Open your e-mail program, and check for new e-mail messages. Within a few moments, you ll receive the e-mail message you sent using the Web page. (The delay between sending and receiving will vary according to how long it takes your e-mail provider to receive the message and make it available to you.) If you have friends who are willing to help you, experiment with sending them e-mail messages as well.

    If your page reports an error, review the section Installing and Configuring the SMTP Virtual Server, earlier in the chapter. Most difficulties with sending e-mail messages involve either a problem with the SMTP virtual server configuration or a problem with permissions to run cdosys.dll.

    If you added the recommended validation controls to the page, you won t be able to skip the recipient s e-mail address, and you ll have to enter an e-mail address that s at least formatted properly. However, nothing you re doing with the MailMessage object or the SmtpMail object can guarantee that the e-mail addresses you specify are valid, either for the To field or for the From field. The validator control will not ensure that the address you re sending the message to is a real address. The only way to determine whether an e-mail address is valid is to try to send e-mail messages to it.

    Try another experiment. Create a new e-mail message, and this time enter an e-mail address for the To field that s obviously invalid, perhaps something like Sserddaliam-dilavni@contoso_bogus.com. Send the new e-mail message. You won t see any error messages during the send process. After you ve sent the new message, check your own e-mail. Assuming that you really did enter an invalid e-mail address, the e-mail will bounce back to you, because your e-mail address is listed as the sender. The e-mail message has generated an error, but you can t detect the error directly because the error doesn t occur until the e-mail message is in transit.

    That s the basic technique for sending an e-mail message from your Web pages. Having a Web page for sending e-mail messages is fun, but it s not all that practical unless you happen to be away from your computer and want to dash off a quick message to someone. You can use e- mail in various interesting ways in your Web applications, however. Let s explore some of those possibilities.




    Microsoft ASP. NET Web Matrix Starter Kit
    Microsoft ASP.NET Web Matrix Starter Kit (Bpg-Other)
    ISBN: 0735618569
    EAN: 2147483647
    Year: 2003
    Pages: 169
    Authors: Mike Pope
    BUY ON AMAZON

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net