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 sending an email in ASP. NET 2.0, we 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:

String fromaddress = "*** @ ***. com ";
// (1) create a mailmessage instance
Mailmessage Mm = new mailmessage (fromaddress, usersemail. Text );
Mm. bodyencoding = system. Text. encoding. getencoding ("gb2312 ");
Mm. subjectencoding = system. Text. encoding. getencoding ("gb2312 ");
// (2) attribute mailmessage value assignment
Mm. Subject = subject. text;
Mm. Body = "<B> bold </B> ";
Mm. isbodyhtml = true;
// (3) create an smtpclient object
Smtpclient SMTP = new smtpclient ();
// (4) Send mailmessage (Web. config settings will be used)
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:

Bold

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 code in this article. 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:

<Form ID = "form1" runat = "server">
<Div>
<Table border = "0">
<Tr>
<TD>
<B> to email: </B>
</TD>
<TD>
<Asp: textbox runat = "server" id = "usersemail" columns = "30"> </ASP: textbox>
</TD>
</Tr>
<Tr>
<TD>
<B> subject: </B>
</TD>
<TD>
<Asp: textbox runat = "server" id = "subject" columns = "30">
</ASP: textbox>
</TD>
</Tr>
<Tr>
<TD>
<Strong> attachment: </strong> </TD>
<TD>
<Asp: fileupload id = "fileupload1" 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" onclick = "sendemail_click"/>
</TD>
</Tr>
</Table>
</Div>
</Form>

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.

string fromaddress = "***@***. com ";
// (1) create a mailmessage instance
mailmessage Mm = new mailmessage (fromaddress, usersemail. text);
MM. bodyencoding = system. text. encoding. getencoding ("gb2312");
MM. subjectencoding = system. text. encoding. getencoding ("gb2312");
// (2) attribute mailmessage value assignment
MM. subject = subject. text;
MM. body = " bold ";
MM. isbodyhtml = true;
MM. attachments. add (new attachment (fileupload1.postedfile. inputstream, fileupload1.filename);
// (3) create an smtpclient object
smtpclient SMTP = new smtpclient ();
// (4) send mailmessage (the web. config settings)
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
{
String fromaddress = "*** @ ***. com ";
// (1) create a mailmessage instance
Mailmessage Mm = new mailmessage (fromaddress, usersemail. Text );
Mm. bodyencoding = system. Text. encoding. getencoding ("gb2312 ");
Mm. subjectencoding = system. Text. encoding. getencoding ("gb2312 ");
// (2) attribute mailmessage value assignment
Mm. Subject = subject. text;
Mm. Body = "<B> bold </B> ";
Mm. isbodyhtml = true;
Mm. attachments. Add (new attachment (fileupload1.postedfile. inputstream, fileupload1.filename ));
// (3) create an smtpclient object
Smtpclient SMTP = new smtpclient ();
// (4) Send mailmessage (Web. config settings will be used)
SMTP. Send (mm );
}
Catch (smtpexception smtper)
{
Response. write (string. format ("<script language = 'javascript '> alert ('There was a problem in sending the Email: {0}') </SCRIPT>", smtper. message ));
}
Catch (exception ERR)
{
Response. write (string. format ("<script language = 'javascript '> alert ('There was a general problem: {0}') </SCRIPT>", err. message ));
}

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, send emails using attachments, 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.