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

C#中的SMTP电子邮件组件

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.85/5 (18投票s)

2006年4月4日

CPOL

3分钟阅读

viewsIcon

192544

downloadIcon

878

一个简单的电子邮件组件。

引言

EasyMail 是一个简单的邮件组件,可用于通过 SMTP 客户端发送电子邮件。您只需确保正确配置所有 SMTP 设置即可。

这只是一个如何发送电子邮件的示例。扩展此组件非常容易,因此我将其留给用户修改和改进以满足您的需求。

构建组件 DLL

  • 创建一个新的“Windows 控件库”。
  • 在解决方案资源管理器中,删除 *UserControl1.cs*。
  • 向控件库添加一个新项。
  • 创建一个名为 EasyMail 的新组件类。
  • 将新创建的 EasyMail 类替换为以下代码
  • /// <summary>
    /// Easy mail component that only needs to be droped on
    /// your form to be used.
    /// </summary>
    public partial class EasyMail : Component
    {
      // All the fields that are needed
      private string mMailFrom;
      private string mMailTo;
      private string mMailSubject;
      private string mMailBody;
      private string mSMTPServer;
      private int mSMTPPort;
      private string mSMTPUsername;
      private string mSMTPPassword;
      private bool mSMTPSSL;
      private MailMessage MailObject;
    
      // Properties
      public string MailFrom { set { mMailFrom = value; }
                               get { return mMailFrom; } }
      public string MailTo { set { mMailTo = value; }
                             get { return mMailTo; } }
      public string MailSubject
          { set { mMailSubject = value; }
            get { return mMailSubject; } }
      public string MailBody { set { mMailBody = value; }
                               get { return mMailBody; } }
      public string SMTPServer { set { mSMTPServer = value; }
                                 get { return mSMTPServer; } }
      public int SMTPPort { set { mSMTPPort = value; }
                            get { return mSMTPPort; } }
      public string SMTPUsername
          { set { mSMTPUsername = value; }
            get { return mSMTPUsername; } }
      public string SMTPPassword {
            set { mSMTPPassword = value; }
            get { return mSMTPPassword; } }
      public Boolean SMTPSSL { set { mSMTPSSL = value; }
                               get { return mSMTPSSL; } }
    
    
      // Functions
      public Boolean Send()
      {
        // build the email message
        MailMessage Email = new MailMessage();
        MailAddress MailFrom = 
         new MailAddress(mMailFrom,mMailFrom);
        Email.From = MailFrom;
        Email.To.Add(mMailTo);
        
        Email.Subject = mMailSubject;
        Email.Body = mMailBody;
    
        // Smtp Client
        SmtpClient SmtpMail = 
        new SmtpClient(mSMTPServer,mSMTPPort);
        SmtpMail.Credentials = 
        new NetworkCredential(mSMTPUsername,mSMTPPassword);
        SmtpMail.EnableSsl = mSMTPSSL;
    
        Boolean bTemp = true;
    
        try
        {
         SmtpMail.Send(Email);
         return true;
        }
        catch (SmtpFailedRecipientsException ex)
        {
         MessageBox.Show("The message was not sent!!!");
         bTemp = false;
        }
        return bTemp;
      }
           
      // Constructor
      public EasyMail()
      {
        InitializeComponent();
    
        MailObject = new MailMessage();
        mMailFrom = "";
        mMailTo = "";
        mMailSubject = "";
        mMailBody = "";
        mSMTPServer = "";
        mSMTPPort = 25;
        mSMTPUsername = "";
        mSMTPPassword = "";
        mSMTPSSL = false;
      }
    
      public EasyMail(IContainer container)
      {
        container.Add(this);
        InitializeComponent();
      }
    }
  • 确保所有以下“using”子句都在文件的顶部,然后构建组件。
  • using System;
    using System.ComponentModel;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Text;
    using System.Net;
    using System.Net.Mail;
    using System.Windows.Forms;

