本程序利用VS2013工具开发的,用的是.net farmework3.5。主要给公司HR实现批量发工资条和拆分工资条!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace SendEmail
{
public partial class FrmMain : Form
{
string receiveAppendixColumn = "附件";
string receiveMailAddressColumn = "邮件地址";
string extention = "xlsx"; //遍历目录的 默认扩展名。
List<string> emails = new List<string>();
string body; //设置主体内容
string sbject; //设置主题
/// <summary>
/// 导入文件路径
/// </summary>
string inportFile = "";
/// <summary>
/// 上次选择的email收件人列
/// </summary>
int emailReveiveBeforIndex = -1;
/// <summary>
/// 上次选择的附件列
/// </summary>
int emailAppendixIndex = -1;
/// <summary>
/// 处理结果 的列名
/// </summary>
private string resultColumnName = "处理结果";
/// <summary>
/// 所有收邮件用户的信息,如邮件地址,附件地址....
/// </summary>
List<ReceiveUser> receiveUsers;
/// <summary>
/// 当前选择发送的邮箱账号
/// </summary>
EmailUser curUser = null;
/// <summary>
/// 发用邮件的抽象类
/// </summary>
MailAbstract mail;
public FrmMain()
{
InitializeComponent();
}
private void LoadGlobalConfig()
{
GlobalConfig config = new GlobalConfig();
receiveAppendixColumn = config.GetAppendixColumn();//得到附件列
receiveMailAddressColumn = config.GetReceiveEmail(); //得到收邮件列
if(!string.IsNullOrEmpty(config.GetExtention()))
{
extention = config.GetExtention();
}
if (config.isSendFujian()) //是否发送附件
{
chkAppendix.Checked = true;
}
else
{
chkAppendix.Checked = false;
}
}
#region Load 加载
private void FrmMain_Load(object sender, EventArgs e)
{
try
{
LoadGlobalConfig();
LoadUser();
}
catch
{
// MessageBox.Show("加载失败" ex.Message);
}
}
#endregion
#region 从XML文件加载用户信息 - LoadUser()
private void LoadUser()
{
XMLAccountInfo account = new XMLAccountInfo();
List<EmailUser> users = account.GetAllExchangAccout();
if (users != null && users.Count > 0)
{
cbmEmail.DisplayMember = "Email";
cbmEmail.DataSource = users;
cbmEmail.SelectedIndex = 0;
curUser = users[0];
//txtSendMail.Text = curUser.Email;
//txtDispalyName.Text = curUser.SendName;
//txtSendPwd.Text = curUser.Password;
//txtSmtp.Text = curUser.EmailServer;
}
}
#endregion
#region 将 DatagivdView.DataSource 转成table; -DgvSourceToTable(DataGridView dgv)
/// <summary>
/// 将 DatagivdView.DataSource 转成table;
/// </summary>
/// <param name="dgv">DatagidView控件 </param>
/// <returns>返回 Table</returns>
private DataTable DgvSourceToTable(DataGridView dgv)
{
DataTable table = new DataTable();
foreach (DataGridViewColumn column in dgv.Columns)
{
table.Columns.Add(column.Name);
}
for (int row = dgv.Rows.Count - 1; row > -1; row--)
{
if (dgv.Rows[row].Cells[0].Value != null)
{
DataRow Rowcount = table.Rows.Add();
foreach (DataGridViewColumn column in dgv.Columns)
{
Rowcount[column.Name] = dgv.Rows[row].Cells[column.Name].Value.ToString();
}
}
}
return table;
}
private void tsExchangeAccont_Click(object sender, EventArgs e)
{
FrmExchangAccout exchang = new FrmExchangAccout();
exchang.ShowDialog();
LoadUser();
}
#endregion
#region 画出行号
/// <summary>
/// 画出行号
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dgvShow_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
System.Drawing.Rectangle rectangle =
new System.Drawing.Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, dgvShow.RowHeadersWidth - 4, e.RowBounds.Height);
TextRenderer.DrawText(e.Graphics, (e.RowIndex 1).ToString(),
dgvShow.RowHeadersDefaultCellStyle.Font,
rectangle,
dgvShow.RowHeadersDefaultCellStyle.ForeColor,
TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
}
#endregion
#region 选择账号改变事件 - cbmEmail_SelectedIndexChanged(object sender, EventArgs e)
private void cbmEmail_SelectedIndexChanged(object sender, EventArgs e)
{
curUser = cbmEmail.SelectedItem as EmailUser; //获取账号信息
SelectNextControl(Form.ActiveForm, true, true, true, true); //让当前控件失去焦点
}
#endregion
#region 导入EXCEL -tsInportFile_Click(object sender, EventArgs e)
private void tsInportFile_Click(object sender, EventArgs e)
{
OpenFileDialog file = new OpenFileDialog();
file.Filter = "Excel文件 (*.xlsx)|*.xlsx|所有文件 (*.*)|*.*";
if (file.ShowDialog() == DialogResult.OK)
{
try
{
// ExcelOperator excel = new ExcelOperator();
emailReveiveBeforIndex = -1; //清空上次导入记录的列
emailAppendixIndex = -1; //清空上次导入记录的列
dgvShow.Columns.Clear();//清空所有 列
EPPlusHelper excel = new EPPlusHelper();
inportFile = file.FileName;
DataTable tb = excel.ExcelToTable(inportFile);
dgvShow.DataSource = tb;
if (!string.IsNullOrEmpty(receiveAppendixColumn)) //如果receiveAppendixColumn为null 不检查为异常
{
if (dgvShow.Columns.Contains(receiveAppendixColumn))
{
dgvShow.Columns[receiveAppendixColumn].DefaultCellStyle.BackColor = ColorHelper.fujianColor;
emailAppendixIndex = dgvShow.Columns[receiveAppendixColumn].Index;
}
}
if (!string.IsNullOrEmpty(receiveMailAddressColumn)) //如果receiveMailAddressColumn为null 不检查为异常
{
if (dgvShow.Columns.Contains(receiveMailAddressColumn))
{
dgvShow.Columns[receiveMailAddressColumn].DefaultCellStyle.BackColor = ColorHelper.emailColor;
emailReveiveBeforIndex = dgvShow.Columns[receiveMailAddressColumn].Index;
}
}
//else
//{
// MessageBox.Show(string.Format("导入的文件必须包含\"{0}\"列和\"{1}\"列", receiveMailAddressColumn, reveiveNameColumn));
//}
// dgvShow.Columns[0].DefaultCellStyle.BackColor = ColorHelper.emailColor; // Color.GreenYellow;
//dgvShow.Columns[1].DefaultCellStyle.BackColor = Color.Gray;
}
catch (Exception ex)
{
MessageBox.Show("导入失败 " ex.Message);
}
}
DisbleSort();
}
#endregion
#region 导出EXCEL -tsOutFile_Click(object sender, EventArgs e)
private void tsOutFile_Click(object sender, EventArgs e)
{
//string dir = Common.ExcelSaveDir;
//if (!System.IO.Directory.Exists(dir))
//{
// System.IO.Directory.CreateDirectory(dir);
//}
//string fileName = dir "\\处理结果 " DateTime.Now.ToString("yyyy年MM月dd日hh时mm分ss秒") ".xlsx";
//Expout(fileName);
SaveFileDialog save = new SaveFileDialog();
save.Filter = "Excel文件 (*.xlsx)|*.xlsx|所有文件 (*.*)|*.*";
if (save.ShowDialog() == DialogResult.OK)
{
string fileName = save.FileName;
Expout(fileName);
MessageBox.Show("导出成功");
}
}
#endregion
#region 导出文件 -void Expout(string fileName)
/// <summary>
/// 导出文件
/// </summary>
/// <param name="fileName"></param>
private void Expout(string fileName)
{
// ExcelOperator excel = new ExcelOperator();
EPPlusHelper excel = new EPPlusHelper();
DataTable table = DgvSourceToTable(dgvShow);
excel.ExportExcel(table, fileName);
}
#endregion
#region 获取收件人相关信息, 返回没有添加附件的数量 - int GetAllReceiveUserInfo()
/// <summary>
/// 获取收件人相关信息, 返回没有添加附件的数量 写法有些...
/// </summary>
private int GetAllReceiveUserInfo()
{
int noAppendixNum = 0; //没有附件数量
ReceiveUser receice;
bool fuJianIsChecked = chkAppendix.Checked; //是否添加附件
receiveUsers = new List<ReceiveUser>();//所有收件人列表
string filedir = Common.ExcelSaveDir; //发送文件附件目录
RegexFind emailReg = new RegexFind();
for (int row = 0; row < dgvShow.Rows.Count - 1; row ) //获取dgvShow表信息
{
receice = new ReceiveUser();
string email = dgvShow.Rows[row].Cells[receiveMailAddressColumn].Value.ToString();
if (fuJianIsChecked)//如果选择添加附件就添加
{
string name = dgvShow.Rows[row].Cells[receiveAppendixColumn].Value.ToString();
string fujianPath = filedir "\\" name "." extention;
if (!System.IO.File.Exists(fujianPath))
{
dgvShow.Rows[row].Cells[resultColumnName].Value = "附件没找到";
dgvShow.Rows[row].Cells[resultColumnName].Style.BackColor = Color.Red;
noAppendixNum ;
continue;
}
if (string.IsNullOrEmpty(name))
{
dgvShow.Rows[row].Cells[resultColumnName].Value = "收件人姓名不能为空";
}
receice.Name = name;
receice.FilePath = fujianPath;
}
if (emailReg.IsEmail(email)) //如果是Email
{
receice.EmailAddress = email;
receice.RowNum = row;
receiveUsers.Add(receice); //把当前用户加入待发送邮件 列表中
dgvShow.Rows[row].Cells[resultColumnName].Style.BackColor = Color.White;
}
else
{
dgvShow.Rows[row].Cells[resultColumnName].Value = "邮件地址不正确";
dgvShow.Rows[row].Cells[resultColumnName].Style.BackColor = Color.Red;
}
}
return noAppendixNum;
}
#endregion
#region 检查输入的内容,并附加签名内容 -string CheckInputContext()
/// <summary>
/// 检查输入的内容,并附加签名内容
/// </summary>
/// <returns></returns>
private string CheckInputContext()
{
// string resultStr = "";
string qianMing = ""; //定义签名内容
if (System.IO.File.Exists(Common.QianMingPath))
{
qianMing = System.IO.File.ReadAllText(Common.QianMingPath, Encoding.UTF8).Replace("src=\"", "src=\"cid:");
}
body = txtContent.Text qianMing; //设置主体内容,附加了签名
sbject = txtSubject.Text; //5设置主题
body = body.Replace("\r\n", ""); //替换掉换行标签
if (sbject.Trim() == "")
{
return "主题不能为空";
}
return "";
}
#endregion
#region 添加处理结果行 -void AddResultColumn()
/// <summary>
/// 添加处理结果行
/// </summary>
private void AddResultColumn()
{
if (!dgvShow.Columns.Contains(resultColumnName))
{
dgvShow.Columns.Add(resultColumnName, resultColumnName); //添加一列
}
else
{
dgvShow.Columns.Remove(resultColumnName);
dgvShow.Columns.Add(resultColumnName, resultColumnName); //添加一列
}
}
#endregion
#region 禁用dgvShow中排序 -void DisbleSort()
/// <summary>
/// 禁用dgvShow中排序
/// </summary>
public void DisbleSort()
{
for (int i = 0; i < this.dgvShow.Columns.Count; i )
{
this.dgvShow.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
}
}
#endregion
public string ReplaceBody(int row, string Curbody)
{
List<ColumnRelation> columnsName = new ColumnRelation().GetReveviceUser(); //得到所有列
if (columnsName != null && columnsName.Count > 0)
{
foreach (ColumnRelation columnName in columnsName)
{
string replaceColumnName = columnName.ExcelColumnName;
string replaceColumnValue = columnName.ExcelColumnReplace;
if (dgvShow.Columns.Contains(replaceColumnName))
{
if (dgvShow.Rows[row].Cells[replaceColumnName] != null)
{
Curbody = Curbody.Replace(replaceColumnValue, dgvShow.Rows[row].Cells[replaceColumnName].Value.ToString());
}
}
}
}
else
{
return body;
}
return Curbody;
}
#region 多线程发送邮件 void SendMailMutiply()
string sendBody;
private void SendMailMutiply()
{
this.Invoke((EventHandler)delegate { btnSendMail.Text = "停止"; });
bool isLogin = mail.Login(); //登陆邮件服务器
if (!isLogin)
{
MessageBox.Show("登陆失败,请检查网络, 用户名或密码是否正确");
this.Invoke((EventHandler)delegate { btnSendMail.Text = "发送"; });
return;
}
; //替换body中的内容,想当把 body中插入excel列指定的字符替换掉
SendMailResult result = new SendMailResult();
for (int i = 0; i < receiveUsers.Count; i )
{
ReceiveUser CurReveiveUser = receiveUsers[i];
sendBody = ReplaceBody(i, body);
ErrorMsg err = SendEmail(CurReveiveUser); //发送邮件
if (!err.SendStatu) //如果发送失败
{
// mail.Login(); //重新登陆,不过SNMP默认都是true;
if (CurReveiveUser.SendFaildCount == 0) //如果失败次数为0,就重新发送
{
dgvShow.Rows[CurReveiveUser.RowNum].Cells[resultColumnName].Value = "发送失败,等待重新发送...";
dgvShow.Rows[CurReveiveUser.RowNum].Cells[resultColumnName].Style.BackColor = Color.Red;
SendEmail(CurReveiveUser);
CurReveiveUser.SendFaildCount ;
if(!err.SendStatu)
{
result.FaildCount ; ;//记录发送失败的数量
dgvShow.Rows[CurReveiveUser.RowNum].Cells[resultColumnName].Value = "发送失败";
dgvShow.Rows[CurReveiveUser.RowNum].Cells[resultColumnName].Style.BackColor = Color.Red;
}
else
{
result.SuccessCount ; //记录发送成功的数量
dgvShow.Rows[CurReveiveUser.RowNum].Cells[resultColumnName].Value = "发送邮件成功";
dgvShow.Rows[CurReveiveUser.RowNum].Cells[resultColumnName].Style.BackColor = Color.White;
}
}
}
else
{
result.SuccessCount ;//记录发送成功的数量
dgvShow.Rows[CurReveiveUser.RowNum].Cells[resultColumnName].Value = "发送邮件成功";
dgvShow.Rows[CurReveiveUser.RowNum].Cells[resultColumnName].Style.BackColor = Color.White;
}
}
this.Invoke((EventHandler)delegate { btnSendMail.Text = "发送";
MessageBox.Show(string.Format("发送成功{0}封,未发送数量{1}", result.SuccessCount, result.FaildCount));
});
}
#endregion
#region 发送邮件 -SendEmail()
private ErrorMsg SendEmail(ReceiveUser CurReveiveUser)
{
List<string> str = new List<string>(); //增加附件
if (!string.IsNullOrEmpty(CurReveiveUser.FilePath)) //如果存在就添加附件
{
str.Add(CurReveiveUser.FilePath); //增加附件 // str.Add("mimi.txt"); //str.Add("haha.png");
}
ErrorMsg err = mail.SendMail(sbject, CurReveiveUser.EmailAddress, sendBody, str, ""); //发送邮件
return err;
}
#endregion
private void tsQianMing_Click(object sender, EventArgs e)
{
FrmQianMing qianming = new FrmQianMing();
qianming.ShowDialog();
}
/*
private void button1_Click(object sender, EventArgs e)
{
RegexFind find = new RegexFind();
string qianMing = ""; //定义签名内容
if (System.IO.File.Exists(Common.QianMingPath))
{
qianMing = System.IO.File.ReadAllText(Common.QianMingPath,Encoding.UTF8);
}
find.FindText(qianMing);
}
*/
#region 批量发送邮件事件 -void BtnSendMail_Click(object sender, EventArgs e)
private void BtnSendMail_Click(object sender, EventArgs e)
{
}
#endregion
Thread thread;
/// <summary>
/// 准备开始发送邮件
/// </summary>
private void BeginSendMail()
{
if (curUser == null)
{
MessageBox.Show("请先添加发件人账号");
}
if (dgvShow.Rows.Count <= 0) //检查是否有导入的信息
{
MessageBox.Show("请导入收件人相关信息");
return;
}
if(!ChedkIsSetColumn())// 检查是否设置邮件收件人列和附件列
{
return;
}
AddResultColumn(); //添加处理结果行
string result = CheckInputContext(); //检查输入信息
if (!string.IsNullOrEmpty(result))
{
MessageBox.Show(result);
dgvShow.Columns.Remove(resultColumnName);
return;
}
int errorNum = GetAllReceiveUserInfo(); // 得到收件人相关信息 ,并添加附件信息
if (errorNum > 0)
{
if (MessageBox.Show("没有附件数为" errorNum " 是否发送已经添加附件的邮件", "是否发送已添加附件的邮件", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
{
return;
}
}
if (curUser.SendMailIsExchange())
{
mail = new Exchang(curUser.SendName, curUser.Email,curUser.Password);//需要加判断
}
else
{
mail = new Smtp(curUser.SendName, curUser.Email,curUser.Password, curUser.EmailServer);
}
thread = new Thread(SendMailMutiply);
thread.IsBackground = true;
thread.Start();
}
/// <summary>
/// 检查是否设置邮件收件人列和附件列
/// </summary>
private bool ChedkIsSetColumn()
{
if (!dgvShow.Columns.Contains(receiveMailAddressColumn))
{
MessageBox.Show("请在表格中单击需设置成收件人列中的任意单元格,再右键选择\"设置成附件列\"");
return false;
}
if (chkAppendix.Checked)
{
if (!dgvShow.Columns.Contains(receiveAppendixColumn))
{
MessageBox.Show("请在表格中请单击需设置成附件列中的任意单元格,再右键选择\"设置成附件列\"");
return false;
}
}
return true;
}
private void tsGlobalConfig_Click(object sender, EventArgs e)
{
FrmGlobalConfig column = new FrmGlobalConfig();
column.ShowDialog();
try
{
LoadGlobalConfig();
}
catch
{
// throw;
}
}
//自定义列于Excel列对应关系
private void tsColumnRelation_Click(object sender, EventArgs e)
{
FrmExcelColumn column = new FrmExcelColumn();
column.ShowDialog();
}
private void tsGetFiles_Click(object sender, EventArgs e)
{
// new ExcelOperator().CopyRow();
}
private void tsHelp_Click(object sender, EventArgs e)
{
FrmHelp help = new FrmHelp();
help.ShowDialog();
}
private void btnSendMail_Click_1(object sender, EventArgs e)
{
if (btnSendMail.Text == "发送")
{
BeginSendMail(); //开始发送邮件
}
else
{
//提示用户是否要中断 中断邮件的发送
if (MessageBox.Show("是否要中断邮件发送", "是否要中断邮件发送", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
{
if (thread != null)
{
try
{
thread.Abort(); //停止发送邮件
}
catch (Exception ex)
{
MessageBox.Show("意外中断 " ex.Message);
}
}
btnSendMail.Text = "发送";
}
}
}
private void 拆分成单文件ToolStripMenuItem_Click(object sender, EventArgs e)
{
FrmSplictSintgeFile splictFile = new FrmSplictSintgeFile();
splictFile.ShowDialog();
}
private void tsSendMailCell_Click(object sender, EventArgs e)
{
if (dgvShow.SelectedCells.Count > 0)
{
if (emailReveiveBeforIndex >= 0)
{
dgvShow.Columns[emailReveiveBeforIndex].DefaultCellStyle.BackColor = Color.White; //取消上次设置的颜色
}
int columnIndex = dgvShow.SelectedCells[0].ColumnIndex;
if (dgvShow.SelectedCells[0]!=null)
{
// colum.ReceiveEmail = dgvShow.SelectedCells[0].Value.ToString();
receiveMailAddressColumn = dgvShow.Columns[dgvShow.SelectedCells[0].ColumnIndex].Name; //得到附件列名
GlobalConfig colum = new GlobalConfig().GetReveviceUser(); //读取配置文件并保存
string columnName = receiveMailAddressColumn;
colum.ReceiveEmail = columnName;
colum.Save(colum);
}
dgvShow.Columns[columnIndex].DefaultCellStyle.BackColor = ColorHelper.emailColor;
emailReveiveBeforIndex = columnIndex; //记录当前设置的行index
}
else
{
MessageBox.Show("请先点击要选择的列!");
}
}
private void tsFujianCell_Click(object sender, EventArgs e)
{
if (dgvShow.SelectedCells.Count > 0)
{
if (emailAppendixIndex >= 0)
{
dgvShow.Columns[emailAppendixIndex].DefaultCellStyle.BackColor = Color.White; //取消上次设置的颜色
}
int columnIndex = dgvShow.SelectedCells[0].ColumnIndex;
if (dgvShow.SelectedCells[0] != null)
{
receiveAppendixColumn = dgvShow.Columns[dgvShow.SelectedCells[0].ColumnIndex].Name; //得到附件列名
GlobalConfig colum = new GlobalConfig().GetReveviceUser(); //读取配置文件并保存
string columnName = receiveAppendixColumn;
colum.ReceiveAppendixColumn = columnName;
colum.Save(colum);
}
dgvShow.Columns[columnIndex].DefaultCellStyle.BackColor = ColorHelper.fujianColor;
emailAppendixIndex = columnIndex;
}
else
{
MessageBox.Show("请先点击要选择的列!");
}
}
private void btnSplictFile_Click(object sender, EventArgs e)
{
if( inportFile!="")
{
if(emailAppendixIndex<0)
{
MessageBox.Show("请单击需设置成附件列中的任意单元格,再右键选择\"设置成附件列\"");
return;
}
if(!File.Exists(Common.ExcelTemplateFile))
{
MessageBox.Show("模板文件不存在,请先定义模板文件后在进行拆分文件");
new EPPlusHelper().CreateNewExcelFile(Common.ExcelTemplateFile); //创建模板文件
System.Diagnostics.Process.Start(Common.ExcelTemplateFile);
return;
}
FrmSplictSintgeFile splictFile = new FrmSplictSintgeFile(inportFile, emailAppendixIndex 1);
splictFile.ShowDialog();
}
else
{
MessageBox.Show("请先导入文件");
}
}
private void chkSimple_Click(object sender, EventArgs e)
{
chkSimple.Checked = true;
chkAll.Checked = false;
SetColumIsVisible(false);//让所有的列隐藏
if (emailReveiveBeforIndex > -1)
{
dgvShow.Columns[emailReveiveBeforIndex].Visible = true;
}
if (emailAppendixIndex > -1)
{
dgvShow.Columns[emailAppendixIndex].Visible = true;
}
if(dgvShow.Columns.Contains(resultColumnName))
{
dgvShow.Columns[resultColumnName].Visible = true;
}
}
private void chkAll_Click(object sender, EventArgs e)
{
chkAll.Checked = true;
chkSimple.Checked = false;
SetColumIsVisible(true); //让所有列显示
}
private void SetColumIsVisible(bool isVisible)
{
foreach (DataGridViewColumn column in dgvShow.Columns)
{
column.Visible = isVisible;
}
}
private void chkSimple_CheckedChanged(object sender, EventArgs e)
{
}
}
class ColorHelper
{
public static Color emailColor= Color.Gray;
public static Color fujianColor = Color.GreenYellow;
}
class SendMailResult
{
public int FaildCount { get; set; }
public int SuccessCount { get; set; }
}
}
评论