Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Build Your Own ASP.NET 2.0 Web Site Using CSharp And VB (2006) [eng]-1.pdf
Скачиваний:
143
Добавлен:
16.08.2013
Размер:
15.69 Mб
Скачать

Creating the Company Newsletter Page

Figure 14.17. Viewing the email

Creating the Company Newsletter Page

Let’s now extend the Dorknozzle site structure by adding a Newsletters page. This page will be accessible only to the site administrator, and will provide tools with which a customized newsletter can be sent to a list of recipients.

Open the Dorknozzle project in Visual Web Developer, and add to it a new web form named AdminNewsletter.aspx, making sure both the Select master page and Create code in a separate file checkboxes are checked. When prompted, select the Dorknozzle.master master page.

Complete the generated code like this:

File: AdminNewsletter.aspx

<%@ Page Language="VB" MasterPageFile="~/DorkNozzle.master" AutoEventWireup="false" CodeFile="AdminNewsletter.aspx.vb" Inherits="AdminNewsletter" Title="Dorknozzle Admin Newsletter"

%>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">

<h1>Create Newsletter</h1>

<asp:Label ID="resultLabel" runat="server" ForeColor="Red"/> <br />To:<br />

<asp:TextBox ID="toTextBox" runat="server" /> <br />Subject:<br />

<asp:TextBox ID="subjectTextBox" runat="server" /> <br />Introduction:<br />

601

Chapter 14: Working with Files and Email

<asp:TextBox ID="introTextBox" runat="server" TextMode="MultiLine" Width="300" Height="100" />

<br />Employee Of The Month:<br />

<asp:TextBox ID="employeeTextBox" runat="server" /> <br />Featured Event:<br />

<asp:TextBox ID="eventTextBox" runat="server" /> <br />

<asp:Button ID="sendNewsletterButton" runat="server" Text="Send Newsletter" />

</asp:Content>

Switch to Design View. The form should look like the one shown in Figure 14.18.

As you can see, the form contains seven TextBox controls, plus a Button and a Label. The boxes will allow the administrator to specify who the email is to be sent to and what the subject is, enter a simple introduction, identify the employee of the month, and feature a company event and a store item. The Button control is used to submit the form, while the Label control will display a confirmation message once the email has been sent.

To ensure that only administrators can send email messages, add the code highlighted in bold below, which we discussed in detail in Chapter 13, to Web.config:

File: Web.config (excerpt)

<!-- Only administrators are allowed to access AdminTools.aspx -->

<location path="AdminTools.aspx"> <system.web>

<authorization>

<allow roles="Administrators" /> <deny users="*" />

</authorization>

</system.web>

</location>

<!-- Only administrators are allowed to send emails --> <location path="AdminNewsletter.aspx">

<system.web>

<authorization>

<allow roles="Administrators" /> <deny users="*" />

</authorization>

</system.web>

</location>

</configuration>

602

Creating the Company Newsletter Page

Figure 14.18. The Create Newsletter form

One hurdle that we need to overcome is that we want to include an image to be displayed as part of the HTML content of the message. We can use either of two approaches to solve this problem:

Host the image on our web server and reference it in an <img> tag in the HTML code of the message (e.g. <img src="http://www.dorknozzle.com/Images/Newsletter.jpg" …>).

Embed the image data in the email.

We’ll apply the first technique, as it has the benefit of simplicity, and keeps the message as small as possible. If you want readers to see the image even when they’re not connected to the Internet, you should look into the second option.

603

Chapter 14: Working with Files and Email

Developer Mike Pope explained image embedding, and provided sample code, in a post on his blog.3

All we need to do is handle the Send Newsletter button’s Click event. While in Design View, double-click the button to generate the event handler signature. In the code-behind file, we’ll need to import the System.Net.Mail namespace:

Visual Basic

File: AdminNewsletter.aspx.vb (excerpt)

Imports System.Net.Mail

 

 

 

C#

File: AdminNewsletter.aspx.cs (excerpt)

 

 

using System.Net.Mail;

 

