分享
 
 
 

在.NET 应用程序中用System.Web.Mail 发送电子邮件

王朝c#·作者佚名  2006-01-08
窄屏简体版  字體: |||超大  

在.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 服务的任务就是基于配置接收和发送消息。这个服务可以直接投递消息,也可以使用代理服务器来发送消息。当代理服务器已配置时,所有的消息将转发给它以备发送。你必须确保 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 网上书店的开发中,我们同样可以利用发送电子邮件来向客户反馈书籍信息,为客户提供定单服务等等。

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有