天天看点

c# asp.net sql查询结果集以excel形式发送邮件

/// <summary>
    /// DataTable发送邮件,以excel形式表现
    ///using System.Net.Mail;using ClosedXML.Excel;这两个要引用
    /// </summary>
    /// <param name="dt">DataTable数据</param>
    /// <param name="TableName">excel名称,表名</param>
    /// <param name="MailAddress_To">收件人邮件地址,以逗号隔开</param>
    /// <param name="subject">邮件标题</param>
    /// <param name="body">邮件正文</param>
    public static void DataTable_to_Email(DataTable dt,string tableName,string MailAddress_To,string subject,string body)
    {
        try
        {
            dt.TableName = tableName;
            using (XLWorkbook wb = new XLWorkbook())
            {
                //Add the DataTable as Excel Worksheet.
                wb.Worksheets.Add(dt);

                using (MemoryStream memoryStream = new MemoryStream())
                {
                    //Save the Excel Workbook to MemoryStream.
                    wb.SaveAs(memoryStream);

                    //Convert MemoryStream to Byte array.
                    byte[] bytes = memoryStream.ToArray();
                    memoryStream.Close();

                    //Send Email with Excel attachment.
                    using (MailMessage mm = new MailMessage("你的发件人的邮件地址", MailAddress_To))
                    {
                        mm.Subject = subject;
                        mm.Body = body;
                        //Add Byte array as Attachment.
                        mm.Attachments.Add(new Attachment(new MemoryStream(bytes), tableName+ ".xlsx"));
                        mm.IsBodyHtml = true;
                        SmtpClient smtp = new SmtpClient();
                        smtp.Host = "你的邮件服务器的地址";
                        smtp.EnableSsl = true;
                        System.Net.NetworkCredential credentials = new System.Net.NetworkCredential();
                        credentials.UserName = "发件人邮件的用户名";
                        credentials.Password = "发件人邮件的密码";
                        smtp.UseDefaultCredentials = true;
                        smtp.Credentials = credentials;
                        smtp.Port = 邮件服务器的端口号;
                        smtp.Send(mm);
                    }
                }
            }

        }
        catch(Exception ex)
        {
            System.Web.HttpContext.Current.Response.Write("<script>alert('"+ex.ToString()+"')</script>");

        }
    }