asp.net 2.0 send e-mail comprehensive analysis of the second

Source: Internet
Author: User
Tags format config error handling exception handling file system include sorts mailmessage
asp.net

   First, Introduction

In the last chapter, we analyzed in detail. Net Framework version 2.0 provides a new namespace (System.Net.Mail) and some new classes for sending e-mail messages (note:. NET Framework the namespace System.Web.Mail and related classes provided in the 1.x version are still available for backward compatibility. Also, we have analyzed in detail how to use the MailMessage and SmtpClient classes in the System.Net.Mail namespace to send e-mail messages in simple plain text format.

This article will discuss more advanced options related to e-mail. We want to analyze how to send e-mail in HTML format, how to include attachments, and how to gracefully handle SMTP exceptions when sending an e-mail message (such as invalid relay server credentials or if the relay server is offline).

This article assumes that you are already familiar with sending simple plain text emails from a asp.net 2.0 Web page, otherwise please read the previous article in this series first.

   e-mail sent in HTML format

When sending an e-mail message in asp.net 2.0, we have seen how to send an ordinary text e-mail message by assigning the content of the e-mail message to the Body property of the MailMessage class. In fact, in order to send an e-mail in HTM format, we simply set the Body property to the HTML content to send, and then set the MailMessage class's Isbodyhtml property to True.

To demonstrate how to send an HTML-formatted message, I created an example with the name htmlemail.aspx. The code is as follows:

' (1) Create MailMessage instance
Dim mm as New mailmessage (fromemailaddress, toemailaddress)
' (2) properties of the assigned MailMessage
Mm. Subject = "html-formatted Email Demo Using the Isbodyhtml property"
Mm. BODY = "This is a html-formatted Email Send Using the <code> isbodyhtml </code> property <p> Isn ' t HTML <em> neat</em The </p> <p> You can make all sorts of <span style= "" Color:red;font-weight:bold; "" >pretty colors!! </span>. </p> "
Mm. isbodyhtml = True
' (3) Create SmtpClient Object
Dim SMTP as New smtpclient
' (4) Send MailMessage (will use Web.config settings)
Smtp. Send (mm)
As you can see, simply set the Body property to the HTML content to send, and set the Isbodyhtml property to True. So far, all this you have done! The actual e-mail content that is sent to the relay server (and finally to the recipient's e-mail client) looks like this:

X-sender:toemailaddress
X-receiver:fromemailaddress
mime-version:1.0
From:fromemailaddress
To:toemailaddress
Date:25 June 2006 15:06:44-0700
subject:html-formatted Email Demo Using the Isbodyhtml property
content-type:text/html; Charset=us-ascii
Content-transfer-encoding:quoted-printable
This is a html-formatted Email Send Using the <code> isbodyhtml </code> =
Property <p> Isn ' t HTML <em> neat </em>? </p> <p> You can do all sorts=
of <span style=3d "color:red;font-weight:bold;" >pretty colors!! </span>. </p>

Tip: Observe the e-mail content sent to the relay server

It is interesting to observe the actual email content sent to the relay server via the SmtpClient class (as above), right? In the previous article, we discussed how to configure the SmtpClient class to send e-mail to a relay server or to put it into a specified directory. When we use the second option, we can explore the actual e-mail content. You can check the web.config file in the download code for this article. Among them, there is an annotated <smtp> element that shows how to configure the SmtpClient class to copy the contents of an e-mail message to a specified directory.

The e-mail client (assuming it supports HTML-formatted e-mail) will display the HTML content in an e-mail message. As shown in the following figure.


Tip: Instructions for sending an e-mail message in HTML format

When sending HTML-formatted emails, it is important to understand that the HTML you see on your screen may be quite different from what your recipients see. Most e-mail clients "eliminate" potentially dangerous HTML content, such as ActiveX controls, and many users prevent JavaScript from running.

   third, including annex

The MailMessage class has a attachments property, which is a collection of attachment class instances. You can attach an existing file on the Web server to an e-mail message or base the contents of the attachment on a stream (stream). To demonstrate the use of attachments to send e-mail, I created a demo program in which visitors can populate a form of feedback to send an email to an administrator. However, this feedback form allows visitors to select a file from their computer to attach to an e-mail message sent from the Web page (this is much like a web-based e-mail program, such as Hotmail,gmail, etc.). When sending an email, they allow you to attach a file from your computer.

To allow visitors to attach a file from their computer, we need to allow the user to upload a file from their computer to the Web server. This can be easily implemented using the FileUpload control, which is newly added by asp.net2.0. Let's take a look at the declarative syntax that this demo program uses to create user interfaces:

<table border= "0" >
<tr>
<td> <b> Your Email: </b> </td>
<td> <asp:textbox runat= "Server" id= "Usersemail" columns= "" </asp:TextBox> </td>
</tr>
<tr>
<td> <b> File to Send: </b> </td>
<td>
<asp:fileupload id= "Attachmentfile" runat= "Server"/>
</td>
</tr>
<tr>
<TD colspan= "2" >
<b> Body: </b> <BR/>
<asp:textbox runat= "Server" id= "Body" textmode= "MultiLine" columns= "a" rows= "ten" > </asp:TextBox>
</td>
</tr>
<tr>
<TD colspan= "2" align= "center"
<asp:button runat= "Server" id= "SendEmail" text= "Send Feedback"/>
</td>
</tr>
</table>
This fileupload control generates a <input type= "file" .../>html element, which is displayed as a text box with a browse button in the browser. When clicked, a dialog box opens so that users can select a file from their computer.


After filling in the feedback form, select a file to upload, and click the "Send Feedback" button, then a postback occurs, and finally the contents of the selection file sent to the Web server. In the Click event Processor of the Send Feedback button, create a MailMessage object and add an attachment. Since the FileUpload provides a stream to upload data, we can simply point to the new Attachment object in this stream. We do not need to save the uploaded file to the Web server's file system.

' Make sure you've uploaded a file
If String.IsNullOrEmpty (attachmentfile.filename) OrElse attachmentfile.postedfile is nothing Then
Throw New applicationexception ("Egad, a file wasn ' t uploaded ..." should probably use more graceful error handling This, though ... ")
End If
' (1) Create MailMessage instance
Dim mm as New mailmessage (fromemailaddress, toemailaddress)
' (2) properties of the assigned MailMessage
Mm. Subject = "Emailing an uploaded File as a attachment Demo"
Mm. BODY = Body.text
Mm. isbodyhtml = False
' Attach File
Mm. Attachments.Add (New attachment (AttachmentFile.PostedFile.InputStream, attachmentfile.filename))
' (3) Create SmtpClient Object
Dim SMTP as New smtpclient
' (4) Send MailMessage (will use Web.config settings)
Smtp. Send (mm)
The overloaded attachment constructor in the preceding code example uses two inputs: a reference to the stream (which contains the data to append), and the name of the attachment to use. The filename and filename properties of the FileUpload are applied to both values.

   iv. Handling SMTP Exceptions

What happens if the relay server shuts down when you send an e-mail message from a asp.net page? What happens if the authentication information is not used? When an SMTP error occurs, the SmtpClient class throws a Smtpexception exception. To better handle such problems, we can include exception handling code in the code that sends the e-mail. If a smtpexception appears, we are able to display a more friendly informational error hint.

For the downloads in this article, I include a demo that allows visitors to specify the relay server to use and the authentication information. If there is an error while trying to send an e-mail message, a client warning box will be displayed to explain the problem. To test this, you can enter an invalid relay server hostname or invalid credentials for a relay server that requires authentication.

Try
' (1) Create MailMessage instance
Dim mm as New mailmessage (fromemailaddress, toemailaddress)
' (2) properties of the assigned MailMessage
Mm. Subject = "Test Email ... Do NOT PANIC!!! 1!!! 111!! "
Mm. BODY = ' This is ' a test message ... '
Mm. isbodyhtml = False
' (3) Create SmtpClient Object
Dim SMTP as New smtpclient
' SMTP Settings ...
Smtp. Host = Hostname.text
If not String.IsNullOrEmpty (port.text) Then
Smtp. Port = Convert.ToInt32 (Port.text)
End If
If not String.IsNullOrEmpty (username.text) Then
Smtp. Credentials = New NetworkCredential (username.text, Password.text)
End If
' (4) Send MailMessage (will use Web.config settings)
Smtp. Send (mm)
' Displays a client pop-up window explaining that the message has been sent
Clientscript.registerstartupscript (Me.GetType (), "himom!", String.Format ("Alert" (' An test email has successfully Sent to {0} '); ", Toaddress.replace (" "," \ "), True)
Catch Smtpex as Smtpexception
' A problem occurred while sending an e-mail message
Clientscript.registerstartupscript (Me.GetType (), "Ohcrap", String.Format ("Alert" (' There is a problem in sending the Email: {0} '); ", SmtpEx.Message.Replace (" "," \ "), True)
Catch Generalex as Exception
' There are some other problems
Clientscript.registerstartupscript (Me.GetType (), "Ohcrap", String.Format ("alert (' There is general problem: {0} ');" , GeneralEx.Message.Replace ("'", "\")), True)
End Try
This code captures SMTP-specific error messages and common exceptions, such as assigning an invalid e-mail address to the to or from property of a MailMessage object. In either case, a client warning box is displayed to notify the user of details about the error.


   v. Conclusion

In this article, we learned how to send an HTML-formatted e-mail message, send an e-mail message using an attachment, and gracefully handle the exception that occurred in sending an e-mail message. Sending an HTML-formatted e-mail message is like specifying the HTML content in the Body property and simply setting the Isbodyhtml property to True. The real challenge is to make sure that HTML content is generated as expected in the popular e-mail client. In order to add an attachment to an e-mail message, simply add a attachment object to the MailMessage attachment collection. The appropriate data for the attachment can come from a file on the Web server or from a stream. Finally, to handle SMTP-level exceptions, you can add exception handling code that uses the SmtpClient class to catch smtpexception throws.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.