概要:
         子线程工作,发送成功邮件做标记,逐条提取数据,气泡提示信息,最小化到托盘,实时进度条
 
代码:
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Threading;
using System.Text;
using System.Windows.Forms;
using System.Net.Mail;
using System.Net;
using System.Text.RegularExpressions;
 
namespace MailGroupSends
{
    public partial class Form1 : Form
    {

        private string subject = string.Empty, mailto = string.Empty, body = string.Empty;

        private int sucNum = 0;

        private int TotalDate=0;

        private string ConnString

        {
            get
            {

                string pathFull = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;

                string path = pathFull.Substring(0, pathFull.LastIndexOf(@"\"));

                return @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + @"\mail.mdb";

            }
        }

        private bool mailSent = false; //邮件是否发送成功

        private int mailTotalCount = 0;

        private int CategoryId = 0;

        private int SentCount = 0; //已发送数

        private int UnitConversion = 1; //默认为秒

       
        /// 发送间隔

        private int Interval

        {
            get
            {

                int timer = 0;

                int totalMis = (TotalDate * UnitConversion * 1000);

                timer = totalMis / (mailTotalCount-SentCount);

                return timer;

            }
        }

private void Form1_Load(object sender, EventArgs e)

        {

            Control.CheckForIllegalCrossThreadCalls = false;

            InitMailCategory();
            SentMailCount();
            LoadMailList();
            ClearTxt(txtAnnexPath);
           InitTime();
        }
/// 发送

        private void btnSendMail_Click(object sender, EventArgs e)

        {
            TotalDate = Convert.ToInt32(this.txtDateCount.Text.Trim());
            ControlEnabled(false);
            subject = this.txtSubject.Text.Trim();
            body = this.rtxtBody.Text.Trim();

            this.progressBar1.Visible = true;

            this.lblProgress.Visible = true;

            //用子线程工作
           new Thread(new ThreadStart(StartMailSend)).Start();
        }
/// 邮件发送

        private bool Send(string mailTo, string subject, string body)

        {
            try
            {

                if (!IsEmail(mailTo)) //邮箱格式验证

                {

                    WriteToTxt(DateTime.Now + "   Faild      " + mailTo, txtLogPath + "   Error Message:邮箱格式不正确");

                    MarkErrorMail(mailTo);

                    return false;

                }

                MailMessage msg = new MailMessage();

                msg.From = new MailAddress("***@****", "xiaoyaosr", Encoding.UTF8);

                if (mailTo.IndexOf(",") > -1)

                    msg.Bcc.Add(mailTo);
                else
                    msg.To.Add(mailTo);
                msg.Subject = subject;
                msg.Body = body;
 

                ArrayList annexList = ReadTxt(txtAnnexPath);

                for (int i = 0; i < annexList.Count; i++)

                {
                    msg.Attachments.Add(new Attachment(annexList[i].ToString()));
                }
 

                SmtpClient smtp = new SmtpClient("mail.163.com");

                smtp.Credentials = new NetworkCredential("***@****", "*******");
                smtp.Send(msg);
                mailSent = true;
                sucNum++;
            }

            catch (Exception ex)

            {

                WriteToTxt(DateTime.Now + "   Faild   Error Message:" + ex.Message, txtLogPath);

                this.notifyIcon1.ShowBalloonTip(Interval, "", ex.Message, ToolTipIcon.None);

                System.Threading.Thread.Sleep(Interval * 2);
                KillThread();
                MarkErrorMail(mailTo);
                mailSent = false;
            }

            return mailSent;

        }
 
//开始发送
        public void StartMailSend()
        {

            MailSend mailSend = new MailSend();

            mailSend.iTotalCount = mailTotalCount;

            mailSend.interval = Interval;
            mailSend.iSentCount = SentCount;
            mailSend.onMailSendProgress += new MailSend.dMailSendProgress(mailSend_onMailSendProgress);
            mailSend.Start();
        }
 
        //同步更新

        void mailSend_onMailSendProgress(int total, int current)

        {
            try
            {

                if (this.InvokeRequired)

                {

                    this.Invoke(new MailSend.dMailSendProgress(mailSend_onMailSendProgress), new object[] { total, current });

                }
                else
                {
                    InitMailList();

                    string percent = (((current + 1) *100) / mailTotalCount).ToString() + "%";

                    string progress = percent + " " + (current + 1) + "/" + mailTotalCount;

                    this.lableTimer.Text = progress;

                    this.notifyIcon1.ShowBalloonTip(Interval,"", progress,ToolTipIcon.None);//气泡提示信息

                    this.progressBar1.Maximum = total;

                    this.progressBar1.Value = current;

                   if (total > 0 && subject.Length > 0)

                    {                                                                                  

                        if (Send(mailto, subject, body))
                        {

                            UpdateMailState(mailto, 1);

                            LoadMailList();
                        }
                    }

                    if (current == total - 1)

                    {

                        this.notifyIcon1.ShowBalloonTip(Interval, "", "发送完毕,成功发送" + sucNum + "封", ToolTipIcon.None);

                        this.progressBar1.Visible = false;
                        this.lblProgress.Visible = false;

                        this.lableTimer.Text = "";

                        ControlEnabled(true);
                        return;
                    }
                }
            }
            catch(Exception ex)
            {

                this.notifyIcon1.ShowBalloonTip(Interval, "", ex.Message, ToolTipIcon.None);

                System.Threading.Thread.Sleep(Interval * 2);
                base.Dispose(true);
                Application.ExitThread();
                KillThread();
            }
        }
        /// 逐条读取未发送的邮件,具体代码就不在这里唠叨了,详见附件

        private void InitMailList(){}

        /// 加载邮件列表 (DataGridView),不是主要内容,如需了解,详见附件

        private void LoadMailList(){ }

        ///取状态为已发送的邮件个数,详见附件

       private void SentMailCount(){}

        ///修改邮箱状态,这里标记为10,详见附件

        private void MarkErrorMail(string mail) {}

        ///标记已发送或出错的邮箱,详见附件

        private void UpdateMailState(string mail, int state) {}

        /// 初始化时间长

        private void InitTime()

        {

            if (mailTotalCount > 0 && SentCount < mailTotalCount)

            {

                this.txtDateCount.Text = ((mailTotalCount - SentCount) * 10).ToString();

                this.lblTime.Text = TimeConvert((mailTotalCount - SentCount) * 10);

            }
        }
        /// 添加附件

        private void btnAnnexSelect_Click(object sender, EventArgs e)

        {

            OpenFileDialog ofd = new OpenFileDialog();

            ofd.InitialDirectory = Application.ExecutablePath;
            ofd.FileName = "";
            ofd.Filter = "所有文件(*)|*";

            string strFileName = "";

            if (ofd.ShowDialog() == DialogResult.OK)

            {
                strFileName = ofd.FileName;

                this.txtAnnex.Text = strFileName;

            }

            WriteToTxt(strFileName, txtAnnexPath);

            ArrayList list = ReadTxt(txtAnnexPath);

            if (list.Count > 0)

            {

                string str = string.Empty;

                for (int i = 0; i < list.Count; i++)

                {

                    string file = list[i].ToString();

                    str += "·¡è"+file.Substring(file.LastIndexOf("\\") + 1) + ";";
                }

                this.lblAnnexList.Text = str.Trim(";".ToCharArray());

            }
        }
       
        /// 结束进程

        private void KillThread()

        {

            foreach (System.Diagnostics.Process thisproc in System.Diagnostics.Process.GetProcesses())

            {

                if (thisproc.ProcessName.Equals("MailGroupSends"))

                {
                    thisproc.Kill();
                }
            }
        }
        #region 最小化到托盘

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)

        {

            this.ShowInTaskbar = true;

            this.WindowState = FormWindowState.Normal;

            this.Activate();
        }

        private void Form1_SizeChanged(object sender, EventArgs e)

        {

            if (this.WindowState == FormWindowState.Minimized)

                this.ShowInTaskbar = false;

        }
        #endregion
        /// 邮箱分类(comboBox)

        private void InitMailCategory()

       {

            OleDbConnection Conn = new OleDbConnection(ConnString);

            try
            {

                string sql = @"select categoryid,categoryname from mailCategory where recordstate=0";

                if (Conn.State == ConnectionState.Closed) Conn.Open();

                OleDbCommand cmd = new OleDbCommand(sql, Conn);

                OleDbDataReader reader = cmd.ExecuteReader();

                mailTotalCount = 0;

                DataTable table = new DataTable();

                table.Columns.Add("categoryid");
                table.Columns.Add("categoryname");

                DataRow row = table.NewRow();

                row[0] = "1000";
                row[1] = "全部";
                table.Rows.Add(row);

                while (reader.Read())

                {
                    row = table.NewRow();

                    row[0] = reader[0].ToString();

                    row[1] = reader[1].ToString();

                    table.Rows.Add(row);
                }
                reader.Close();

                if (reader != null) reader.Dispose();

 

                this.comboBox_mailcategory.ValueMember = "categoryid";

                this.comboBox_mailcategory.DisplayMember = "categoryname";

                this.comboBox_mailcategory.DataSource = table;

                this.comboBox_mailcategory.SelectedIndex = 0;

            }
            catch{}
           finally
            {

                if (Conn.State == ConnectionState.Open) Conn.Close();

                if (Conn != null) Conn.Dispose();

            }
        }
        /// 选择邮箱分类

        private void comboBox_mailcategory_SelectedIndexChanged(object sender, EventArgs e)

        {
            CategoryId =Convert.ToInt32(this.comboBox_mailcategory.SelectedValue);
            LoadMailList();
            SentMailCount();
            InitTime();
        }
        /// 时间长(秒)转换成时分秒格式

        private string TimeConvert(int time)

        {

            int h = time / 3600;

            int m = (time - h * 3600) / 60;

            int s = time - h * 3600 - m * 60;

            return h + "时" + m + "分" + s + "秒";

        }
        /// 验证邮件格式是否正确

        private bool IsEmail(string email)

        {

            string strExp = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";

            Regex r = new Regex(strExp);

            Match m = r.Match(email);

            return m.Success ? true : false;

        }
 
        #region TxtOperator
        //由于篇幅有限,这里就不具体贴出了,如需了解,详见附件
        #endregion
}
 
    public class MailSend
    {
        //委托

        public delegate void dMailSendProgress(int total, int current);

        //事件

        public event dMailSendProgress onMailSendProgress;

 
        public int iTotalCount;
        public int interval;
        public int iSentCount;
        //开始模拟工作
        public void Start()
        {

            for (int i = iSentCount; i < iTotalCount; i++)

            {

                if (onMailSendProgress != null)

                    onMailSendProgress(iTotalCount, i);

                Thread.Sleep(interval);
            }
        }
    }
}

点击下载源码