65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 ASP.NET 的电子邮件系统

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.46/5 (26投票s)

2005年11月15日

CPOL

4分钟阅读

viewsIcon

197782

downloadIcon

5143

本文探讨了 SMTP 的概念、配置以及简单的邮件服务。

引言

本文探讨了一个以简单方式开发的电子邮件系统的特性,并展示了如何轻松地创建一个简单的邮件服务。我相信,阅读本文的任何人都会对电子邮件服务以及基于 SMTP 的邮件服务器背后的概念有一个相当好的了解。

问题所在

您多久会遇到因缺乏技术知识和框架核心概念而导致的问题?本文以最简单的方式探讨了邮件服务器背后的概念。本文

  • 探讨了使用 SMTP 配置邮件服务器的设置。
  • 以非常有趣且简单的方式描述了代码。
  • 描述了为在 Web 服务器上托管它需要进行的设置。
  • 描述了运行时发生问题的解决方案。

探索技术

SMTP 代表简单邮件传输协议。电子邮件使用此完美协议发送。 .NET Framework 提供了 SMTP 类,可让您发送简单的电子邮件。如果您需要发送具有附加功能的电子邮件,则必须使用 MailMessage 类。借助此类,您可以轻松地插入附件、设置优先级等。您还可以使用此类发送 HTML 电子邮件。

邮件服务器的先决条件

首先,您需要检查 IIS(Internet Information Service,是随操作系统一起提供的 Windows 组件)中的 SMTP 服务是否已启用。您可以在控制面板的“添加/删除程序”部分中找到此服务。

在“添加/删除程序”部分中,单击“Windows 组件”,您将看到如下所示的屏幕。

查看 IIS 是否已选中,如果已选中(已安装),请单击 IIS(Internet Information Services),您将看到如下所示的屏幕。

然后,检查 SMTP 服务是否已安装。如果服务不可用,您需要选择 SMTP 服务并按照向导进行操作。有时它可能会要求提供 Windows XP CD 来安装 Windows 组件。现在,该应用程序就可以使用 SMTP 邮件服务了。

配置和设置

要配置 SMTP 服务器,您需要按照以下步骤操作:

  1. 转到 >“开始”菜单 >“控制面板” >“管理工具” >“Internet Information Services”。
  2. 单击“Internet Information Services”并找到“默认 SMTP 虚拟服务器”。
  3. 右键单击它,然后转到属性,如下所示。

    根据图示进行设置,选择您自己的 IP 地址。

  4. 然后转到选项卡菜单中的“访问”选项,然后单击“中继限制”。在“中继”中,您将看到如下所示的屏幕,现在请相应配置。

    在“访问”选项卡中,您还需要根据下图配置连接属性,并将其余设置保留原样。

    IP 地址 127.0.0.1 代表本地主机。现在,您可以准备好应用程序了。

代码片段

项目代码片段将在下面解释。

private void SendMail()
{
  try
   {
     MailMessage Email=new MailMessage(); //Creating the Mail Message 

                                          //object.

     Email.To=txtTo.Text;                 //Storing the To value in 

                                          //the object.

     Email.From=txtFrom.Text;             //Storing the From value 

                                          //in the object.

     Email.Cc=txtCC.Text;                 //Storing the CC value in 

                                          //the object.

     Email.Bcc=txtBCC.Text;               //Storing the BCC value in 

                                          //the object.

     Email.Subject=txtSubject.Text;       //Storing the Subject value 

                                          //in the object.

     Email.Body=txtMessage.Text;          //Specifies the email body.

     Email.Priority=MailPriority.High;    //Setting priority to the mail 

                                          //as high,low,or normal

     Email.BodyFormat=MailFormat.Text;    //Formatting the mail as html 

                                          //or text.


     //Checking whether the attachment is needed or not.

     if(rbtnAttach.Checked)
     {
       //Adding attachment to the mail.

       Email.Attachments.Add(
                  new MailAttachment(FileBrowse.Value));

     }
     //Specifying the real SMTP Mail Server.

     SmtpMail.SmtpServer.Insert(0,"127.0.0.1");
     SmtpMail.Send(Email);                //Sending the mail.

     Reset();                             //calling the reset method to 

                                          //erase the text entered.

     lblMessage.ForeColor=Color.Navy;
     lblMessage.Text=
         "*Your email has been sent successfully-Thank You";
   }
   //Handling the Exception

   catch(Exception exc)
   {
     lblMessage.Text="Send error:"+exc.ToString();
     lblMessage.ForeColor=Color.Red;
   }
}

