使用c#的System.Net.Mail包、NPOI包实现了基于excel表格的邮箱自定义批量发送

in 桌面应用自动化运维 with 0 comment

C# System.Net.Mail命名空间

官网API地址为:https://docs.microsoft.com/zh-cn/dotnet/api/system.net.mail?redirectedfrom=MSDN&view=netframework-4.8

通过该命名空间,可实现基于POP协议的邮箱自动发送功能,具体的C# DLL后面提供。

        //mailContent是发送邮件的内容,mailSubject是发送邮件的标题,mailTo发送给哪个邮箱
        public static int SendEmail(string mailContent, string mailSubject, string mailTo)
        {
            // 设置例网易的smtp
            string smtpServer = "smtp.qq.com";// "14.18.245.164"; //SMTP服务器
            string mailFrom = "XXXX@qq.com"; //登陆用户名
            string userPassword = "XXXXXXXXX";//登陆密码

            // 邮件服务设置
            SmtpClient smtpClient = new SmtpClient();
            smtpClient.EnableSsl = true;
            smtpClient.UseDefaultCredentials = false;
            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;//指定电子邮件发送方式
            smtpClient.Host = smtpServer; //指定SMTP服务器
            smtpClient.Timeout = 5000;
            smtpClient.Port = 587; //不设置默认为25端口
            smtpClient.Credentials = new System.Net.NetworkCredential(mailFrom, userPassword);//用户名和密码
           
            MailMessage mailMessage = new MailMessage(mailFrom, mailTo); // 发送人和收件人
            mailMessage.Subject = mailSubject;//主题
            mailMessage.Body = mailContent;//内容
            mailMessage.BodyEncoding = Encoding.UTF8;//正文编码
            mailMessage.IsBodyHtml = true;//设置为HTML格式
            mailMessage.Priority = MailPriority.Low;//优先级

            try
            {
                ServicePointManager.ServerCertificateValidationCallback =
                           delegate (Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; };
                smtpClient.Send(mailMessage); // 发送邮件
                return 1;
            }
            catch (SmtpException ex)
            {
                Logger.Create("- 邮件发送异常", ex.ToString());
                return 0;
            }
        }

