明輝手游網(wǎng)中心:是一個(gè)免費(fèi)提供流行視頻軟件教程、在線學(xué)習(xí)分享的學(xué)習(xí)平臺(tái)!

在.NET 應(yīng)用程序中用System.Web.Mail 發(fā)送電子郵件

[摘要]作者:Mark Strawmyer日期:February 9, 2004 歡迎來(lái)到 .NET Nuts & Bolts 欄目。在這個(gè)欄目中,我們將探討怎樣在應(yīng)用中發(fā)送電子郵件。這將用到System.Web.Mail 名字空間中的類(lèi)。協(xié)作數(shù)據(jù)對(duì)象Windows 2000 協(xié)作數(shù)據(jù)對(duì)象 (CD...


作者:Mark Strawmyer
日期:February 9, 2004
 
歡迎來(lái)到 .NET Nuts & Bolts 欄目。在這個(gè)欄目中,我們將探討怎樣在應(yīng)用中發(fā)送電子郵件。這將用到System.Web.Mail 名字空間中的類(lèi)。

協(xié)作數(shù)據(jù)對(duì)象
Windows 2000 協(xié)作數(shù)據(jù)對(duì)象 (CDOSYS) 是微軟用來(lái)創(chuàng)建和發(fā)送基于標(biāo)準(zhǔn)的電子郵件信息的消息組件。它是 用與 Windows NT的協(xié)作數(shù)據(jù)對(duì)象(CDONTS) 的替代物。 盡管由于向后兼容的原因 CDONTS 已包含在 Windows 2000 中, 但是 Windows XP, Windows Server 2003 以及更高版本均未包含或支持 CDONTS 組件。 所以任何使用 CDONTS 發(fā)送消息的應(yīng)用程序都必須遷移到使用 CDOSYS 上來(lái)。它提供了相同的功能,而且易于使用。

除了作為替代物外, CDOSYS 還引入了一些 CDONTS 中沒(méi)有的功能,如:

向新聞組發(fā)送消息的能力
對(duì)消息的 MIME 體結(jié)構(gòu)的控制
接收和轉(zhuǎn)發(fā)機(jī)制
傳輸事件接受池以便對(duì)事件作出響應(yīng)
System.Web.Mail 命名空間包含了與 CDOSYS 組件交互從而創(chuàng)建和發(fā)送信息的類(lèi)。

使用互聯(lián)網(wǎng)信息服務(wù)(IIS)和 SMTP 服務(wù)
為了能從應(yīng)用程序中利用 CDOSYS 發(fā)送電子郵件,您必須確認(rèn) IIS 服務(wù)列表中已經(jīng)安裝了SMTP 服務(wù)。在 Windows 2000/XP中,您可以通過(guò)控制面板 -> 添加/刪除程序 -> 添加/刪除 Windows 組件選項(xiàng)來(lái)設(shè)置。STMP 服務(wù)的任務(wù)就是基于配置接收和發(fā)送消息。這個(gè)服務(wù)可以直接投遞消息,也可以使用代理服務(wù)器來(lái)發(fā)送消息。當(dāng)代理服務(wù)器已配置時(shí),所有的消息將轉(zhuǎn)發(fā)給它以備發(fā)送。你必須確保 IIS 和 SMTP 服務(wù)正確的安裝和配置好。

在投遞之前,SMTP 服務(wù)使用一個(gè)目錄結(jié)構(gòu)來(lái)保存消息。默認(rèn)的目錄為C:\Inetpub\mailroot。這個(gè)文件夾中包含了一些子目錄,如:Queue, Drop, Badmail。 如果你無(wú)法配置SMTP服務(wù)實(shí)例以便發(fā)送的話,您將可以在目錄 C:\Inetpub\mailroot\Queue 中的 *.EML 文件中找到郵件。這個(gè)技巧在離線創(chuàng)建郵件時(shí)將很有用。

發(fā)送消息
正如前面提到的,發(fā)送電子郵件將是一件相對(duì)簡(jiǎn)單的事。類(lèi) System.Web.Mail.MailMessage class 代表了將要發(fā)送的消息。E-mail 消息將由該類(lèi)的實(shí)例來(lái)創(chuàng)建。這個(gè)類(lèi)包含了諸如:收件人,發(fā)件人和主題等屬性來(lái)讓你控制想要發(fā)送的消息。還可以使用類(lèi) System.Web.Mail.MailAttachment 的實(shí)例創(chuàng)建附件,然后添加到 MailMessage 的 Attachments (附件)集合中。隨后該消息將由 類(lèi)System.Web.Mail.SmtpMail 發(fā)送出去。

發(fā)送郵件示例代碼
下面的 C# 示例代碼將包含一個(gè)演示如何發(fā)送簡(jiǎn)單電子郵件的 Windows 控制臺(tái)程序。當(dāng)沒(méi)有設(shè)置 SmtpMail 的 SmtpServer 屬性時(shí),本地機(jī)器將為其默認(rèn)配置。你必須確保添加了針對(duì) System.Web.dll 的引用,因?yàn)樗强刂婆_(tái)應(yīng)用程序而不是 ASP.NET 應(yīng)用。

using System;
using System.Web.Mail;

namespace CodeGuru.SendMail
{
  /// <summary>
  /// Test console application to demonstrate sending e-mail.
  /// </summary>
  class TestMail
  {
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
      TestMail.Send("testuser@codeguru.com",
                    "mstrawmyer@crowechizek.com",
                    "Test Message Using CDOSYS",
                    "Hello World!  This is a simple message sent
                     using CDOSYS.");
    }

    /// <summary>
    /// Send a message using the .NET wrapper for Collaborative Data
    /// Objects (CDO).  This method should be used when sending to a
    /// single recipient only; otherwise, the list of recipients
    /// will be known.
    /// </summary>
    /// <param name="MessageFrom">Message originator</param>
    /// <param name="MessageTo">Message receipent</param>
    /// <param name="MessageSubject">Message subject</param>
    /// <param name="MessageBody">Message body</param>
    public static void Send(string MessageFrom,
                            string MessageTo,
                            string MessageSubject,
                            string MessageBody)
    {
      MailMessage message = new MailMessage();
      message.From        = MessageFrom;
      message.To          = MessageTo;
      message.Subject     = MessageSubject;
      message.BodyFormat  = MailFormat.Text;
      message.Body        = MessageBody;

      try
      {
        System.Console.WriteLine("Sending outgoing message");
        SmtpMail.Send(message);
      }
      catch( System.Web.HttpException exHttp )
      {
        System.Console.WriteLine("Exception occurred:" +
                                 exHttp.Message);
      }
    }
  }
}

發(fā)送帶有附件的郵件示例代碼
下面的 C# 示例代碼將包含一個(gè)演示如何發(fā)送帶有附件的電子郵件的 Windows 控制臺(tái)程序。這將由創(chuàng)建類(lèi) MessageAttachment 的實(shí)例,然后將其添加到 Attachments 集合來(lái)完成。

using System;
using System.Web.Mail;

namespace CodeGuru.SendMail
{
  /// <summary>
  /// console application to demonstrate sending e-mail with an
  /// attachment.
  /// </summary>
  class TestMail
  {
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
      TestMail.SendAttachment("testuser@codeguru.com",
                              "mstrawmyer@crowechizek.com",
                              "Test Message Using CDOSYS",
                              "Hello World!  This is a simple
                               message sent using CDOSYS.",
                              "c:\\myattachment.txt");
    }

    /// <summary>
    /// Send a message using the .NET wrapper for Collaborative Data
    /// Objects (CDO).  This method should be used when sending to
    /// a single recipient only; otherwise, the list of recipients
    /// will be known.
    /// </summary>
    /// <param name="MessageFrom">Message originator</param>
    /// <param name="MessageTo">Message receipent</param>
    /// <param name="MessageSubject">Message subject</param>
    /// <param name="MessageBody">Message body</param>
    /// <param name="MessageAttachmentPath">Path to attachment
    /// </param>
    public static void SendAttachment(string MessageFrom,
                                      string MessageTo,
                                      string MessageSubject,
                                      string MessageBody,
                                      string MessageAttachmentPath)
    {
      // Create and setup the message
      MailMessage message = new MailMessage();
      message.From        = MessageFrom;
      message.To          = MessageTo;
      message.Subject     = MessageSubject;
      message.BodyFormat  = MailFormat.Text;
      message.Body        = MessageBody;

      // Create and add the attachment
      MailAttachment attachment = new
          MailAttachment(MessageAttachmentPath);
      message.Attachments.Add(attachment);

      try
      {
        // Deliver the message
        System.Console.WriteLine("Sending outgoing message");
        SmtpMail.Send(message);
      }
      catch( System.Web.HttpException exHttp )
      {
        System.Console.WriteLine("Exception occurred:" +
                                 exHttp.Message);
      }
    }
  }
}

