熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

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

2022-06-13   來源: .NET編程 
    在這個欄目中我們將探討怎樣在應用中發送電子郵件這將用到SystemWebMail 名字空間中的類
協作數據對象
    Windows 協作數據對象 (CDOSYS) 是微軟用來創建和發送基於標准的電子郵件信息的消息組件它是 用與 Windows NT的協作數據對象(CDONTS) 的替代物 盡管由於向後兼容的原因 CDONTS 已包含在 Windows 但是 Windows xp Windows Server 以及更高版本均未包含或支持 CDONTS 組件 所以任何使用 CDONTS 發送消息的應用程序都必須遷移到使用 CDOSYS 上來它提供了相同的功能而且易於使用
    除了作為替代物外 CDOSYS 還引入了一些 CDONTS 中沒有的功能
    向新聞組發送消息的能力
    對消息的 MIME 體結構的控制
    接收和轉發機制
    傳輸事件接受池以便對事件作出響應
    SystemWebMail 命名空間包含了與 CDOSYS 組件交互從而創建和發送信息的類
    使用互聯網信息服務(IIS)和 SMTP 服務
    為了能從應用程序中利用 CDOSYS 發送電子郵件您必須確認 IIS 服務列表中已經安裝了SMTP 服務在 Windows /XP中您可以通過控制面板 > 添加/刪除程序 > 添加/刪除 Windows 組件選項來設置STMP 服務的任務就是基於配置接收和發送消息這個服務可以直接投遞消息也可以使用代理服務器來發送消息當代理服務器已配置時所有的消息將轉發給它以備發送你必須確保 IIS 和 SMTP 服務正確的安裝和配置好
    在投遞之前SMTP 服務使用一個目錄結構來保存消息默認的目錄為C:\Inetpub\mailroot這個文件夾中包含了一些子目錄Queue Drop Badmail 如果你無法配置SMTP服務實例以便發送的話您將可以在目錄 C:\Inetpub\mailroot\Queue 中的 *EML 文件中找到郵件這個技巧在離線創建郵件時將很有用
    發送消息
    正如前面提到的發送電子郵件將是一件相對簡單的事類 SystemWebMailMailMessage class 代表了將要發送的消息Email 消息將由該類的實例來創建這個類包含了諸如收件人發件人和主題等屬性來讓你控制想要發送的消息還可以使用類 SystemWebMailMailAttachment 的實例創建附件然後添加到 MailMessage 的 Attachments (附件)集合中隨後該消息將由 類SystemWebMailSmtpMail 發送出去
發送郵件示例代碼
    下面的 C# 示例代碼將包含一個演示如何發送簡單電子郵件的 Windows 控制台程序當沒有設置 SmtpMail 的 SmtpServer 屬性時本地機器將為其默認配置你必須確保添加了針對 SystemWebdll 的引用因為它是控制台應用程序而不是 應用
    using System;
    using SystemWebMail;
    namespace CodeGuruSendMail
    {
    /// <summary>
    /// Test console application to demonstrate sending email
    /// </summary>
    class TestMail
    {
    /// <summary>
    /// The main entry point for the application
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
    TestMailSend(t
    mstraw
    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();
    messageFrom        = MessageFrom;
    messageTo          = MessageTo;
    messageSubject     = MessageSubject;
    messageBodyFormat  = MailFormatText;
    messageBody        = MessageBody;
    try
    {
    SystemConsoleWriteLine(Sending outgoing message);
    SmtpMailSend(message);
    }
    catch( SystemWebHttpException exHttp )
    {
    SystemConsoleWriteLine(Exception occurred: +
    exHttpMessage);
    }
    }
    }
    }


發送帶有附件的郵件示例代碼
    下面的 C# 示例代碼將包含一個演示如何發送帶有附件的電子郵件的 Windows 控制台程序這將由創建類 MessageAttachment 的實例然後將其添加到 Attachments 集合來完成
    using System;
    using SystemWebMail;
    namespace CodeGuruSendMail
    {
    /// <summary>
    /// console application to demonstrate sending email with an
    /// attachment
    /// </summary>
    class TestMail
    {
    /// <summary>
    /// The main entry point for the application
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
    TestMailSendAttachment(t
    mstraw
    Test Message Using CDOSYS
    Hello World!  This is a simple
    message sent using CDOSYS
    c:\\myattachmenttxt);
    }
    /// <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();
    messageFrom        = MessageFrom;
    messageTo          = MessageTo;
    messageSubject     = MessageSubject;
    messageBodyFormat  = MailFormatText;
    messageBody        = MessageBody;
    // Create and add the attachment
    MailAttachment attachment = new
    MailAttachment(MessageAttachmentPath);
    messageAttachmentsAdd(attachment);
    try
    {
    // Deliver the message
    SystemConsoleWriteLine(Sending outgoing message);
    SmtpMailSend(message);
    }
    catch( SystemWebHttpException exHttp )
    {
    SystemConsoleWriteLine(Exception occurred: +
    exHttpMessage);
    }
    }
    }
    }


