概要:
子线程工作,发送成功邮件做标记,逐条提取数据,气泡提示信息,最小化到托盘,实时进度条
代码:
using System;
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
{
publicForm1()
{
InitializeComponent();
}
privatestring subject = string.Empty;
privatestring mailto = string.Empty;
privatestring body = string.Empty;
privateint sucNum = 0;
privateint TotalDate
{
get
{
if(this.txtDateCount.Text.Trim().Length > 0)
returnConvert.ToInt32(this.txtDateCount.Text.Trim());
return4;
}
set{ this.txtDateCount.Text = value.ToString(); }
}
privatestring ConnString
{
get
{
stringpathFull = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
stringpath = pathFull.Substring(0, pathFull.LastIndexOf(@"\"));
return@"Provider=Microsoft.Jet.OLEDB.4.0;DataSource=" + path + @"\mail.mdb";
}
}
privatebool mailSent = false; //邮件是否发送成功
privateint mailTotalCount = 0;
privateint CategoryId = 0;
privateint SentCount = 0; //已发送数
privateint UnitConversion = 1; //默认为秒
/// <summary>
/// 发送间隔
/// </summary>
privateint Interval
{
get
{
inttimer = 0;
inttotalMis = (TotalDate * UnitConversion * 1000);
timer = totalMis /(mailTotalCount-SentCount);
returntimer;
}
}
/// <summary>
/// 提取邮件
/// </summary>
privatevoid InitMailList()
{
OleDbConnectionConn = new OleDbConnection(ConnString);
try
{
stringstrWhere = CategoryId == 1000 ? "": " and categoryid=" + CategoryId+ " order by isSend,uyx";
stringsqlStr = @"select top 1 uyx from [usermail]where isDelete=0 and IsSend=0 " + strWhere;
if(Conn.State == ConnectionState.Closed)Conn.Open();
OleDbCommandcmd = new OleDbCommand(sqlStr,Conn);
OleDbDataReaderreader = cmd.ExecuteReader();
mailto = string.Empty;
while(reader.Read())
{
mailto +=reader[0].ToString() + ",";
}
reader.Close();
if(reader != null) reader.Dispose();
mailto = mailto.Trim(",".ToCharArray());
}
catch(Exception ex)
{
MessageBox.Show(ex.Message,"错误", MessageBoxButtons.OK,MessageBoxIcon.Error);
}
finally
{
if(Conn.State == ConnectionState.Open)Conn.Close();
if(Conn != null) Conn.Dispose();
}
}
/// <summary>
/// 加载邮件列表
/// </summary>
privatevoid LoadMailList()
{
this.dataGridView1.Columns.Clear();
if(this.dataGridView1.Rows.Count > 0)
this.dataGridView1.Rows.Clear();
dataGridView1.RowHeadersWidth = 21;
DataGridViewTextBoxColumncolumn = new DataGridViewTextBoxColumn();
column.ReadOnly = true;
column.HeaderText = "邮箱列表";
column.DisplayIndex = 0;
column.Name = "邮箱列表";
column.Width = 120;
dataGridView1.Columns.Add(column);
column = newDataGridViewTextBoxColumn();
column.ReadOnly = true;
column.HeaderText = "状态";
column.DisplayIndex = 1;
column.Name = "状态";
column.Width = 60;
dataGridView1.Columns.Add(column);
OleDbConnectionConn = new OleDbConnection(ConnString);
try
{
stringstrWhere = CategoryId == 1000 ? "": " and categoryid=" + CategoryId+ " order by isSend,uyx";
stringsql = @"select uyx,IsSend from usermail whereisDelete=0 "+strWhere;
if(Conn.State == ConnectionState.Closed)Conn.Open();
OleDbCommandcmd = new OleDbCommand(sql,Conn);
OleDbDataReaderreader = cmd.ExecuteReader();
mailTotalCount = 0;
while(reader.Read())
{
DataGridViewRowdgvr = new DataGridViewRow();
DataGridViewTextBoxCellcell = new DataGridViewTextBoxCell();
cell.Value =reader[0].ToString();
dgvr.Cells.Add(cell);
cell = new DataGridViewTextBoxCell();
cell.Value = "●";
cell.Style.ForeColor = Convert.ToInt32(reader[1]) == 0 ? System.Drawing.Color.Yellow : System.Drawing.Color.Green;
dgvr.Cells.Add(cell);
dataGridView1.Rows.Add(dgvr);
mailTotalCount++;
}
reader.Close();
if(reader != null) reader.Dispose();
this.lblmailCount.Text= "(" + SentCount + "/"+ mailTotalCount + ")";
}
catch
{
}
finally
{
if(Conn.State == ConnectionState.Open)Conn.Close();
if(Conn != null) Conn.Dispose();
}
}
/// <summary>
/// 已发送邮件个数
/// </summary>
private voidSentMailCount()
{
OleDbConnectionConn = new OleDbConnection(ConnString);
try
{
stringstrWhere = CategoryId == 1000 ? "": " and categoryid=" + CategoryId;
stringsqlStr = @"select uyx from [usermail] whereisDelete=0 and IsSend=1 " + strWhere;
if(Conn.State == ConnectionState.Closed)Conn.Open();
OleDbDataAdapteradapter = new OleDbDataAdapter(sqlStr,Conn);
DataSetds = new DataSet();
adapter.Fill(ds);
SentCount =ds.Tables[0].Rows.Count;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message,"错误", MessageBoxButtons.OK,MessageBoxIcon.Error);
}
finally
{
if(Conn.State == ConnectionState.Open)Conn.Close();
if(Conn != null) Conn.Dispose();
}
}
/// <summary>
/// 标记出错的邮箱
/// </summary>
/// <paramname="mail"></param>
privatevoid MarkErrorMail(stringmail)
{
OleDbConnectionConn = new OleDbConnection(ConnString);
try
{
stringsql = "update usermail set IsDelete=10 whereuyx='" + mail + "' ";
if(Conn.State == ConnectionState.Closed)Conn.Open();
OleDbCommandcmd = new OleDbCommand(sql,Conn);
cmd.ExecuteNonQuery();
}
catch
{ }
finally
{
if(Conn.State == ConnectionState.Open)Conn.Close();
if(Conn != null) Conn.Dispose();
}
}
/// <summary>
/// 修改已发送邮件状态
/// </summary>
/// <param name="mail"></param>
privatevoid UpdateMailState(stringmail, int state)
{
OleDbConnectionConn = new OleDbConnection(ConnString);
try
{
stringwhere = string.Empty;
if(mail.Length > 0)
{
WriteToTxt(DateTime.Now + " Success " + mail, txtLogPath);
if(mail.IndexOf(",") > -1)
where = " and uyx ='" + mail.Replace(",", "'and uyx='") + "' ";
else
where = " and uyx='" + mail + "'";
}
else
{
where = " and IsSend=1";
}
stringcategory = CategoryId == 1000 ? "": " and categoryid=" + CategoryId;
stringsql = "update usermail set IsSend="+ state + " where IsDelete=0 " +category + where;
if(Conn.State == ConnectionState.Closed)Conn.Open();
OleDbCommandcmd = new OleDbCommand(sql,Conn);
cmd.ExecuteNonQuery();
}
catch
{ }
finally
{
if(Conn.State == ConnectionState.Open)Conn.Close();
if(Conn != null) Conn.Dispose();
}
}
/// <summary>
/// 邮件发送
/// </summary>
/// <paramname="mailTo"></param>
/// <paramname="subject"></param>
/// <paramname="body"></param>
/// <returns></returns>
privatebool Send(stringmailTo, string subject, string body)
{
try
{
if(!IsEmail(mailTo))
{
WriteToTxt(DateTime.Now + " Faild " + mailTo, txtLogPath + " Error Message:邮箱格式不正确");
MarkErrorMail(mailTo);
returnfalse;
}
if(mailTo.Substring(mailTo.Length - 1) == "."|| mailTo.Substring(mailTo.Length - 1) == ",")
{
WriteToTxt(DateTime.Now + " Faild " + mailTo, txtLogPath + " Error Message:邮箱格式不正确");
MarkErrorMail(mailTo);
returnfalse;
}
MailMessagemsg = 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;
ArrayListannexList = ReadTxt(txtAnnexPath);
for(int i = 0; i < annexList.Count; i++)
{
msg.Attachments.Add(new Attachment(annexList[i].ToString()));
}
SmtpClientsmtp = new SmtpClient("mail.163.com");
smtp.Credentials = new NetworkCredential("***@****", "*******");
smtp.Send(msg);
mailSent = true;
sucNum++;
}
catch(Exception ex)
{
if(ex.Message.IndexOf("http://www.ipmotor.com/smtp_err.htm")> -1)
{
WriteToTxt(DateTime.Now + " Faild Error Message:" + ex.Message, txtLogPath);
this.notifyIcon1.ShowBalloonTip(Interval,"", ex.Message, ToolTipIcon.None);
System.Threading.Thread.Sleep(Interval * 2);
base.Dispose(true);
Application.ExitThread();
KillThread();
}
WriteToTxt(DateTime.Now + " Faild " + mailTo + " Error Message:" + ex.Message,txtLogPath);
MarkErrorMail(mailTo);
mailSent = false;
}
returnmailSent;
}
//*******************************************************************//
//开始发送
public void StartMailSend()
{
MailSendmailSend = new MailSend();
mailSend.iTotalCount =mailTotalCount;
mailSend.interval = Interval;
mailSend.iSentCount = SentCount;
mailSend.onMailSendProgress += new MailSend.dMailSendProgress(mailSend_onMailSendProgress);
mailSend.Start();
}
//同步更新
voidmailSend_onMailSendProgress(int total, int current)
{
try
{
if(this.InvokeRequired)
{
this.Invoke(new MailSend.dMailSendProgress(mailSend_onMailSendProgress), new object[] { total,current });
}
else
{
InitMailList();
stringpercent = (((current + 1) *100) / mailTotalCount).ToString() + "%";
stringprogress = 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)
{
mailto =mailto.Replace(" ", ",");
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 voidForm1_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls= false;
InitMailCategory();
SentMailCount();
LoadMailList();
ClearTxt(txtAnnexPath);
InitTime();
}
/// <summary>
/// 初始化时间长
/// </summary>
privatevoid InitTime()
{
if(mailTotalCount > 0 && SentCount < mailTotalCount)
{
this.txtDateCount.Text= ((mailTotalCount - SentCount) * 10).ToString();
this.lblTime.Text= TimeConvert((mailTotalCount - SentCount) * 10);
}
}
/// <summary>
/// 附件
/// </summary>
/// <paramname="sender"></param>
/// <paramname="e"></param>
privatevoid btnAnnexSelect_Click(object sender, EventArgse)
{
OpenFileDialogofd = new OpenFileDialog();
ofd.InitialDirectory = Application.ExecutablePath;
ofd.FileName = "";
ofd.Filter = "所有文件(*)|*";
stringstrFileName = "";
if(ofd.ShowDialog() == DialogResult.OK)
{
strFileName = ofd.FileName;
this.txtAnnex.Text= strFileName;
}
WriteToTxt(strFileName,txtAnnexPath);
ArrayListlist = ReadTxt(txtAnnexPath);
if(list.Count > 0)
{
stringstr = string.Empty;
for(int i = 0; i < list.Count; i++)
{
stringfile = list[i].ToString();
str += "·¡è"+file.Substring(file.LastIndexOf("\\") + 1) + ";";
}
this.lblAnnexList.Text= str.Trim(";".ToCharArray());
}
}
/// <summary>
/// 发送
/// </summary>
/// <paramname="sender"></param>
/// <paramname="e"></param>
privatevoid btnSendMail_Click(objectsender, EventArgs e)
{
if(this.txtDateCount.Text.Trim().Length == 0 ||!IsNumber(this.txtDateCount.Text.Trim()))
{
MessageBox.Show("请正确设定计划用时");
return;
}
TotalDate = Convert.ToInt32(this.txtDateCount.Text.Trim());
if(UnitConversion==1&& this.lblTime.Text.Length==0)
this.lblTime.Text= TimeConvert(TotalDate);
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();
}
/// <summary>
/// 刷新
/// </summary>
/// <paramname="sender"></param>
/// <paramname="e"></param>
privatevoid btnRefresh_Click(objectsender, EventArgs e)
{
LoadMailList();
}
/// <summary>
/// 邮件状态重置
/// </summary>
/// <paramname="sender"></param>
/// <paramname="e"></param>
privatevoid btnMailStateReSet_Click(object sender, EventArgse)
{
UpdateMailState("", 0);
SentMailCount();
LoadMailList();
InitTime();
}
/// <summary>
/// 关闭
/// </summary>
/// <param name="sender"></param>
/// <paramname="e"></param>
privatevoid btnClose_Click(objectsender, EventArgs e)
{
base.Dispose(true);
Application.ExitThread();
KillThread();
}
/// <summary>
/// 结束进程
/// </summary>
privatevoid KillThread()
{
foreach(System.Diagnostics.Process thisproc in System.Diagnostics.Process.GetProcesses())
{
if(thisproc.ProcessName.Equals("MailGroupSends"))
{
thisproc.Kill();
}
}
}
/// <summary>
/// 状态
/// </summary>
/// <paramname="state"></param>
privatevoid ControlEnabled(boolstate)
{
this.txtDateCount.Enabled= state;
this.rbHours.Enabled= state;
this.rbMinutes.Enabled= state;
this.rbtSeconds.Enabled= state;
this.txtSubject.Enabled= state;
this.rtxtBody.Enabled= state;
this.txtAnnex.Enabled= state;
this.btnAnnexSelect.Enabled= state;
this.btnSendMail.Enabled= state;
this.btnRefresh.Enabled= state;
this.btnMailStateReSet.Enabled= state;
this.comboBox_mailcategory.Enabled= state;
this.lableTimer.Text= string.Empty;
}
/// <summary>
/// 时
/// </summary>
/// <paramname="sender"></param>
/// <paramname="e"></param>
privatevoid rbHours_Click(objectsender, EventArgs e)
{
this.UnitConversion= 3600;
this.lblTime.Text= "";
}
/// <summary>
/// 分
/// </summary>
/// <paramname="sender"></param>
/// <param name="e"></param>
privatevoid rbMinutes_Click(objectsender, EventArgs e)
{
this.UnitConversion= 60;
this.lblTime.Text= "";
}
/// <summary>
/// 秒
/// </summary>
/// <param name="sender"></param>
/// <paramname="e"></param>
privatevoid rbtSeconds_Click(objectsender, EventArgs e)
{
this.UnitConversion= 1;
}
#region 最小化到托盘
privatevoid notifyIcon1_MouseDoubleClick(object sender, MouseEventArgse)
{
this.ShowInTaskbar= true;
this.WindowState= FormWindowState.Normal;
this.Activate();
}
privatevoid Form1_SizeChanged(objectsender, EventArgs e)
{
if(this.WindowState == FormWindowState.Minimized)
this.ShowInTaskbar= false;
}
#endregion
/// <summary>
/// 邮箱分类
/// </summary>
privatevoid InitMailCategory()
{
OleDbConnectionConn = new OleDbConnection(ConnString);
try
{
stringsql = @"select categoryid,categoryname frommailCategory where recordstate=0";
if(Conn.State == ConnectionState.Closed)Conn.Open();
OleDbCommandcmd = new OleDbCommand(sql,Conn);
OleDbDataReaderreader = cmd.ExecuteReader();
mailTotalCount = 0;
DataTabletable = new DataTable();
table.Columns.Add("categoryid");
table.Columns.Add("categoryname");
DataRowrow = table.NewRow();
row[0] = "1000";
row[1] = "全部";
table.Rows.Add(row);
row = table.NewRow();
row[0] = "0";
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();
}
}
/// <summary>
/// 选择邮箱分类
/// </summary>
/// <paramname="sender"></param>
/// <paramname="e"></param>
privatevoidcomboBox_mailcategory_SelectedIndexChanged(objectsender, EventArgs e)
{
CategoryId =Convert.ToInt32(this.comboBox_mailcategory.SelectedValue);
LoadMailList();
SentMailCount();
InitTime();
}
/// <summary>
/// 时间长(秒)转换成时分秒格式
/// </summary>
/// <paramname="time"></param>
/// <returns></returns>
privatestring TimeConvert(inttime)
{
inth = time / 3600;
intm = (time - h * 3600) / 60;
ints = time - h * 3600 - m * 60;
returnh + "时" + m + "分" + s + "秒";
}
/// <summary>
/// 验证邮件格式是否正确
/// </summary>
/// <paramname="email"></param>
/// <returns></returns>
privatebool IsEmail(stringemail)
{
stringstrExp = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
Regexr = new Regex(strExp);
Matchm = r.Match(email);
returnm.Success ? true : false;
}
/// <summary>
/// 是否为整数
/// </summary>
/// <paramname="txt"></param>
/// <returns></returns>
privatebool IsNumber(stringtxt)
{
boolflag = false;
try
{
intnum = Convert.ToInt32(txt);
flag = true;
}
catch
{
flag = false;
}
returnflag;
}
#region TxtOperator
privatestring txtAnnexPath
{
get
{
stringpathFull = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
stringpath = pathFull.Substring(0, pathFull.LastIndexOf(@"\"));
returnpath + @"\Annex.txt";
}
}
privatestring txtLogPath
{
get
{
stringpathFull = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
stringpath = pathFull.Substring(0, pathFull.LastIndexOf(@"\"));
returnpath + @"\Log.txt";
}
}
public voidWriteToTxt(string txt, stringfilePath)
{
System.IO.FileInfoerrfile = new System.IO.FileInfo(filePath);
if(!errfile.Exists)
{
System.IO.FileStream fs = System.IO.File.Create(filePath);
fs.Close();
}
System.IO.StreamWritersrWriteLine = System.IO.File.AppendText(filePath);
srWriteLine.WriteLine(txt);
srWriteLine.Close();
}
public ArrayList ReadTxt(stringfilePath)
{
stringtxt = string.Empty;
System.IO.FileInfoerrfile = new System.IO.FileInfo(filePath);
if(!errfile.Exists)
{
System.IO.FileStream fs = System.IO.File.Create(filePath);
fs.Close();
}
System.IO.StreamReaderobjReader = new System.IO.StreamReader(filePath);
stringsLine = "";
ArrayListarrText = new ArrayList();
while(sLine != null)
{
sLine = objReader.ReadLine();
if(sLine != null)
arrText.Add(sLine);
}
objReader.Close();
returnarrText;
}
public void ClearTxt(stringfilePath)
{
System.IO.FileInfoerrfile = new System.IO.FileInfo(filePath);
if(ReadTxt(filePath).Count > 0)
{
System.IO.FileStream fs = System.IO.File.Create(filePath);
fs.Close();
}
}
#endregion
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace MailGroupSends
{
public class MailSend
{
//委托
public delegate void dMailSendProgress(inttotal, int current);
//事件
public event dMailSendProgressonMailSendProgress;
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);
}
}
}
}