可能的改進(jìn)
我們已經(jīng)從不同途徑演示了如何發(fā)送電子郵件。現(xiàn)在輪到你想想如何在你的應(yīng)用程序中應(yīng)用這項(xiàng)功能了。這里有一些想法和你共同分享:

E-mail 警告—當(dāng)一個(gè)致命的或無(wú)法恢復(fù)的應(yīng)用程序錯(cuò)誤發(fā)生時(shí),您的應(yīng)用程序可以發(fā)送電子郵件到一指定地址以使其能很快得知。
創(chuàng)建一個(gè)基于Web的聯(lián)系消息窗體—你可以使用戶(hù)通過(guò)填寫(xiě) Web 表單來(lái)發(fā)送用戶(hù)反饋,然后編寫(xiě)相關(guān)程序把消息發(fā)送給適當(dāng)?shù)穆?lián)系人。
訂閱服務(wù)—當(dāng)通過(guò) CDOSYS 組件發(fā)送電子郵件來(lái)支持訂閱類(lèi)型的服務(wù)時(shí),您將需要發(fā)送多封郵件而不是單一郵件給所有的接收者。當(dāng)一則消息擁有大量的接收者時(shí),處理所有的接收者將戲劇性地減滿處理速度。這時(shí)候您最好將接收者列表分解成多個(gè)列表,分好幾次發(fā)送消息。
使用 Bcc 發(fā)送消息—當(dāng)通過(guò) CDOSYS 組件發(fā)送電子郵件來(lái)支持訂閱類(lèi)型的服務(wù)時(shí),您也許想要使用 Bcc 而不是 To 來(lái)填寫(xiě)接收人地址。這樣可以使得所有接收者無(wú)法得知接收者列表。
發(fā)送 HTML 格式的郵件—消息主體格式可以是 HTML。它可以使消息主體以 HTML 格式發(fā)送而不是普通文本。
-----------------------------------------------------------