可能的改進
    我們已經從不同途徑演示了如何發送電子郵件現在輪到你想想如何在你的應用程序中應用這項功能了這裡有一些想法和你共同分享
    Email 警告—當一個致命的或無法恢復的應用程序錯誤發生時您的應用程序可以發送電子郵件到一指定地址以使其能很快得知
    創建一個基於Web的聯系消息窗體—你可以使用戶通過填寫 Web 表單來發送用戶反饋然後編寫相關程序把消息發送給適當的聯系人
    訂閱服務—當通過 CDOSYS 組件發送電子郵件來支持訂閱類型的服務時您將需要發送多封郵件而不是單一郵件給所有的接收者當一則消息擁有大量的接收者時處理所有的接收者將戲劇性地減滿處理速度這時候您最好將接收者列表分解成多個列表分好幾次發送消息
    使用 Bcc 發送消息—當通過 CDOSYS 組件發送電子郵件來支持訂閱類型的服務時您也許想要使用 Bcc 而不是 To 來填寫接收人地址這樣可以使得所有接收者無法得知接收者列表
    發送 HTML 格式的郵件—消息主體格式可以是 HTML它可以使消息主體以 HTML 格式發送而不是普通文本
   
    原文
    Sending EMail with SystemWebMail
    Mark Strawmyer (view PRofile)
    February
    Rating: not yet rated
   
    Welcome to the next installment of the NET Nuts & Bolts column In this column well explore sending email from within applications This will involve utilizing classes contained in the SystemWebMail namespace
    Collaboration Data Objects
    Collaboration Data Objects for Windows (CDOSYS) is a Microsoft messaging component that allows for standardsbased email 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 for backwards compatibility but Windows XP Windows Server 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 SystemWebMail 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 email or other messages from your application you need to enlist the services of IIS with the SMTP Service installed Both are available in Windows /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 email is a relatively simple thing to do The SystemWebMailMailMessage class represents the message to be sent Email 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 SystemWebMailMailAttachment and then added to the MailMessage through the Attachments collection of the MailMessage The message is then delivered through the SystemWebMailSmtpMail class


    Sending a Message Sample Code
    The following sample code contains a C#based Windows Console application that shows how to send an email message By not specifying that the SmtpMailSmtpServer property is not set the localhost is used by default You need to make sure to add a reference to the SystemWebdll because this is a console application and not an ASPNET application
    using System;
    using SystemWebMail;
    namespace CodeGuruSendMail
    {
    /// <summary>
    /// Test console application to demonstrate sending email
    /// </summary>
    class TestMail
    {
    /// <summary>
    /// The main entry point for the application
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
    TestMailSend(t
    mstraw
    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();
    messageFrom        = MessageFrom;
    messageTo          = MessageTo;
    messageSubject     = MessageSubject;
    messageBodyFormat  = MailFormatText;
    messageBody        = MessageBody;
    try
    {
    SystemConsoleWriteLine(Sending outgoing message);
    SmtpMailSend(message);
    }
    catch( SystemWebHttpException exHttp )
    {
    SystemConsoleWriteLine(Exception occurred: +
    exHttpMessage);
    }
    }
    }
    }
    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 email 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 SystemWebMail;
    namespace CodeGuruSendMail
    {
    /// <summary>
    /// console application to demonstrate sending email with an
    /// attachment
    /// </summary>
    class TestMail
    {
    /// <summary>
    /// The main entry point for the application
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
    TestMailSendAttachment(t
    mstraw
    Test Message Using CDOSYS
    Hello World!  This is a simple
    message sent using CDOSYS
    c:\\myattachmenttxt);
    }
    /// <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();
    messageFrom        = MessageFrom;
    messageTo          = MessageTo;
    messageSubject     = MessageSubject;
    messageBodyFormat  = MailFormatText;
    messageBody        = MessageBody;
    // Create and add the attachment
    MailAttachment attachment = new
    MailAttachment(MessageAttachmentPath);
    messageAttachmentsAdd(attachment);
    try
    {
    // Deliver the message
    SystemConsoleWriteLine(Sending outgoing message);
    SmtpMailSend(message);
    }
    catch( SystemWebHttpException exHttp )
    {
    SystemConsoleWriteLine(Exception occurred: +
    exHttpMessage);
    }
    }
    }
    }
    Possible Enhancements
    We have demonstrated how to send email 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:
    Email alerts—when a fatal or unrecoverable application error occurs your application could email information to a designated location so that it is immediately known
    Build a Webbased contact form—you can allow users to send customer feedback by filling out a Web form and then programmatically emailing it to the appropriate contact(s)
    Subscription service—when sending mail by using CDOSYS for a subscriptiontype 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 subscriptiontype 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 HTMLformatted 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


From:http://tw.wingwit.com/Article/program/net/201311/12488.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.