首页 > 开发 > 综合 > 正文

用System.Web.Mail发送电子邮件

2024-07-21 02:21:58
字体:
来源:转载
供稿:网友



作者: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,
                                      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]",
                              "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 网上书店的开发中,我们同样可以利用发送电子邮件来向客户反馈书籍信息,为客户提供定单服务等等。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表