原文:

 
Sending E-Mail with System.Web.Mail


 Mark Strawmyer (view profile)
February 9, 2004
Rating: not yet rated 

 

--------------------------------------------------------------------------------

 

Welcome to the next installment of the .NET Nuts & Bolts column. In this column, we'll explore sending e-mail from within applications. This will involve utilizing classes contained in the System.Web.Mail namespace.

Collaboration Data Objects
Collaboration Data Objects for Windows 2000 (CDOSYS) is a Microsoft messaging component that allows for standards-based e-mail messages to be constructed and sent. It is a replacement of the Collaboration Data Objects for NTS (CDONTS), which, as you can probably guess by the name, was for Windows NT. CDONTS is included with Windows 2000 for backwards compatibility, but Windows XP, Windows Server 2003, and beyond do not include or support the use of CDONTS. Thus, any applications that send messages using CDONTS must be migrated to use CDOSYS. It provides the same functionality and is just as easy to use.

In addition to serving as a replacement, CDOSYS introduces some new functionality that was not previously available in CDONTS. Some of the functionality includes:

Ability to post messages to newsgroups
Control of MIME body structure for messages
Reply and forward functionality
Transport event sink to allow responding to events
The System.Web.Mail namespace contains classes that interact with CDOSYS to construct and send the message(s).

Using IIS and SMTP Service
In order for CDOSYS to send e-mail or other messages from your application, you need to enlist the services of IIS with the SMTP Service installed. Both are available in Windows 2000/XP through the Control Panel -> Add/Remove Programs -> Add/Remove Windows Components option. The job of the STMP Service is to accept and deliver the messages, based on the configuration. The service can attempt to deliver the messages directly, or it can utilize a smart host to deliver the message instead. When a smart host is enlisted, all messages are forwarded to it for delivery. You need to have IIS and the SMTP service installed and configured.

The SMTP Service uses a directory structure to contain messages prior to delivery. The default directory is C:\Inetpub\mailroot. This folder contains a number of subdirectories such as Queue, Drop, and Badmail. If you are unable to configure your instance of the SMTP Service for delivery, you can find the message in a *.EML file in the C:\Inetpub\mailroot\Queue directory. This technique can be useful when creating messages offline.

Sending a Message
As previously mentioned, sending an e-mail is a relatively simple thing to do. The System.Web.Mail.MailMessage class represents the message to be sent. E-mail messages are constructed by using instances of this class. This class contains properties such as To, From, and Subject that allow you to control the message being sent. Attachments can be created through instances of the System.Web.Mail.MailAttachment and then added to the MailMessage through the Attachments collection of the MailMessage. The message is then delivered through the System.Web.Mail.SmtpMail class.

Sending a Message Sample Code
The following sample code contains a C#-based Windows Console application that shows how to send an e-mail message. By not specifying that the SmtpMail.SmtpServer property is not set, the localhost is used by default. You need to make sure to add a reference to the System.Web.dll because this is a console application and not an ASP.NET application.

using System;
using System.Web.Mail;

namespace CodeGuru.SendMail
{
  /// <summary>
  /// Test console application to demonstrate sending e-mail.
  /// </summary>
  class TestMail
  {
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
      TestMail.Send("testuser@codeguru.com",
                    "mstrawmyer@crowechizek.com",
                    "Test Message Using CDOSYS",
                    "Hello World!  This is a simple message sent
                     using CDOSYS.");
    }

