ASP. NET 2.0 email sending Comprehensive Analysis 2

Source: Internet
Author: User
Tags mailmessage smtpclient
I. Introduction

In the previous article, we analyzed in detail ,. net Framework 2.0 provides a new namespace (system. net. mail) and some new email sending classes (Note :. net Framework 1. the namespace system provided in Version X. web. mail and related classes can still be used for backward compatibility ). In addition, we have analyzed in detail how to use the mailmessage and smtpclient classes in the system. net. Mail namespace to send simple e-mail messages in common text format.

This article will discuss more advanced options related to email. We need to analyze how to send HTML-format emails, how to include attachments, and how to handle SMTP exceptions elegantly when sending an email (for example, invalid relay server creden。 or if the relay server is offline ).

This document assumes that you are familiar with sending simple plain text emails from an ASP. NET 2.0 web page. Otherwise, read this series first.Article.

Ii. Send an HTML-format email

When you send an email in ASP. NET 2.0, you can see how to send a normal text email by assigning the email content to the body attribute of the mailmessage class. In fact, to send an HTM-format email, we only need to set the body attribute to the HTML content to be sent, and then set the isbodyhtml attribute of the mailmessage class to true.

To demonstrate how to send an HTML message, I created an example named htmlemail. aspx.CodeAs follows:

'(1) create a mailmessage instance
Dim mm as new mailmessage (fromemailaddress, toemailaddress)
'(2) Assign the attributes of mailmessage
Mm. Subject = "HTML-formatted email demo using the isbodyhtml property"
Mm. body = "<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 = "" color: red; font-weight: bold; ""> pretty colors !! </Span>. </P>"
Mm. isbodyhtml = true
'(3) create an smtpclient object
Dim SMTP as new smtpclient
'(4) Send mailmessage (set using web. config)
SMTP. Send (mm)

As you can see, set the body attribute to the HTML content to be sent, and set the isbodyhtml attribute to true. Now, you have completed all this! The actual email content sent to the relay server (and finally the email client to reach the recipient) looks as follows:

X-Sender: toemailaddress
X-Cycler: fromemailaddress
Mime-type: 1.0
From: fromemailaddress
To: toemailaddress
Date: 25 Jul 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
<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>

Tip: Observe the email content sent to the relay server

It is interesting to observe the actual email content sent to the relay server through the smtpclient class (as shown above), right? In the previous article, we discussed how to configure the smtpclient class to send emails to a relay server or to a specified directory. When using the second option, we can explore the actual email content. You can check the Web. config file in the downloaded code. There is an <SMTP> element with a comment. It shows how to configure the smtpclient class to copy the email content to a specified directory.

This email client (assuming it supports HTML-format emails) will display the HTML content in the email. As shown in.

Tip: Instructions on sending HTML-format emails

When sending an HTML-format email, you must understand that the HTML you see on your screen may be quite different from what your recipient sees. Most email clients "Remove" potentially dangerous HTML content (such as ActiveX controls), and many users stop JavaScript from running.
Iii. Attachment included

The mailmessage class has an attachments attribute, which is a set of attachment class instances. You can append an existing file on the Web server to an email message, or make the content of the Attachment based on a stream ). To show how to use attachments to send emails, I created a demoProgramThe visitor can fill in a feedback form to send an email to the Administrator. However, this feedback form allows visitors to select a file from their computer to attach to emails sent from the web page (this is like a Web-based email program, such as Hotmail and Gmail. When sending an email, they allow you to append a file in your computer ).

To allow visitors to append 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 (newly added by ASP. net2.0. Let's take a look at the declarative syntax used to create user interfaces in this demo:

<Table border = "0">
<Tr>
<TD> <B> your email: </B> </TD>
<TD> <asp: textbox runat = "server" id = "usersemail" columns = "30"> </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 = "55" rows = "10"> </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 an <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 be uploaded and click "send feedback". A mail return occurs, and finally the content of the selected file is sent to the web server. In the "send feedback" button, click event processor to 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 files to the file system of the Web server.

'Make sure you have uploaded a file
If string. isnullorempty (attachmentfile. filename) orelse attachmentfile. postedfile is nothing then
Throw new applicationexception ("Egad, a file wasn' t uploaded... You shoshould probably use more graceful error handling than this, though ...")
End if
'(1) create a mailmessage instance
Dim mm as new mailmessage (fromemailaddress, toemailaddress)
'(2) Assign the attributes of mailmessage
Mm. Subject = "emailing an uploaded file as an attachment Demo"
Mm. Body = body. Text
Mm. isbodyhtml = false
'Additional File
Mm. attachments. Add (new attachment (attachmentfile. postedfile. inputstream, attachmentfile. filename ))
'(3) create an smtpclient object
Dim SMTP as new smtpclient
'(4) Send mailmessage (set using web. config)
SMTP. Send (mm)

In the preceding code example, the overloaded attachment constructor uses two inputs: a reference to stream (which contains the data to be appended) and the name of the attachment to be used. The filename and filename attributes of the fileupload are applied to these two values.

4. Handling SMTP exceptions

What happens if the relay server is disabled when an email is sent from an ASP. NET page? What if the authentication information is invalid? When an SMTP error occurs, the smtpclient class throws an smtpexception. To better handle such problems, we can add exception handling code in the Code for sending emails. If a smtpexception occurs, a more informative error message is displayed.

In the download content of this article, I included a demo that allows visitors to specify the relay server to be used and authentication information. If an error occurs when you try to send an email, a client warning box is displayed to explain the problem. To test this, you can enter an invalid relay server host name or invalid credential for a relay server to be authenticated.

Try
'(1) create a mailmessage instance
Dim mm as new mailmessage (fromemailaddress, toemailaddress)
'(2) Assign the attributes of mailmessage
Mm. Subject = "test email... Do not panic !!! 1 !!! 111 !! "
Mm. Body = "This Is A Test message ..."
Mm. isbodyhtml = false
'(3) create an 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 (set using web. config)
SMTP. Send (mm)
'A client pop-up window is displayed, explaining that the email has been sent
Clientscript. registerstartupscript (Me. GetType (), "himom! ", String. format ("alert ('an test email has successfully been sent to {0} ');", toaddress. replace ("'", "\'"), true)
Catch smtpex as smtpexception
'The problem occurs when an email message is sent.
Clientscript. registerstartupscript (Me. getType (), "ohcrap", String. format ("alert ('There was a problem in sending the Email: {0} ');", smtpex. message. replace ("'", "\'"), true)
Catch generalex as exception
'Other problems
Clientscript. registerstartupscript (Me. getType (), "ohcrap", String. format ("alert ('There was a general problem: {0} ');", generalex. message. replace ("'", "\'"), true)
End try

This code captures SMTP-specific error messages and Common exceptions (for example, assigning an invalid email address to the to or from attribute of the mailmessage object ). In either case, a client warning box is displayed to notify the user of the error details.

V. Conclusion

In this article, we learned how to send HTML-format emails, use attachments to send emails, and elegantly handle exceptions in sending an email message. Sending an HTML-format email is as simple as specifying HTML content in the body attribute and setting the isbodyhtml attribute to true. The real challenge is to ensure that HTML content can be generated as expected on popular email clients. To add an attachment to an email, simply add an attachment object to the attachment set of mailmessage. The data in the attachment can be from a file on the Web server or from a stream. Finally, to handle SMTP-level exceptions, you can add the exception handling code that uses the smtpclient class to capture the exceptions thrown by smtpexception.

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.