C#发送邮件,可带有Excel附件
记录工作中遇到发邮件带附件的需求,新建控制台应用程序,目录下创建好所需要的定义好的Excel模板!
class Program
{
static string newExcelPath = string.Empty;
static string fileName = string.Empty; static void Main(string[] args)
{
CopyReportTemplate();
ExportDataToExcel();
SendEmail();
} #region 复制 Excel 模板 -- void CopyReportTemplate()
/// <summary>
/// 复制 Excel 模板
///
/// ++++++++++++++++++++++++++++++++++++++++++++
/// liam 2021.03.9
/// 获取应用程序的当前工作目录。
/// System.IO.Directory.GetCurrentDirectory()
/// 获取启动了应用程序的可执行文件的路径。
/// System.Windows.Forms.Application.StartupPath
/// +++++++++++++++++++++++++++++++++++++++++++++
///
/// </summary>
private static void CopyReportTemplate()
{
string excelTemplatePath = System.Windows.Forms.Application.StartupPath + "\\出行申报报表.xlsx";
//Directory.GetCurrentDirectory() + "\\出行报表.xlsx";
string str = DateTime.Now.ToString("yyyyMMdd");
fileName = "出行申报报表-" + str; newExcelPath =System.Windows.Forms.Application.StartupPath + "\\Report\\" + fileName + ".xlsx";
//Directory.GetCurrentDirectory() + "\\Report\\" + fileName + ".xlsx";
File.Delete(newExcelPath);
File.Copy(excelTemplatePath, newExcelPath);
}
#endregion #region 获取报表数据 -- DataSet GetReportData()
/// <summary>
/// 获取报表数据
/// </summary>
/// <returns></returns>
private static DataSet GetReportData()
{
DataSet ds = new DataSet();
string sql0 = "pc_Select_CheckHolidayInformationData_No";
string date = DateTime.Now.ToString("yyyy-MM-dd");
SqlParameter[] sp = {
new SqlParameter("@date",date)
};
DataTable table0 = GetDataTable(CommandType.StoredProcedure, sql0, sp);
table0.TableName = "未申报记录";
string sql1 = "pc_Select_CheckHolidayInformationData_Yes";
DataTable table1 = GetDataTable(CommandType.StoredProcedure, sql1);
table1.TableName = "已申报记录";
ds.Tables.Add(table0);
ds.Tables.Add(table1); return ds;
}
#endregion #region 导出数据至 Excel -- static void ExportDataToExcel()
/// <summary>
/// 导出数据至 Excel
/// </summary>
private static void ExportDataToExcel()
{
XSSFWorkbook workbook = null;
using (FileStream file = new FileStream(newExcelPath, FileMode.Open, FileAccess.Read))
{
workbook = new XSSFWorkbook(file);
file.Close();
}
ICellStyle style = CellStyle(workbook);
ICellStyle styleRed = CellStyle(workbook);
styleRed.FillPattern = FillPattern.SolidForeground;
styleRed.FillForegroundColor = HSSFColor.Coral.Index;
DataSet ds = GetReportData();
for (int i = 0; i < ds.Tables.Count; i++)
{
DataTable table = ds.Tables[i];
ISheet sheet = workbook.GetSheet(table.TableName);
for (int j = 0; j < table.Rows.Count; j++)
{
IRow row = sheet.CreateRow(1 + j);
row.Height = 18 * 20; for (int k = 0; k < table.Columns.Count; k++)
{
string colName = table.Columns[k].ColumnName;
string str = CheckFieldIsNullOrEmpty(table, j, colName);
ICell cell = row.CreateCell(k);
cell.SetCellValue(str);
}
}
}
using (FileStream fs = new FileStream(newExcelPath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
workbook.Write(fs);
fs.Close();
}
}
#endregion #region 创建 Excel 单元格样式 -- ICellStyle CellStyle(XSSFWorkbook workbook)
/// <summary>
/// 创建 Excel 单元格样式
/// </summary>
/// <param name="workbook"></param>
/// <returns></returns>
private static ICellStyle CellStyle(XSSFWorkbook workbook)
{
IFont fontAll = workbook.CreateFont();
fontAll.FontName = "Microsoft YaHei";
fontAll.FontHeight = 10 * 20;
ICellStyle ItemCellStyle = workbook.CreateCellStyle();
ItemCellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
ItemCellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
ItemCellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
ItemCellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
ItemCellStyle.BottomBorderColor = HSSFColor.Grey25Percent.Index;
ItemCellStyle.LeftBorderColor = HSSFColor.Grey25Percent.Index;
ItemCellStyle.RightBorderColor = HSSFColor.Grey25Percent.Index;
ItemCellStyle.TopBorderColor = HSSFColor.Grey25Percent.Index;
ItemCellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;
ItemCellStyle.VerticalAlignment = VerticalAlignment.Center;
ItemCellStyle.SetFont(fontAll);
return ItemCellStyle;
}
#endregion #region 检查 Table CELL 数据 -- string CheckFieldIsNullOrEmpty(DataTable table, string key)
/// <summary>
/// 检查 Table CELL 数据
/// </summary>
/// <param name="table"></param>
/// <param name="key"></param>
/// <returns></returns>
public static string CheckFieldIsNullOrEmpty(DataTable table, string key)
{
string value = string.Empty;
if (table != null && table.Rows.Count > 0)
{
if (!string.IsNullOrEmpty(table.Rows[0][key].ToString()))
{
value = table.Rows[0][key].ToString();
}
}
return value;
} /// <summary>
/// 检查 Table CELL 数据
/// </summary>
/// <param name="table"></param>
/// <param name="rowIndex"></param>
/// <param name="key"></param>
/// <returns></returns>
public static string CheckFieldIsNullOrEmpty(DataTable table, int rowIndex, string key)
{
string value = string.Empty;
if (table != null && table.Rows.Count > 0)
{
if (!string.IsNullOrEmpty(table.Rows[rowIndex][key].ToString()))
{
value = table.Rows[rowIndex][key].ToString();
}
}
return value;
}
#endregion #region 发送邮件 -- static void SendEmail()
/// <summary>
/// 发送邮件
/// </summary>
private static void SendEmail()
{
//string sql = "pc_SendEmail_CheckUserReport";
//SqlParameter[] sp = {
// new SqlParameter("@path",newExcelPath),
// new SqlParameter("@fileName",fileName)
//};
//int i = NonQuery(CommandType.StoredProcedure, sql, sp); //设置邮件的服务器
string host = "IP地址";
//替换成你的hotmail账户
string mailAddress = "发邮件地址";
//目标邮件地址。可添加多个地址,逗号分隔
string[] ToAddress = { "目标邮件地址" };
string[] CcAddress = { "抄送邮件地址" }; SmtpClient smtp = new SmtpClient(host);
smtp.EnableSsl = false; //开启安全连接。
smtp.DeliveryMethod = SmtpDeliveryMethod.Network; //使用网络传送
StringBuilder sb = new StringBuilder();
sb.AppendLine("<span style='font-family:Arial; font-size: 13px; '>Dear All:</span><br/><br/>");
sb.AppendLine("<div style='font-family:Microsoft YaHei UI;font-size: 13px; padding-left:100px; width:300px;'> 出行申报情况,请查阅附件,谢谢。</div>");
sb.AppendLine("<br/><span style='font-family:Arial;font-size: 13px; '> Best regards, CMOA System;</ span ><br/> ");
sb.AppendLine("<span style='font-family:Arial;font-size: 13px;'>This is auto-generated email, please do not reply. Thank you for your attention !<br/></span><br/><br/>");
MailMessage message = new MailMessage(); //创建邮件
message.From = new MailAddress(mailAddress);
message.Subject = fileName;
message.IsBodyHtml = true;
for (int i = 0; i < ToAddress.Length; i++)
{
message.To.Add(ToAddress[i]);
}
for (int i = 0; i < CcAddress.Length; i++)
{
message.CC.Add(CcAddress[i]);
}
message.Body = sb.ToString(); //string newExcelPath = @"D:\MID PDF.zip"; string MIME = MimeMapping.GetMimeMapping(newExcelPath);//文件的MediaType MIME
//message.AlternateViews.Add(new AlternateView(fileAddress,MIME)); //发送附加内容(附加的内容为文件中的内容) //发送附加件
message.Attachments.Add(new Attachment(newExcelPath, MIME));
smtp.Send(message); //发送邮件
}
#endregion #region DataTable -- static DataTable GetDataTable(CommandType cmdType, string cmdText, params SqlParameter[] cmdParams)
/// <summary>
/// DataTable
/// </summary>
/// <param name="cmdType"></param>
/// <param name="cmdText"></param>
/// <param name="cmdParams"></param>
/// <returns></returns>
public static DataTable GetDataTable(CommandType cmdType, string cmdText, params SqlParameter[] cmdParams)
{
DateTime starttime = DateTime.Now; //起始时间
using (SqlConnection Connection = new SqlConnection("Server=IP地址;DataBase=库名;Uid=账号;Pwd=密码"))
{
DataTable dt = new DataTable();
Connection.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdText, Connection);
try
{
da.SelectCommand.CommandTimeout = 300;
da.SelectCommand.CommandType = cmdType; //设置命令类型
da.SelectCommand.Parameters.AddRange(cmdParams);
da.Fill(dt); return dt; }
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
da.Dispose();
Connection.Close();
return null;
}
finally
{
Connection.Close();
Connection.Dispose();
}
}
}
#endregion #region 执行数据的增、删、改方法 -- static int NonQuery(CommandType type, string CommandText, string sysName, params SqlParameter[] pars)
/// <summary>
/// 执行数据的增、删、改方法
/// </summary>
/// <param name="type">要执行的数据库命令类型</param>
/// <param name="CommandText">要执行的SQL语句或存储过程</param>
/// <param name="pars">所需的参数列表</param>
/// <returns>受影响的行数</returns>
public static int NonQuery(CommandType type, string CommandText, params SqlParameter[] pars)
{
DateTime starttime = DateTime.Now; //起始时间
int i = 0;
using (SqlConnection Connection = new SqlConnection("Server=IP地址;DataBase=库名;Uid=账号;Pwd=密码"))
{
Connection.Open();
//实例化数据库命令对象
SqlCommand cmd = new SqlCommand(CommandText, Connection);
try
{
cmd.CommandTimeout = 0;
//设置命令执行类型
cmd.CommandType = type;
//设置SQL语句或存储过程参数
SqlParameter[] sp = new SqlParameter[pars.Length];
sp = pars;
cmd.Parameters.AddRange(sp);
//调用方法得到SqlDataReader对象
i = cmd.ExecuteNonQuery(); return i;
}
catch (Exception err)
{
cmd.Dispose();
Connection.Close();
throw new Exception(err.Message);
}
finally
{
Connection.Close();
Connection.Dispose();
}
}
}
#endregion
}
C#发送邮件,可带有Excel附件的更多相关文章
- Python模块探秘 Smtplib发送带有各种附件的邮件
这两天对Python的邮件模块比较感兴趣,于是就查了查资料.同时在实际的编码过程中也遇到了各种各样的问题.下面我就来分享一下我与smtplib的故事. 前提条件 我的上一篇博文里面讲解了,发送邮件必须 ...
- C# 解决 邮件发送Excel附件后,excel处于锁定状态
当使用c#自带的MailMessage类发送excel附件时,再次打开excel会提示处于锁定状态. 解决思路:Attachment是添加附件的类,邮件发送后没有释放该类 public string ...
- ci框架(codeigniter)Email发送邮件、收件人、附件、Email调试工具
ci框架(codeigniter)Email发送邮件.收件人.附件.Email调试工具 Email 类 CodeIgniter 拥有强大的 Email 类来提供如下的功能: 多 ...
- python3使用smtplib发送邮件,带xlsx附件
一.概述 最近在做一个统计报表,需要发送邮件,并带附件的. 在之前的文章中 https://www.cnblogs.com/xiao987334176/p/10022026.html 已经实现了发送邮 ...
- 个人永久性免费-Excel催化剂功能第24波-批量发送邮件并指点不同附件不同变量
批量发送邮件功能,对高级OFFICE用户来说,第1时间会想到使用WORD的邮件合并功能.但对于需要发送附件来说,邮件合并功能就无能为力,同样还有的限制是用户电脑上没有安装OUTLOOK,同样也不能发送 ...
- 基于PHP自带的mail函数实现发送邮件以及带有附件的邮件功能
PHPmail函数简介 bool mail ( string $to , string $subject , string $message [, string $additional_headers ...
- android--email发送邮件,文本还有附件形式的邮件
1.首先用的jar包为javaemail 下载地址: https://yunpan.cn/cB3kY8WIvcGtU (提取码:e042) 2.工具包 package com.kllayhello.u ...
- Java使用javax.mail.jar发送邮件并同意发送附件
因为Java在开发网页上占有绝大优势.所以作为web端的领军人物,譬如发送短信和发送邮件这些就成了必定,网络安全一再安全我们须要把账号的安全级别提到更高.因此这些对于开发者也就成了必须掌握的技能!我一 ...
- Android简单发送邮件(可带附件)
项目中遇到了一个发送邮件的功能,在网上查了很多,资料也很多.这里就不一一介绍了,只是写出我使用的方案(最简单的) Intent email = new Intent(android.content.I ...
随机推荐
- python 定义函数关键字def 简单介绍
一 在类中定义的def # python中def 是用来干什么的? # 可以定义函数,就是定义一个功能. class People(): def __init__(self): print(&quo ...
- 如何在 IDEA 中添加 Maven 项目的 Archetype(解决添加不起作用的问题)
前言 在 IDEA 中点击新建 Maven 模块,会发现他已经为我们罗列出来了许多的 archetype,但有些时候满足不了我们的需求.下面就来看看如何添加自己的脚手架吧. 实现过程 新建模块 在 I ...
- 计算机网络再次整理————tcp例子[五]
前言 本文介绍一些tcp的例子,然后不断完善一下. 正文 服务端: // See https://aka.ms/new-console-template for more information us ...
- AtCoder ABC213 简要题解
这世道连 \(\rm ABC\) 都要写题解来续命了... A - D 略. E 有如下观察: 对于任意的四个方格,出去之后再回来可以调整为先在内部走到固定位置再走出去. 因此只需要考虑在一开始把内部 ...
- 阿里云服务器sshd-D cpu占用过高
发现阿里云服务器cpu占用到达了100%,原因是被植入了挖矿程序,解决方法如下 1.使用top命令查看进程id 直接kill杀死该进程过一会就会重新启动. 2.查看该进程所在的文件目录 这个文件基本上 ...
- linux 编译C++
转载请注明来源:https://www.cnblogs.com/hookjc/ makefile文件内容: main:main.o fun1.o fun2.o g++ -o main main.o ...
- 服务器硬件及RAID配置实践
服务器硬件及RAID配置实践 1.RAID磁盘阵列介绍 2.创建RAID磁盘阵列 1.RAID:中文简称为独立冗余磁盘阵列 把多块独立的物理硬盘按不同的方式组合起来形成一个硬盘组(逻辑硬盘),从而提供 ...
- 大话PHP设计模式笔记
针对PHP的设计模式进行总结记录. 顺带,我会在后面把我整理的一整套CSS3,PHP,MYSQL的开发的笔记打包放到百度云,有需要可以直接去百度云下载,这样以后你们开发就可以直接翻笔记不用百度搜那么麻 ...
- Solution -「CF 1586F」Defender of Childhood Dreams
\(\mathcal{Description}\) Link. 定义有向图 \(G=(V,E)\),\(|V|=n\),\(\lang u,v\rang \in E \Leftrightarr ...
- Visual Studio Code 配置C、C++ 文件debug调试环境
目录 vscode C/C++ Extension Pack 插件安装 vscode windows 端 debug 配置 window MinGW 环境安装 windows 端 C.CPP 单文件 ...