by Grant Harmeyer 
Requirements: ASP.net, Internet Information Services, Visual Studio.NET 2003 (recommended)
As a web developer, at some point in time you are going to have to make an
email address available on a website in one form or another. The
traditional quick and dirty way to accomplish the “publishing” of an
email address on a website is to make the email address a hyperlink
using an HTML anchor tag with the email address specified as the HREF
attribute as shown below:
<a href=mailto: yourname @ yourdomain.com> yourname @ yourdomain.com</a>
This
method of using hyperlinks for email addresses published on websites
worked beautifully until the dawn of web based email services such as
Hotmail, Yahoo! and GMail to name a few. These web based services do
not operate through mail client software, but rather a web browser.
When your website uses mailto and your visitor uses a web based email
service, it is a combination that is a potential frustration for your
visitors. So why not use the same tool that they used to get them there
in the first place? The web browser.
[1.A] The WebForm: Visual
To
accomplish the task of using an alternative to mailto, we must first
create an ASP.NET WebForm that will mimic some functionality of a
standard email composer. We will start by creating a WebForm that will
send a basic text email message. The WebForm will be a combination of
ASP.NET Web Server Controls wrapped up in standard HTML code. The
WebForm will use 4 types of ASP.NET Server Controls:
• System.Web.UI.WebControls.TextBox (4)
• System.Web.UI.WebControls.Button (1)
• System.Web.UI.WebControls.Literal (1)
• System.Web.UI.WebControls.Panel (1)
We’ll
begin by creating the WebForm in Visual Studio® .NET 2003 and position
the above mentioned web controls as shown in the figure below:
You
cannot see them in the diagram above, but the Literal control is placed
between the “Form Mailer” text and the “Your Name” text. This control
is used in notifying the visitor of when their message was sent, or
when an error occurred while attempting to send their message. The
Panel control is used to encapsulate all of the controls that make the
input form. This way, we can toggle visibility of the entire input form
simply by changing the visibility of the Panel rather than the
visibility of each input control.
{mosgoogle}
[1.B] The WebForm: Code
Visual
Studio® .NET 2003 will automatically generate a C# codebehind file for
the WebForm. In the codebehind file we are going to create one method
and one event handler. The method, named SendMessage(), will be used to
attempt sending the email message and report an error if the message is
not able to be sent. The event handler, named
btnSendTextMailMessage_Click(), will be wired to the Button server
control to fire on the Click event of the Button. Our SendMessage()
method will be invoked from inside the Click event handler. Let’s take
a look at our method definition for SendMessage():
When the SendMessage() method is invoked, the following steps are executed:
- A new instance of a MailMessage object is created. This object will be used to compose the email.
- The To, From and Subject properties are all set on the MailMessage
object. The From property is set to the value that the user provides
in the email address TextBox on the WebForm (txtEmailAddress). The Body property of the MailMessage object is set to the string value of
a StringBuilder object. The StringBuilder is used as the proper means
to build a string in pieces “on the fly”. The Body is a compilation
of strings concatenated with the values from the WebForm user input.
- A
try/catch block is constructed to attempt the sending of the message
using the static Send() method that is a member of the
System.Web.Mail.SmtpMail class. It is not necessary to specify the SMTP
server if the web server is running an SMTP service, but it is a good
practice to explicitly name it. If no exception is thrown, the
notification “Message Sent!” is displayed in the Literal control
(ltrNotification) and the method returns a value of true. If an
exception is encountered, the details of the exception are shown in the
Literal and the method returns a value of false.
Now
that we have a method defined to mail the message for us, we need to
somehow invoke the method. To accomplish this, we will invoke
SendMessage() from our btnSendTextMailMessage_Click() event handler.
Event
handlers in C# use a publish/subscribe model. An object publishes an
event that specifies a delegate type. You can then write event handler
methods that match the event handler delegate and subscribe these event
handler methods to the event. All event handler methods subscribed to
an event are invoked when the event is raised. In our scenario, the
delegate for the Click event of our btnSendTextMailMessage control is
defined as having a return type of void and an argument list of
System.Object, System.EventArgs. We now know enough to write our event
handler method as shown below:
What
this event handler accomplishes is rather simple. It toggles the
visibility of the input form. Our SendMessage() method returns a
Boolean value for the success or failure of sending the message, so the
return value of this method is what will be used as the conditional
test to set the Visible property of the Panel control. In order for
this event handler to fire when the button is clicked, it must be
“wired” to the event. When you’re using Visual Studio® .NET 2003, the
event wiring (or subscribing) is done by the forms designer when you
double click the Button control. However, the wiring of an event
handler is a simple line of code:
btnSendTextMailMessage.Click += new System.EventHandler(btnSendTextMailMessage_Click);
This
simply tells the Click event of the btnSendTextMailMessage control to
attach, or subscribe, the btnSendTextMailMessage_Click method to the
event.
Now that we’ve built a simple text mailer, there
are just some small modifications that can be made to this code to send
HTML formatted messages.
[1.C] The WebForm: HTML Formatted
In
order send an HTML formatted message, the body of the mail message must
be an HTML document, but not as an attachment. It’s been my experience
that the easiest way to accomplish this is to use an actual HTML file
as a template and read the template at runtime. In this example, we
have an HTML file named “__EmailMessage.htm”. You can format this HTML
document in any way that you wish such as using inline CSS classes,
font colors, background colors, etc. Inside the HTML code, we are going
to encapsulate the portions of the page with the pound sign (#) that we
would like to be populated by our program. With the pound sign serving
as a delimiting character, we can define a few patterns in the HTML
file to be recognized by our program, and then replace these patterns
with the user input. This is accomplished by using a StreamReader
object to read the HTML file as text into a StringBuilder object. This
will be illustrated more clearly in the next few steps.
In my HTML template, I will use the following patterns for data input by the visitor:
- #VISITOR_NAME#
- #VISITOR_EMAIL#
- #MESSAGE_BODY#
- #MESSAGE_SUBJECT#
Our
event handler for the Click event of the btnSendHtmlMailMessage will
look the same as before. The SendMessage() method will also be much the
same as before, with slight modifications. Instead of using the
StringBuilder object to build the string on the fly using the Append()
method, we are going to read the HTML file into the StringBuilder
object and use the Replace() method to replace occurrances of our
defined string patterns. If you view our HTML file in a web browser, it
will appear as shown below:
Now
that we have constructed our email message template, we need to modify
our SendMessage() method to use this template. The modified
SendMessage() method is shown below:
As
with the text mailer version of the SendMessage() method, a MailMessage
object is created for the email. However, notice that we are now
changing the BodyFormat property of the MailMessage to the enumerated
type MailFormat.Html. Next, we create a new StreamReader object and
read in the HTML file as text to the StringBuilder object. Finally, we
use the StringBuilder object’s Replace() method to replace the string
patterns from our HTML file with the user input. Also note that the
email body and email subject are HTML encoded to ensure proper
formatting in the email viewer. The most appealing point of using an
external HTML file is that you can change the look and format of the
email message by just changing the HTML file without having to touch
your C# code.
Closing
There are a
great number of functions that web applications can use this type of
mailing functionality. Some common functions include contact forms,
such as the ones created here, or using an email to send exception
details to the webmaster. One important thing to remember is that this
is not a substitution for a mail client. This just simply insures that
your visitor can send you an email without having to use a default mail
client.
Also remember to use caution when sending SMTP
messages from an ASP.NET application. This type of functionality
requires that an SMTP server be running on the web server hosting the
application or you must specify an SMTP server that will allow you to
relay SMTP messages. Verify SMTP settings with your web host before
implementing an ASP.NET form mailer such as this, as many web hosts do
not allow SMTP messages because of potential SPAM implications.
Contributed by Grant Harmeyer (click the profile icon to view his bio)
Only registered users can write comments. Please login or register. |