    /// <summary>
    /// Send a message using the .NET wrapper for Collaborative Data
    /// Objects (CDO).  This method should be used when sending to a
    /// single recipient only; otherwise, the list of recipients
    /// will be known.
    /// </summary>
    /// <param name="MessageFrom">Message originator</param>
    /// <param name="MessageTo">Message receipent</param>
    /// <param name="MessageSubject">Message subject</param>
    /// <param name="MessageBody">Message body</param>
    public static void Send(string MessageFrom,
                            string MessageTo,
                            string MessageSubject,
                            string MessageBody)
    {
      MailMessage message = new MailMessage();
      message.From        = MessageFrom;
      message.To          = MessageTo;
      message.Subject     = MessageSubject;
      message.BodyFormat  = MailFormat.Text;
      message.Body        = MessageBody;

      try
      {
        System.Console.WriteLine("Sending outgoing message");
        SmtpMail.Send(message);
      }
      catch( System.Web.HttpException exHttp )
      {
        System.Console.WriteLine("Exception occurred:" +
                                 exHttp.Message);
      }
    }
  }
}

Sending a Message with an Attachment Sample Code
The following sample code contains a C#-based Windows Console application that shows how to send an e-mail message that includes an attachment. This is done by creating instances of the MessageAttachment class and then adding them to the message through the Attachments collection.

using System;
using System.Web.Mail;

namespace CodeGuru.SendMail
{
  /// <summary>
  /// console application to demonstrate sending e-mail with an
  /// attachment.
  /// </summary>
  class TestMail
  {
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
      TestMail.SendAttachment("testuser@codeguru.com",
                              "mstrawmyer@crowechizek.com",
                              "Test Message Using CDOSYS",
                              "Hello World!  This is a simple
                               message sent using CDOSYS.",
                              "c:\\myattachment.txt");
    }

    /// <summary>
    /// Send a message using the .NET wrapper for Collaborative Data
    /// Objects (CDO).  This method should be used when sending to
    /// a single recipient only; otherwise, the list of recipients
    /// will be known.
    /// </summary>
    /// <param name="MessageFrom">Message originator</param>
    /// <param name="MessageTo">Message receipent</param>
    /// <param name="MessageSubject">Message subject</param>
    /// <param name="MessageBody">Message body</param>
    /// <param name="MessageAttachmentPath">Path to attachment
    /// </param>
    public static void SendAttachment(string MessageFrom,
                                      string MessageTo,
                                      string MessageSubject,
                                      string MessageBody,
                                      string MessageAttachmentPath)
    {
      // Create and setup the message
      MailMessage message = new MailMessage();
      message.From        = MessageFrom;
      message.To          = MessageTo;
      message.Subject     = MessageSubject;
      message.BodyFormat  = MailFormat.Text;
      message.Body        = MessageBody;

      // Create and add the attachment
      MailAttachment attachment = new
          MailAttachment(MessageAttachmentPath);
      message.Attachments.Add(attachment);

      try
      {
        // Deliver the message
        System.Console.WriteLine("Sending outgoing message");
        SmtpMail.Send(message);
      }
      catch( System.Web.HttpException exHttp )
      {
        System.Console.WriteLine("Exception occurred:" +
                                 exHttp.Message);
      }
    }
  }
}

Possible Enhancements
We have demonstrated how to send e-mail messages in a couple of ways. It is now up to you to think about ways in which you can utilize this functionality within your applications. Here are some ideas to consider on your own:

E-mail alerts—when a fatal or unrecoverable application error occurs, your application could e-mail information to a designated location so that it is immediately known.
Build a Web-based contact form—you can allow users to send customer feedback by filling out a Web form and then programmatically e-mailing it to the appropriate contact(s).
Subscription service—when sending mail by using CDOSYS for a subscription-type service, you may want to send multiple messages instead of a single message with all of the recipients. When a message has too many recipients, it can drastically slow processing as all of the recipients are processed. It is often better to break the list of recipients into multiple lists and send multiple messages.
Send messages using Bcc—when sending mail using by CDOSYS for a subscription-type service, you may want to address messages using the Bcc instead of To. This will keep the list of recipients unknown to all of those that receive it.
Send HTML-formatted mail—the message body format can be set to HTML. This will allow the body of the message to be sent in HTML format rather than plain text.

翻譯心得:

這篇文章介紹了在如何.Net程序中發(fā)送電子郵件,包括怎樣配置IIS和Smtp服務(wù),怎樣發(fā)送簡(jiǎn)單郵件以及如何在應(yīng)用程序中加以利用的一些想法。對(duì)于開(kāi)發(fā)者來(lái)說(shuō)不失為一篇介紹發(fā)送電子郵件的好文章。在.NET 網(wǎng)上書(shū)店的開(kāi)發(fā)中,我們同樣可以利用發(fā)送電子郵件來(lái)向客戶(hù)反饋書(shū)籍信息,為客戶(hù)提供定單服務(wù)等等。