首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 數據庫知識 >  >> SQL Server 資料庫 >> 關於SqlServer

SSRS 入門(八):報表訂閱進階——自動化郵件發送方案

     編輯:關於SqlServer

上一篇介紹了透過共享資料夾訂閱報表。本篇針對 SSRS 原生郵件訂閱的限制(需自建 SMTP、不支援第三方 SMTP),提供一套「變通方案」:利用 SQL Server Agent 排程觸發,結合 WinForm 應用產生 PDF,再由獨立發送程式依設定檔群發郵件。

整體架構三步走

  1. 排程觸發:SQL Server Agent Job 固定週期(如每日晨間 6:00)啟動流程。
  2. 報表產生:WinForm 應用載入 ReportViewer,以隱藏模式將指定報表渲染為 PDF,存放至預設目錄(如 D:\ReportOutput\)。
  3. 郵件發送:另一支程式讀取資料庫設定(SMTP、收件人群組),將 PDF 附件寄出。

核心元件開發

1. 建立 WinForm 產生 PDF 應用

  • Visual Studio 2012 建立 Windows Forms 專案。
  • 工具箱加入 Microsoft.Reporting.WinForms.ReportViewer 控件。
  • 設定 ProcessingMode = Remote,指定 ReportServerUrl 與 ReportPath。
  • 程式碼範例:
var viewer = new ReportViewer();
viewer.ProcessingMode = ProcessingMode.Remote;
viewer.ServerReport.ReportServerUrl = new Uri("https://ssrs-server/ReportServer");
viewer.ServerReport.ReportPath = "/Reports/MonthlySales";
viewer.ServerReport.SetParameters(new[] { new ReportParameter("Month", DateTime.Now.AddMonths(-1).ToString("yyyy-MM")) });
byte[] pdfBytes = viewer.ServerReport.Render("PDF");
File.WriteAllText($@"D:\ReportOutput\MonthlySales_{DateTime.Now:yyyyMM}.pdf", pdfBytes);

2. 資料庫設定表設計

三張核心表:

表名用途關鍵欄位
ReportBase報表定位ReportServer, ReportPath
EmailBaseSMTP 設定SmtpHost, SmtpPort, Account, Password, EnableSsl
ReportTo收件人對應ReportID, EmailGroup, ToAddresses (分號分隔)
資料庫表結構圖

3. 導入 LINQ to SQL / Entity Framework

專案右鍵 → Add → New Item → LINQ to SQL Classes (或 ADO.NET Entity Data Model),拖入上述三表,自動產生實體類別,方便後續程式存取。

LINQ to SQL 設計介面

部署與排程

  • 將 WinForm 應用編譯為 GenReport.exe,放置伺服器固定路徑。
  • SQL Server Agent 建立 Job,步驟 1:cmd /c "D:\Tools\GenReport.exe";步驟 2:cmd /c "D:\Tools\SendMail.exe"。
  • 設定排程:每日、每週、每月均可,依業務需求調整。

優勢與擴充建議

  • 不依賴 SSRS 原生郵件功能,可使用任何 SMTP(含 Gmail、SendGrid、內部 Exchange)。
  • PDF 產生與郵件發送解耦,易於擴充:加入壓縮、加密、多附件、HTML 郵件本文等。
  • 建議加入執行日誌表,記錄每次 Job 開始/結束時間、成功筆數、錯誤訊息,便於監控。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved