using System;
using System.Data.SqlClient;
using System.Text;
using System.Net;
using System.Net.Mail;
class Program
{
static void Main(string[] args)
{
try
{
// 数据库连接字符串·
string connectionString = "Data Source=LAPTOP-6O51C85I;Initial Catalog=zktime;integrated security=True;";
// SQL 查询语句
string query = "SELECT LocationLabel ,GoodsName,PresentNumber,SafeNumber,PresentNumber - SafeNumber as z FROM Sheet1$";
// 构建HTML表格
string htmlTable = GetHtmlTableFromQuery(connectionString, query);
// 发送邮件
SendEmail(htmlTable);
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
static string GetHtmlTableFromQuery(string connectionString, string query)
{
StringBuilder htmlTable = new StringBuilder("<table>");
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(query, connection))
{
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
// 表头
htmlTable.Append("<tr><th>位置</th><th>姓名</th><th>现存</th><th>安全</th><th>差异</th></tr>");
// 数据行
while (reader.Read())
{
htmlTable.Append("<tr>");
htmlTable.Append("<td>").Append(reader["LocationLabel"]).Append("</td>");
htmlTable.Append("<td>").Append(reader["GoodsName"]).Append("</td>");
htmlTable.Append("<td>").Append(reader["PresentNumber"]).Append("</td>");
htmlTable.Append("<td>").Append(reader["SafeNumber"]).Append("</td>");
htmlTable.Append("<td>").Append(reader["z"]).Append("</td>");
htmlTable.Append("</tr>");
}
}
htmlTable.Append("</table>");
}
}
return htmlTable.ToString();
}
static void SendEmail(string htmlTable)
{
string excelFilePath = @"D:\send_email_excel_files\SET安全值检查2024-04-30.xls";
// 邮件设置
string fromAddress = "2252450311@qq.com";
string toAddress = "2502960498@qq.com";
string subject = "查询结果";
string smtpServer = "smtp.qq.com";
int smtpPort = 587; // 根据你的SMTP服务器设置
string smtpUsername = "2252450311@qq.com";
string smtpPassword = "fdarlfkfqiyhebjh";
Attachment attachment = new Attachment(excelFilePath);
// 创建邮件对象
MailMessage mail = new MailMessage(fromAddress, toAddress, subject, htmlTable);
mail.IsBodyHtml = true;
// 创建SMTP客户端
SmtpClient smtp = new SmtpClient(smtpServer, smtpPort);
smtp.EnableSsl = true; // 如果需要SSL
NetworkCredential credentials = new NetworkCredential(smtpUsername, smtpPassword);
smtp.Credentials = credentials;
// 发送邮件
smtp.Send(mail);
mail.Attachments.Add(attachment);
Console.WriteLine("邮件已发送成功!");
}
}