using System;
using System.IO;
using System.Net;
using System.Net.Mail;
using OfficeOpenXml;
namespace EmailWithExcelAttachment
{
class Program
{
static void Main(string[] args)
{
// Excel文件路径
string excelFilePath = @"C:\Path\To\Your\Excel\File.xlsx";
// 邮件信息
string fromAddress = "your_email@example.com";
string toAddress = "recipient@example.com";
string subject = "Excel Data Preview with Attachment";
string smtpServer = "smtp.example.com";
int smtpPort = 587; // 或者其他适用的SMTP端口
bool enableSsl = true;
string username = "your_username";
string password = "your_password";
try
{
// 创建邮件消息
MailMessage mail = new MailMessage();
mail.From = new MailAddress(fromAddress);
mail.To.Add(toAddress);
mail.Subject = subject;
// 读取Excel文件并转换为HTML插入邮件正文
string excelHtmlContent = GetExcelDataAsHtml(excelFilePath);
mail.Body = excelHtmlContent;
mail.IsBodyHtml = true;
// 添加Excel文件作为附件
Attachment attachment = new Attachment(excelFilePath);
mail.Attachments.Add(attachment);
// 设置SMTP客户端
SmtpClient smtp = new SmtpClient(smtpServer);
smtp.Port = smtpPort;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(username, password);
smtp.EnableSsl = enableSsl;
// 发送邮件
smtp.Send(mail);
Console.WriteLine("邮件已成功发送!");
}
catch (Exception ex)
{
Console.WriteLine("发送邮件时发生错误: " + ex.Message);
}
}
// 将Excel文件内容转换为HTML字符串
private static string GetExcelDataAsHtml(string filePath)
{
// 使用EPPlus读取Excel
using (var package = new ExcelPackage(new FileInfo(filePath)))
{
var worksheet = package.Workbook.Worksheets[0]; // 假设我们只处理第一个工作表
var tableHtml = "<table border='1'>"; // 开始构建HTML表格
// 添加行头
foreach (var firstRowCell in worksheet.Cells[1, 1, 1, worksheet.Dimension.End.Column])
{
tableHtml += $"<th>{firstRowCell.Text}</th>";
}
tableHtml += "</tr>"; // 结束行头行
// 添加数据行
for (int rowNum = 2; rowNum <= worksheet.Dimension.End.Row; rowNum++)
{
tableHtml += "<tr>";
for (int colNum = 1; colNum <= worksheet.Dimension.End.Column; colNum++)
{
var cell = worksheet.Cells[rowNum, colNum];
tableHtml += $"<td>{cell.Text}</td>";
}
tableHtml += "</tr>";
}
tableHtml += "</table>"; // 结束表格
return tableHtml;
}
}
}
}