Then, complete the code of sendNewsletterButton_Click to send your newsletter:

Visual Basic File: AdminNewsletter.aspx.vb (excerpt)

Protected Sub sendNewsletterButton_Click( _

ByVal sender As Object, ByVal e As System.EventArgs) _ Handles sendNewsletterButton.Click

Dim smtpClient As SmtpClient = New SmtpClient() Dim message As MailMessage = New MailMessage() ' Try to send the message

Try

' Prepare two email addresses

Dim fromAddress As New MailAddress( _ "newsletter@dorknozzle.com", "Your Friends at Dorknozzle")

Dim toAddress As New MailAddress(toTextBox.Text) ' Prepare the mail message

message.From = fromAddress message.To.Add(toAddress) message.Subject = subjectTextBox.Text message.IsBodyHtml = True message.Body = _

"<html><head><title>" & _ HttpUtility.HtmlEncode(subjectTextBox.Text) & _ "</title></head><body>" & _

"<img src=""http://www.cristiandarie.ro/Dorknozzle" & _ "/Images/newsletter_header.gif"" />" & _

"<p>" & _

HttpUtility.HtmlEncode(introTextBox.Text) & "</p>" & _ "<p>Employee of the month: " & _ HttpUtility.HtmlEncode(employeeTextBox.Text) & "</p>" & _

3 http://www.mikepope.com/blog/DisplayBlog.aspx?permalink=1264

604

Creating the Company Newsletter Page

"<p>This months featured event: " & _ HttpUtility.HtmlEncode(eventTextBox.Text) & "</p>" & _ "</body></html>"

' Set server details smtpClient.Host = "localhost" ' Send the email smtpClient.Send(message)

' Inform the user

resultLabel.Text = "Email sent!<br />" Catch ex As Exception

 

' Display error message

 

resultLabel.Text = "Couldn't send the message!"

 

End Try

End Sub

 

 

C#

File: AdminNewsletter.aspx.cs (excerpt)

 

protected void sendNewsletterButton_Click(

 

object sender, EventArgs e)

{

 

 

SmtpClient smtpClient = new SmtpClient();

 

MailMessage message = new MailMessage();

 

// Try to send the message

 

try

 

{

// Prepare two email addresses

MailAddress fromAddress = new MailAddress( "newsletter@dorknozzle.com", "Your Friends at Dorknozzle" );

MailAddress toAddress = new MailAddress(toTextBox.Text); // Prepare the mail message

message.From = fromAddress; message.To.Add(toAddress); message.Subject = subjectTextBox.Text; message.IsBodyHtml = true; message.Body =

"<html><head><title>" + HttpUtility.HtmlEncode(subjectTextBox.Text) + "</title></head><body>" +

"<img src=\"http://www.cristiandarie.ro/Dorknozzle" + "/Images/newsletter_header.gif\" />" +

"<p>" +

HttpUtility.HtmlEncode(introTextBox.Text) + "</p>" + "<p>Employee of the month: " + HttpUtility.HtmlEncode(employeeTextBox.Text) + "</p>" + "<p>This months featured event: " + HttpUtility.HtmlEncode(eventTextBox.Text) + "</p>" +

605

Chapter 14: Working with Files and Email

"</body></html>";

//Set server details smtpClient.Host = "localhost";

//Send the email smtpClient.Send(message);

//Inform the user

resultLabel.Text = "Email sent!<br />";

}

catch (Exception ex)

{

// Display error message

resultLabel.Text = "Couldn\'t send the message!";

}

}

That’s a pretty large chunk of code, so let’s break it down. Initially, we create a new instance of the MailMessage class, called message:

Visual Basic

File: AdminNewsletter.aspx.vb (excerpt)

Dim message As MailMessage = New MailMessage()

C#

File: AdminNewsletter.aspx.cs (excerpt)

MailMessage message = new MailMessage();

Next, we begin to define the email message by setting some of the properties that the MailMessage class exposes:

Visual Basic File: AdminNewsletter.aspx.vb (excerpt)

