程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> .NET實例教程 >> 在.NET 應用程序中用System.Web.Mail 發送電子郵件

在.NET 應用程序中用System.Web.Mail 發送電子郵件

編輯:.NET實例教程
作者:Mark Strawmyer
日期:February 9, 2004
 
歡迎來到 .Net Nuts & Bolts 欄目。在這個欄目中,我們將探討怎樣在應用中發送電子郵件。這將用到System.Web.Mail 名字空間中的類。

協作數據對象
Windows 2000 協作數據對象 (CDOSYS) 是微軟用來創建和發送基於標准的電子郵件信息的消息組件。它是 用與 Windows NT的協作數據對象(CDONTS) 的替代物。 盡管由於向後兼容的原因 CDONTS 已包含在 Windows 2000 中, 但是 Windows XP, Windows Server 2003 以及更高版本均未包含或支持 CDONTS 組件。 所以任何使用 CDONTS 發送消息的應用程序都必須遷移到使用 CDOSYS 上來。它提供了相同的功能,而且易於使用。

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

向新聞組發送消息的能力
對消息的 MIME 體結構的控制
接收和轉發機制
傳輸事件接受池以便對事件作出響應
System.Web.Mail 命名空間包含了與 CDOSYS 組件交互從而創建和發送信息的類。

使用互聯網信息服務(IIS)和 SMTP 服務
為了能從應用程序中利用 CDOSYS 發送電子郵件,您必須確認 IIS 服務列表中已經安裝了SMTP 服務。在 Windows 2000/XP中,您可以通過控制面板 -> 添加/刪除程序 -> 添加/刪除 Windows 組件選項來設置。STMP 服務的任務就是基於配置接收和發送消息。這個服務可以直接投遞消息,也可以使用代理服務器來發送消息。當代理服務器已配置時,所有的消息將轉發給它以備發送。你必須確保 IIS 和 SMTP 服務正確的安裝和配置好。

在投遞之前,SMTP 服務使用一個目錄結構來保存消息。默認的目錄為C:\Inetpub\mailroot。這個文件夾中包含了一些子目錄,如:Queue, Drop, Badmail。 如果你無法配置SMTP服務實例以便發送的話,您將可以在目錄 C:\Inetpub\mailroot\Queue 中的 *.EML 文件中找到郵件。這個技巧在離線創建郵件時將很有用。

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

發送郵件示例代碼
下面的 C# 示例代碼將包含一個演示如何發送簡單電子郵件的 Windows 控制台程序。當沒有設置 SmtpMail 的 SmtpServer 屬性時,本地機器將為其默認配置。你必須確保添加了針對 System.Web.dll 的引用,因為它是控制台應用程序而不是 ASP.Net 應用。

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("[email protected]",
                    "[email protected]",
                    "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);
      }
    }
  }
}

發送帶有附件的郵件示例代碼
下面的 C# 示例代碼將包含一個演示如何發送帶有附件的電子郵件的 Windows 控制台程序。這將由創建類 MessageAttachment 的實例,然後將其添加到 Attachments 集合來完成。

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("[email protected]",
                              "[email protected]",
                              "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,
              &nbsp;                       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);
      }
    }
  }
}

可能的改進
我們已經從不同途徑演示了如何發送電子郵件。現在輪到你想想如何在你的應用程序中應用這項功能了。這裡有一些想法和你共同分享:

E-mail 警告—當一個致命的或無法恢復的應用程序錯誤發生時,您的應用程序可以發送電子郵件到一指定地址以使其能很快得知。
創建一個基於Web的聯系消息窗體—你可以使用戶通過填寫 Web 表單來發送用戶反饋,然後編寫相關程序把消息發送給適當的聯系人。
訂閱服務—當通過 CDOSYS 組件發送電子郵件來支持訂閱類型的服務時,您將需要發送多封郵件而不是單一郵件給所有的接收者。當一則消息擁有大量的接收者時,處理所有的接收者將戲劇性地減滿處理速度。這時候您最好將接收者列表分解成多個列表,分好幾次發送消息。
使用 Bcc 發送消息—當通過 CDOSYS 組件發送電子郵件來支持訂閱類型的服務時,您也許想要使用 Bcc 而不是 To 來填寫接收人地址。這樣可以使得所有接收者無法得知接收者列表。
發送 HTML 格式的郵件—消息主體格式可以是 HTML。它可以使消息主體以 Html 格式發送而不是普通文本。
-----------------------------------------------------------

原文:


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("[email protected]",
                    "[email protected]",
                    "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("[email protected]",
                              "[email protected]",
                   &nbsp;          "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程序中發送電子郵件,包括怎樣配置IIS和Smtp服務,怎樣發送簡單郵件以及如何在應用程序中加以利用的一些想法。對於開發者來說不失為一篇介紹發送電子郵件的好文章。在.Net 網上書店的開發中,我們同樣可以利用發送電子郵件來向客戶反饋書籍信息,為客戶提供定單服務等等。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved