Sending Email in ASP.NET 2.0
(Taken from: http://aspnet.4guysfromrolla.com/articles/072606-1.aspx)
Email serves as a ubiquitous, asynchronous notification and information distribution system. Not surprisingly, there are many web development scenarios where server-side code needs to generate an email and scuttle it off to the intended recipient. The email may be destined for a user of the website, informing them of their newly created user account, reminding them of their forgotten password, or emailing them an invoice. Or it may be destined for a web developer or site administrator, providing information of an unhandled exception that just transpired or user feedback.
Fortunately, ASP.NET makes sending email a breeze. The .NET Framework version 1.x included a number of classes in the
System.Web.Mail class that allowed programmatically sending an email with a few scant lines of code. While this namespace and these classes still exist in the .NET Framework version 2.0, they have been deprecated in favor of new mail-related classes found in the
System.Net.Mail namespace. (For an article on sending email in ASP.NET version 1.x, see Sending Email from an ASP.NET 1.x Web Page or consult www.SystemWebMail.com.)
In this article we’ll look at the classes in the
System.Net.Mail namespace and see how to send an email from an ASP.NET 2.0 page’s code-behind class. We’ll also look at specifying relay server information in
Web.config and how this information can be used in some of the built-in ASP.NET server controls for sending emails (such as when a user creates an account or needs a password reminder/reset). Read on to learn more!
Exploring the Classes in the
There are 16 different classes in the
System.Net.Mail namespace, all related to send email to a specified Simple Mail Transfer Protocol (SMTP) server for delivery. The two core classes in this namespace are:
MailMessage– represents an email message; has properties like
Body, and so on.
SmtpClient– sends a specified
MailMessageinstance to a specified SMTP server.
When sending an email from an ASP.NET 2.0 page you will, typically:
- Create a
- Assign its properties
- Create an instance of the
- Specify details about the SMTP server to use (if they’re not already specified within
- Send the
Steps 1 and 2 may be bypassed as the
Send method can accept either a
MailMessage object or four strings, representing the from, to, subject, and body contents of the email message.
System.Net.Mail namespace’s other classes allow for more advanced email functionality. There are classes that can be used to add attachments to an email message, to embed objects within an email, to specify SMTP server authentication information, and
Exception-derived classes for handling SMTP-specific exceptions. We’ll examine using some of these other classes for more advanced scenarios in future articles.
Providing the SMTP Server’s Details
When sending an email to a friend from Outlook or GMail, the email program establishes a connection with a relay server and sends the contents of the email message, along with information such as the date the email was composed, the email body’s format (text or HTML, for example), the recipient(s), and so on. The relay server accepts the message and then connects to the recipient’s SMTP server and sends the message. Once the message has been delivered, the recipient can, at some later point in time, pull down the message using a different protocol (such as IMAP or POP3).
Therefore, to send an email from an ASP.NET page we need to provide the
SmtpClient class with information about the relay server. Along with the hostname of the relay server, you can specify the port (typically port 25 is used), whether or not to use SSL when communicating your email message contents to the relay server, and authentication credentials (if necessary). Alternatively, if you have a local SMTP service installed on your web server, it may periodically monitor a particular “drop-off” directory, sending any messages that appear in that directory. You can configure whether the
SmtpClient class relays its email messages to a separate relay server or if it drops it off in a specified pickup directory through the
The relay server information used by the
SmtpClient class can be specified programmatically, through the
SmtpClient class’s properties, or can be centralized in
Web.config. To use the
Web.config approach, add a
<system.net> element within the
<configuration> element. Then, add a
<mailSettings> element that contains an
<smtp> element whose settings are specified within its
<network> child element, like so:
<configuration> <!-- Add the email settings to the <system.net> element --> <system.net> <mailSettings> <smtp> <network host="relayServerHostname" port="portNumber" userName="username" password="password" /> </smtp> </mailSettings> </system.net> <system.web> ... </system.web> </configuration>
host attribute contains the relayServerHostname. If you are using an external relay server, the relayServerHostname might be something like
smtp.yourisp.com. If the relay server’s port number is something other than the typical port 25, specify it through the
port attribute. Most external relay servers require authentication of some sort (in order to prevent anonymous spammers from sending their garbage through the relay). The
password attributes can be provided in the case where username/password authentication is needed.
Only a subset of the
SmtpClient properties can be specified through settings in
Web.config. To customize the other
SmtpClient properties –
Timeout, and so on – set them programmatically when sending the email (step 4 from the list of five steps examined earlier in this article).
Sending an Administrator Email Through a Feedback Web Page
To illustrate sending an email using the
SmtpClient classes, I’ve created a simple feedback page example. In this page the user is prompted for their email address, the subject of their feedback, and their feedback.
Once the user has supplied the feedback information and clicked the “Send Feedback” button, a postback ensues and the Button’s
Click event fires. Inside the event handler, a
MailMessage object is created and its
Body properties are set according to the information provided by the user. With the
MailMessage object created and its properties populated, the email is then sent through the
We didn’t need to set any of the
SmtpClient class’s properties here in code because they have been specified in
Web.config (download the complete code at the end of this article to run this application on your computer).
Along with a plethora of other improvements from ASP.NET 1.x, the email sending capabilities in ASP.NET 2.0 have been updated and moved to a new namespace,
System.Net.Mail. In 2.0 the relay server settings can easily be decoupled from the ASP.NET code and moved into the
Web.config file, as we saw in this example. Moreover, there’s better support for relay server authentication. Future articles will explore more advanced email scenarios, such as: crafting HTML-formatted emails, sending attachments, embedding objects within the email body, handling SMTP/relay server-related exceptions, and so on.
Sending Email in ASP.NET 2.0: HTML-Formatted Emails, Attachments, and Gracefully Handling SMTP Exceptions
(Taken from: http://aspnet.4guysfromrolla.com/articles/080206-1.aspx)
The .NET Framework version 2.0 includes a new namespace (
System.Net.Mail) and new classes for sending email. (The namespace (
System.Web.Mail) and classes used in the .NET Framework version 1.x still exist for backwards compatibility.) Last week we examined how to use the
SmtpClient classes in the
System.Net.Mail namespace for sending simple, plain-text email messages.
This article looks at the more advanced email-related options. We’ll see how to send HTML-formatted emails, how to include attachments, and how to gracefully handle SMTP exceptions when sending an email (such as invalid relay server credentials or if the relay server is offline). Read on to learn more!
Sending HTML-Formatted Emails
In Sending Email in ASP.NET 2.0 we saw how to send plain-text emails by assigning the contents of the email to the
Body property. To send HTML-formatted emails, simply set the
Body property to the HTML content to send, and then mark the
IsBodyHtml property to True.
To demonstrate sending an HTML-formatted message, I created a sample named
HtmlEmail.aspx available for download at the end of this article. The germane code follows:
As you can see, simply set the
Body property to the HTML content to send and the
IsBodyHtml property to True, and you’re done! The actual email content that gets sent to the relay server (and eventually down to the recipient’s email client), looks something like the following:
date: 25 Jul 2006 15:06:44 -0700
subject: HTML-Formatted Email Demo Using the IsBodyHtml Property
content-type: text/html; charset=us-ascii
<h2>This is an HTML-Formatted Email Send Using the <code>IsBodyHtml</code>=
Property</h2><p>Isn't HTML <em>neat</em>?</p><p>You can make all sorts=
of <span style=3D"color:red;font-weight:bold;">pretty colors!!</span>.</p>
Viewing the Email Content Sent to the Relay Server
Interested in viewing the actual content sent to the relay server by the
The email client – assuming it supports HTML-formatted emails – will display the HTML content within the email.
Caveats on Sending HTML-Formatted Emails
MailMessage class has an
Attachments property that is a collection of
Attachment class instances. You can attach an existing file on the web server to the email message or base the content’s attachment on a Stream. To illustrate sending emails will attachments, I created a demo where the visitor can fill out a feedback-like form to have an email sent to administrator. However, this feedback form allows the visitor to pick a file from their computer to be attached to the email sent from the web page (much like how the web-based email web applications – Hotmail, GMail, etc. – allow you to attach a file from your computer when sending an email).
To allow the visitor to attach a file from their computer, we need to allow the user to upload a file from their machine to the web server. This can be easily accomplished using the FileUpload control (which is new to ASP.NET 2.0). Let’s look at the declarative syntax used for creating the user interface for this demo:
The FileUpload control renders as a
<input type="file" ... /> HTML element, which, in the browser, is displayed as a textbox with a Browse button. When clicked, a dialog box is opened from which the user can pick a file from their computer.
After filling in the feedback form, selecting a file to upload, and clicking the “Send Feedback” button, a postback occurs, sending the contents of the selected file up to the web server. In the “Send Feedback” Button’s
Click event handler, a
MailMessage object is created and an attachment is added. Since the FileUpload provides a Stream to the uploaded data, we can simply point the new
Attachment object at this Stream. There’s no need to save the uploaded file to the web server’s file system.
Attachment constructor overload used in the code sample above expects two inputs: a reference to the Stream that contains the data to attach, and the name to use for the attachment. The FileUpload’s
FileName properties are used for these two values.
Handling SMTP Exceptions
When sending an email from an ASP.NET page, what happens if the relay server is down, or if the authentication information used is invalid? In the face of an SMTP error, the
SmtpClient class will throw an
SmtpException exception. To gracefully handle such problems, we can add exception handling code around the code that sends the email. If there’s an
SmtpException we can then display a more friendly and informative error message (or, perhaps, write the email’s contents to a file to be sent later).
In the download at the end of this article I’ve included a demo that allows the visitor to specify the relay server to use, along with authentication information. If there’s an error in attempting to send an email, a client-side alert box is displayed, explaining the problem. To test this out, enter an invalid relay server hostname or invalid credentials for a relay server that requires authentication.
This code catches both SMTP-specific error messages and general ones (such as assigning invalid email addresses to the
From properties). In either case, a client-side alert box is displayed informing the user of the details of the error.
In this article we saw how to send HTML-formatted emails, send emails with attachments, and gracefully handle exceptions arising from sending an email message. Sending an HTML-formatted email is as simple as specifying the HTML content in the
Body property and setting the
IsBodyHtml property to True. The real challenge comes in making sure the HTML content used is rendered as expected by the popular email clients. To add an attachment to an email, simply add an
Attachment object to the
Attachments collection. The data for the attachment can come from a file on the web server or from a Stream. Finally, to handle SMTP-level exceptions, add exception handling code that catches the
SmtpException thrown by the
SmtpClient class when unable to transport the message to the relay server.