NPOI

        private int read_excel()
        {
            //文件的绝对路径
            string excelpath = textBox_path.Text;
            IWorkbook wk = null;
            if (File.Exists(excelpath))
            {
                //获取文件后缀,根据后缀.xls或者.xlsx选择不同的IWorkbook
                string extension = System.IO.Path.GetExtension(excelpath);
                FileStream fs = File.OpenRead(excelpath);
                if (extension.Equals(".xls"))
                {
                    //读取xls文件中的数据
                    wk = new HSSFWorkbook(fs);
                }
                else
                {
                    //读取xls文件中的数据
                    wk = new XSSFWorkbook(fs);
                }

                fs.Close();

                ISheet sheet = wk.GetSheetAt(0);
                string sheetname = wk.GetSheetName(0); //根据序号获取sheet的名称
                int rowcount = sheet.LastRowNum;  //获取该sheet的总行数

                for (int j = 2; j <= rowcount; j++)
                {
                    IRow row = sheet.GetRow(j);  //读取当前行数据
                     MessageBox.Show(row.GetCell(2)); //获取该行的第三列的数据
                }
                return count;
            }
            else
            {
                return 0;
            }
        }
        public static void WriteExcel(string path)
        {
            string cell_val1 = "cell_val1";
            string cell_val2 = "cell_val2";

            if (File.Exists(path))
            {
                IWorkbook wk = null;
                string extension = System.IO.Path.GetExtension(path);

                FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

                if (extension.Equals(".xls"))
                {
                    //把xls文件中的数据写入wk中
                    wk = new HSSFWorkbook(fs);
                }
                else
                {
                    //把xlsx文件中的数据写入wk中
                    wk = new XSSFWorkbook(fs);
                }
                fs.Close();
                //读取当前表数据
                ISheet sheet = wk.GetSheetAt(0);

                IRow row = sheet.GetRow(1);
                row.Height = 20 * 20;

                ICell c1 = row.CreateCell(1);
                ICell c2 = row.CreateCell(3);
                c1.SetCellValue(cell_val1);
                c2.SetCellValue(cell_val2);

                fs.Close();
                using (FileStream fss = File.Open(@"E:\test.xlsx", FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    wk.Write(fss);
                    fss.Close();
                }
            }
        }
//新建Excel文件   
IWorkbook workbook = new HSSFWorkbook();

//新建Sheet表
ISheet sheet = workbook.CreateSheet("Test Result");

//创建单元格样式和字体样式
IFont font = workbook.CreateFont();
ICellStyle style = workbook.CreateCellStyle(); 
   
//设置居中       
style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CenterSelection;

//设置内容垂直居中
style.VerticalAlignment = VerticalAlignment.Justify;

//字体加粗     
font.Boldweight = short.MaxValue;

//设置字体大小
font.FontHeightInPoints = 12;

style.SetFont(font);
IFont font1 = workbook.CreateFont(); 
ICellStyle style1 = workbook.CreateCellStyle();
style1.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CenterSelection; 
style1.VerticalAlignment = VerticalAlignment.Justify;

//修改列宽
sheet.SetColumnWidth(1, 18 * 400);
sheet.SetColumnWidth(2, 18 * 256);     
string[] value1 = { "NO", "UUT SN", "Condition"};
//新建行
IRow row = sheet.CreateRow(0);
        
for (int a = 0; a < value1.Length; a++)
{
  //将数组中的值逐一添加到单元格中
  row.CreateCell(a).SetCellValue(Convert.ToString(value1[a]));

 //给每个单元格写入样式

  row.GetCell(a).CellStyle = style;
 }
for (int i = 0; i < 32; i++)
{
  //追加行
   IRow row1 = sheet.CreateRow((sheet.LastRowNum + 1));
   row1.CreateCell(0).SetCellValue(i + 1);
   row1.CreateCell(1).SetCellValue("5473567I008D9193541A1000041");
   row1.CreateCell(2).SetCellValue("Temperature ");
   row1.GetCell(0).CellStyle = style1;
   row1.GetCell(1).CellStyle = style1;
   row1.GetCell(2).CellStyle = style1;
   font1.Boldweight = short.MaxValue;
   style1.SetFont(font1);

  //新建path ,文件处理模式为新增:FileMode.Create,
   FileStream fs = new FileStream(@"C:\Users\lenovo\Desktop\Test Result.xls", FileMode.Create, FileAccess.Write);
  //写入
   workbook.Write(fs);
 //关闭
   fs.Close();
 }
        /// <summary>
        /// 设置单元格数据类型
        /// </summary>
        /// <param name="cell">目标单元格</param>
        /// <param name="obj">数据值</param>
        /// <returns></returns>
        public static void SetCellValue(ICell cell, object obj)
        {
            if (obj.GetType() == typeof(int))
            {
                cell.SetCellValue((int)obj);
            }
            else if (obj.GetType() == typeof(double))
            {
                cell.SetCellValue((double)obj);
            }
            else if (obj.GetType() == typeof(IRichTextString))
            {
                cell.SetCellValue((IRichTextString)obj);
            }
            else if (obj.GetType() == typeof(string))
            {
                cell.SetCellValue(obj.ToString());
            }
            else if (obj.GetType() == typeof(DateTime))
            {
                cell.SetCellValue((DateTime)obj);
            }
            else if (obj.GetType() == typeof(bool))
            {
                cell.SetCellValue((bool)obj);
            }
            else
            {
                cell.SetCellValue(obj.ToString());
            }
        }

XietongAuto应用

代码仓库地址为:https://github.com/luozhengszj/XietongAuto
使用该应用,可以自动批量发送自定义的邮件(适用与任何的POP协议邮箱),主要具备特点:

Responses