将电子邮件组件安装到工具箱

  • 转到窗体的设计视图。
  • 打开工具箱。
  • 在工具箱中,右键单击要将电子邮件控件添加到其中的选项卡(在此示例中为“组件”)。
  • 从弹出菜单中选择“选择项...”
  • 将打开“选择工具箱项”窗口。单击“浏览”,然后选择电子邮件组件的 DLL 文件。 单击“确定”关闭“选择工具箱项”窗口。 现在,新组件将位于工具箱中。

使用组件

  • 选择 EasyMail 组件并将其拖放到您的窗体上。将创建一个 EasyMail1 对象。
  • 要使用它,请将以下代码添加到按钮事件或您要从中运行发送事件的任何位置。(将 XXX 替换为正确的信息。)
easyMail1.MailFrom = " XXX@XXX.XXX";
easyMail1.MailTo = " XXX@XXX.XXX";
easyMail1.MailSubject = "Subject";
easyMail1.MailBody = "Mail body";

easyMail1.SMTPServer = "smtp.mail.yahoo.com";
easyMail1.SMTPUsername = "XXX";
easyMail1.SMTPPassword = "XXX";
if (easyMail1.Send())
{
    MessageBox.Show("Sent...");
}

异步或同步发送消息

并非总是需要同步发送消息。它可能会导致您的用户界面冻结或挂起。为了解决这个问题,我们在 SMTPClient 类中有一个单独的函数,名为 sendasync。这允许消息在其自己的线程中发送。

要添加此功能,我们需要添加一个新的布尔属性来启用/禁用此选项。我们还需要添加代码来根据新属性的值执行正确的函数。

新属性

private bool mSendAsync;
public bool SendAsync { set { mSendAsync = value; }
                        get { return mSendAsync; } }

将对新属性做出反应的代码。 这将被添加到 Send 函数。

string sTemp = "";
if (mSendAsync)
    SmtpMail.SendAsync(Email,sTemp);
else
    SmtpMail.Send(Email);

更好的异常处理

邮件服务可能并非总是可用。 因此,我们将不得不添加一些异常处理程序来捕获意外事件。 为此,我将测试是否已发送消息。 如果未发送,我将等待几秒钟,然后再尝试重新发送。

我创建了两个新属性:TryAgianOnFailureTryAgainDelayTime

private bool mTryAgianOnFailure;
private int mTryAgainDelayTime;

public bool TryAgianOnFailure 
  { set { mTryAgianOnFailure = value; }
    get { return mTryAgianOnFailure; } }
public int TryAgainDelayTime
  { set { mTryAgainDelayTime = value; }
    get { return mTryAgainDelayTime; }

这是使其工作的代码... 这将被添加到 Send 函数。

catch (SmtpFailedRecipientsException e)
{
    for (int k=0;k < e.InnerExceptions.Length;k++)
    {
        bTemp = false;
    
        SmtpStatusCode StatusCode = 
        e.InnerExceptions[k].StatusCode;
        if (StatusCode==SmtpStatusCode.MailboxUnavailable||
        StatusCode==SmtpStatusCode.MailboxBusy)
        {
            try
            {
                if (mTryAgianOnFailure)
                {
                    Thread.Sleep(mTryAgainDelayTime);
                    // send the message
                    string sTemp = "";
                    if (mSendAsync)
                        SmtpMail.SendAsync(Email, sTemp);
                    else
                        SmtpMail.Send(Email);
                    // Message was sent.
                    bTemp = true;
                }
            }
            catch { bTemp = false}
        }
    }
}

结论

这只是一个如何在 Visual Studio 中简化操作的简单示例。 我非常喜欢组件,因为所有内容都打包在一起。 如果出现任何问题,您可以直接知道在哪里可以找到问题。 创建控件也是提高您的面向对象技能的好方法。 我希望这在某种程度上对您有所帮助。

有关更多信息,请访问我的网站... www.ChatBert.com

历史

更新 (2008/04/22)

我添加了一个 string[] 属性 (MailAttachments),它将存储附件文件路径的列表。

示例

easyMail1.MailAttachments = new string[2];
easyMail1.MailAttachments[0] = "c:\\temp.txt";
easyMail1.MailAttachments[1] = "c:\\log.txt";
© . All rights reserved.