在.NET 應用程式中用System.Web.Mail 寄送電子郵件

來源:互聯網
上載者:User
web|程式 在.NET 應用程式中用System.Web.Mail 寄送電子郵件


作者: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 服務的任務就是基於配置接收和發送訊息。這個服務可以直接投遞訊息,也可以使用Proxy 伺服器來發送訊息。當Proxy 伺服器已配置時,所有的訊息將轉寄給它以備發送。你必須確保 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("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);
}
}
}
}

發送帶有附件的郵件範例程式碼
下面的 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("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);
}
}
}
}

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

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("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程式中寄送電子郵件,包括怎樣配置IIS和Smtp服務,怎樣發送簡單郵件以及如何在應用程式中加以利用的一些想法。對於開發人員來說不失為一篇介紹寄送電子郵件的好文章。在.NET 網上書店的開發中,我們同樣可以利用寄送電子郵件來向客戶回函書籍資訊,為客戶提供定單服務等等。


相關文章

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。