在按钮的 Click 事件中调用 SendMail() 方法,如下所示。

private void btnSend_Click(object sender, System.EventArgs e)
{
  SendMail();
}

Reset() 方法中的代码块如下所示。

private void Reset()
{
   //Seeking for the controls in the active webform.

   Control myForm=Page.FindControl("Form1");
   //Iterating each control.

   foreach(Control ctl in myForm.Controls)
   {
      // Checking whether it is a text box 

      // and clear when it is a textbox

      if(ctl.GetType().ToString().Equals("System.Web.UI.WebControls.TextBox"))
      ((TextBox)ctl).Text="";
   }
}

在另一个按钮的 Click 事件中调用 Reset() 方法,如下所示。

private void btnCancel_Click(object sender, System.EventArgs e)
{
    Reset();
}

最终解决方案

我们的代码现在如下所示:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.Mail;
namespace Email
{
    /// <summary>

    /// Summary description for WebForm1.

    /// </summary>

    public class WebForm1 : System.Web.UI.Page
    {
        protected System.Web.UI.WebControls.Label lblFrom;
        protected System.Web.UI.WebControls.Label lblCC;
        protected System.Web.UI.WebControls.TextBox txtFrom;
        protected System.Web.UI.WebControls.TextBox txtCC;
        protected System.Web.UI.WebControls.TextBox txtTo;
        protected System.Web.UI.WebControls.Label lblTo;
        protected System.Web.UI.WebControls.Label lblEmailService;
        protected System.Web.UI.WebControls.TextBox txtBCC;
        protected System.Web.UI.WebControls.Label lblBCC;
        protected System.Web.UI.WebControls.Label lblSubject;
        protected System.Web.UI.WebControls.TextBox txtSubject;
        protected System.Web.UI.WebControls.Label lblMessage;
        protected System.Web.UI.WebControls.TextBox txtMessage;
        protected System.Web.UI.WebControls.Button btnSend;
        protected System.Web.UI.HtmlControls.HtmlInputFile FileBrowse;
        protected System.Web.UI.WebControls.Label lblAttachment;
        protected System.Web.UI.WebControls.RadioButton rbtnAttach;
        protected System.Web.UI.WebControls.RadioButton rbtnDetachment;
        protected System.Web.UI.WebControls.Button btnCancel;
        public string strAttachment;
        
        private void Page_Load(object sender, System.EventArgs e)
        {
            lblMessage.Text="";
        }
        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //

            // CODEGEN: This call is required by the 

            // ASP.NET Web Form Designer.

            //

            InitializeComponent();
            base.OnInit(e);
        }
        
        /// <summary>

        /// Required method for Designer support - do not modify

        /// the contents of this method with the code editor.

        /// </summary>

        private void InitializeComponent()
        { 
            this.rbtnDetachment.CheckedChanged += 
               new System.EventHandler(this.rbtnDetachment_CheckedChanged);
            this.btnCancel.Click += 
                new System.EventHandler(this.btnCancel_Click);
            this.btnSend.Click += 
                new System.EventHandler(this.btnSend_Click);
            this.rbtnAttach.CheckedChanged += 
                new System.EventHandler(this.rbtnAttach_CheckedChanged);
            this.Load += new System.EventHandler(this.Page_Load);
        }
        #endregion
        
        //Method for sending the email

        //***************************************************************

        private void SendMail()
        {
            try
            {
                //Creating the Mail Message object.

                MailMessage Email=new MailMessage();
                //Storing the To value in the object reference.

                Email.To=txtTo.Text;                
                //Storing the From value in the object reference.

                Email.From=txtFrom.Text;
                //Storing the CC value in the object reference.

                Email.Cc=txtCC.Text;
                //Storing the BCC value in the object reference.

                Email.Bcc=txtBCC.Text;
                //Storing the Subject value in the object reference.

                Email.Subject=txtSubject.Text;
                //Specifies the email body.

                Email.Body=txtMessage.Text;
                //Setting priority to the mail as high,low,or normal

                Email.Priority=MailPriority.High;
                //Formatting the mail as html or text.

                Email.BodyFormat=MailFormat.Text;
                //Checking whether the attachment is needed or not.

                if(rbtnAttach.Checked)
                {
                    //Adding attachment to the mail.

                    Email.Attachments.Add(
                        new MailAttachment(FileBrowse.Value));
                }
                //specifying the real SMTP Mail Server.

                SmtpMail.SmtpServer.Insert(0,"127.0.0.1");
                SmtpMail.Send(Email);//Sending the mail.

                //calling the reset method to erase all the data 

                //after sending the mail.

                Reset();
                lblMessage.ForeColor=Color.Navy;
                //User information after submission.

                lblMessage.Text=
                  "*Your email has been sent successfully-Thank You";
            }
            //Catching Exception 

            catch(Exception exc)
            { 
                Reset();
                lblMessage.Text="Send error:"+exc.ToString();
                lblMessage.ForeColor=Color.Red;
            }
        }
        //Method to reset the text fields.

        //***********************************************************

        private void Reset()
        {
            //Seeking for the controls in the active webform.

            Control myForm=Page.FindControl("Form1");
            //Iterating each control.

            foreach(Control ctl in myForm.Controls)
            {
                //Checking whether it is a text

                //box and clear when it is a textbox.

                if(ctl.GetType().ToString().Equals(
                            "System.Web.UI.WebControls.TextBox")) 
                                                                 
                ((TextBox)ctl).Text="";
            }
        }
        //Event fires for sending the mail.

        //***********************************************************

        private void btnSend_Click(object sender, System.EventArgs e)
        {
            SendMail();
        }
        //Event for cancelling the mail.

        //***********************************************************

        private void btnCancel_Click(object sender, System.EventArgs e)
        {
            Reset();
        }
        //Event for enabling or disabling the File browser.

        //************************************************************

        private void rbtnAttach_CheckedChanged(object sender, 
                                                  System.EventArgs e)
        {
            FileBrowse.Disabled=false;
        }
        //Event for enabling or disabling the File browser.

        //************************************************************

        private void rbtnDetachment_CheckedChanged(object sender, 
                                                        System.EventArgs e)
        {
            FileBrowse.Disabled=true;
        }
        //*************************************************************

    }
}

使用解决方案

下载上面提供的 zip 格式的源代码文件,并将内容复制到根目录(例如,C:\Inetpub\wwwroot)。转到“Internet Information Services”,创建一个名为 EmailSystem 的虚拟目录,并为其分配正确的映射路径。

某些问题的解决方案

错误:“无法访问 'CDO.Message' 对象”

解决方案 1

SmtpMail.SmtpServer 属性指定一个有效的邮件服务器。如果该属性未设置,请将其设置为 127.0.0.1 或 localhost。例如:SmtpMail.SmtpServer = "127.0.0.1"

解决方案 2

如果您使用“localhost”或“127.0.0.1”作为 SmtpMail.SmtpServer,您可能没有权限通过 IIS SMTP 服务进行中继。要允许访问,请在“管理工具”选项中打开 IIS MMC。找到 SMTP 虚拟服务器,右键单击,然后选择“属性”。在“访问”选项卡上,单击“中继限制”按钮。在“中继限制”对话框中,将您的 IP 地址 (127.0.0.1) 添加到“计算机”列表框中。关闭所有对话框,然后重新启动 SMTP 服务。

解决方案 3

如果您使用“localhost”或“127.0.0.1”作为 SmtpMail.SmtpServer,请确保启用了匿名访问。要允许访问,请打开 IIS 管理 MMC。找到 SMTP 虚拟服务器,右键单击,然后选择“属性”。在“访问”选项卡上,单击“身份验证”按钮。然后,确保仅选中“匿名访问”复选框。关闭所有对话框,然后重新启动 SMTP 服务。

传输连接失败

解决方案 1

上述错误是网络相关错误。现在,请确保 System.Web.Mail 服务器正在执行。有时防火墙或代理服务器可能会导致问题。尝试通过 IP 地址指定值。糟糕的 DNS 解析有时会妨碍名称查找。检查邮件服务器是否正在端口 25 上运行。如果您未指定 SmtpMail.SmtpServer 属性,或者 SmtpMail.SmtpServer 指向“localhost”(或 127.0.0.1),请确保 SMTP 服务正在端口 25 上运行。有时问题是由于中继问题引起的。

© . All rights reserved.