' Prepare two email addresses

Dim fromAddress As New MailAddress( _ "newsletter@dorknozzle.com", "Your Friends at Dorknozzle")

 

Dim toAddress As New MailAddress(toTextBox.Text)

 

' Prepare the mail message

 

message.From = fromAddress

 

message.To.Add(toAddress)

 

message.Subject = subjectTextBox.Text

 

message.IsBodyHtml = True

 

 

C#

File: AdminNewsletter.aspx.cs (excerpt)

 

 

 

// Prepare two email addresses

 

MailAddress fromAddress = new MailAddress(

 

"newsletter@dorknozzle.com", "Your Friends at Dorknozzle"

 

);

 

MailAddress toAddress = new MailAddress(toTextBox.Text);

 

// Prepare the mail message

606

Creating the Company Newsletter Page

message.From = fromAddress; message.To.Add(toAddress); message.Subject = subjectTextBox.Text; message.IsBodyHtml = true;

You’ll notice we’ve set the IsBodyHtml property to True because we’re creating an HTML email message. By default, this property is set to False.

Next, we need to create the body of the message, which, essentially, will be an HTML document:

Visual Basic

File: AdminNewsletter.aspx.vb (excerpt)

 

message.Body = _

 

"<html><head><title>" & _

 

HttpUtility.HtmlEncode(subjectTextBox.Text) & _

 

"</title></head><body>" & _

 

"<img src=""http://www.cristiandarie.ro/Dorknozzle" & _

 

"/Images/newsletter_header.gif"" />" & _

 

"<p>" & _

 

HttpUtility.HtmlEncode(introTextBox.Text) & "</p>" & _

 

"<p>Employee of the month: " & _

 

HttpUtility.HtmlEncode(employeeTextBox.Text) & "</p>" & _

 

"<p>This month's featured event: " & _

 

HttpUtility.HtmlEncode(eventTextBox.Text) & "</p>" & _

 

"</body></html>"

 

 

C#

File: AdminNewsletter.aspx.cs (excerpt)

message.Body = "<html><head><title>" +

HttpUtility.HtmlEncode(subjectTextBox.Text) + "</title></head><body>" +

"<img src=\"http://www.cristiandarie.ro/Dorknozzle" + "/Images/newsletter_header.gif\" />" +

"<p>" +

HttpUtility.HtmlEncode(introTextBox.Text) + "</p>" + "<p>Employee of the month: " + HttpUtility.HtmlEncode(employeeTextBox.Text) + "</p>" + "<p>This month's featured event: " + HttpUtility.HtmlEncode(eventTextBox.Text) + "</p>" + "</body></html>";

As we’re building an HTML document, we need to take care to convert special characters (including <, >, and &) into their character entity equivalents (<, >, &, and so on). The HtmlEncode method of the HttpUtility class does this for us.

607

Chapter 14: Working with Files and Email

Also note that the image we’ll use in the email has to be hosted on a site somewhere. In the code above, I’ve used an example URL. To get this example to work properly, you’ll need to host the image on your web site, and use the appropriate URL in your code.

We set the Host property of the smtpClient object to localhost, indicating that the computer that’s acting as our ASP.NET server should also act as our outgoing mail server—you’ll need to change this if you’re using another SMTP server. Finally, we call the Send method, pass in the message object, and display a confirmation message to the user within the resultLabel control:

File: AdminNewsletter.aspx (excerpt)

'Set server details smtpClient.Host = "localhost"

'Send the email smtpClient.Send(message)

'Inform the user

resultLabel.Text = "Email sent!<br />"

File: AdminNewsletter.aspx (excerpt)

//Set server details smtpClient.Host = "localhost";

//Send the email smtpClient.Send(message);

//Inform the user

resultLabel.Text = "Email sent!<br />";

Save your work and run the page in your browser. Enter all the necessary information into the newsletter page and click the Send Newsletter button, as shown in

Figure 14.19.

608

Creating the Company Newsletter Page

Figure 14.19. Sending the newsletter

609