SQL Server中发送HTML格式邮件的方法
SqlSever 配置邮箱的方法就不说了,自行百度搜索。发送邮件可以非常方便帮助运维人员做统计或者发送给客户定制的订单等。
以下列举使用sqlserver 发送邮件的3个示例:
A. 发送电子邮件
此示例使用电子邮件地址 danw@Adventure-Works.com 向 Dan Wilson 发送电子邮件。该邮件的主题为 Automated Success Message。邮件正文包含一句话 'The stored procedure finished successfully'。
EXEC msdb.dbo.sp_send_dbmail @profile_name = 'AdventureWorks Administrator', @recipients = 'danw@Adventure-Works.com', @body = 'The stored procedure finished successfully.', @subject = 'Automated Success Message' ;
B. 发送包含查询结果的电子邮件
此示例使用电子邮件地址 danw@Adventure-Works.com 向 Dan Wilson 发送电子邮件。该邮件的主题为 Work Order Count。数据库邮件将该结果附加为文本文件。
EXEC msdb.dbo.sp_send_dbmail @profile_name = 'AdventureWorks Administrator', @recipients = 'danw@Adventure-Works.com', @query = 'SELECT COUNT(*) FROM AdventureWorks.Production.WorkOrder WHERE DueDate > ''2004-04-30'' AND DATEDIFF(dd, ''2004-04-30'', DueDate) < 2' , @subject = 'Work Order Count', @attach_query_result_as_file = 1 ;
C. 发送 HTML 电子邮件
此示例使用电子邮件地址 danw@Adventure-Works.com 向 Dan Wilson 发送电子邮件。邮件的主题为 Work Order List,并包含一个 HTML 文档,数据库邮件使用 HTML 格式发送该邮件。
DECLARE @tableHTML NVARCHAR(MAX) ;
SET @tableHTML =
N'<H1>Work Order Report</H1>' +
N'<table border="1">' +
N'<tr><th>Work Order ID</th><th>Product ID</th>' +
N'<th>Name</th><th>Order Qty</th><th>Due Date</th>' +
N'<th>Expected Revenue</th></tr>' +
CAST ( ( SELECT td = wo.WorkOrderID, '',
td = p.ProductID, '',
td = p.Name, '',
td = wo.OrderQty, '',
td = wo.DueDate, '',
td = (p.ListPrice - p.StandardCost) * wo.OrderQty
FROM AdventureWorks.Production.WorkOrder as wo
JOIN AdventureWorks.Production.Product AS p
ON wo.ProductID = p.ProductID
WHERE DueDate > '2004-04-30'
AND DATEDIFF(dd, '2004-04-30', DueDate) < 2
ORDER BY DueDate ASC,
(p.ListPrice - p.StandardCost) * wo.OrderQty DESC
SET @tableHTML =
N'<H1>Work Order Report</H1>' +
N'<table border="1">' +
N'<tr><th>Work Order ID</th><th>Product ID</th>' +
N'<th>Name</th><th>Order Qty</th><th>Due Date</th>' +
N'<th>Expected Revenue</th></tr>' +
CAST ( ( SELECT td = wo.WorkOrderID, '',
td = p.ProductID, '',
td = p.Name, '',
td = wo.OrderQty, '',
td = wo.DueDate, '',
td = (p.ListPrice - p.StandardCost) * wo.OrderQty
FROM AdventureWorks.Production.WorkOrder as wo
JOIN AdventureWorks.Production.Product AS p
ON wo.ProductID = p.ProductID
WHERE DueDate > '2004-04-30'
AND DATEDIFF(dd, '2004-04-30', DueDate) < 2
ORDER BY DueDate ASC,
(p.ListPrice - p.StandardCost) * wo.OrderQty DESC
FOR XML PATH('tr'), TYPE) AS NVARCHAR(MAX) ) +N'</table>' ;
EXEC msdb.dbo.sp_send_dbmail @recipients='danw@Adventure-Works.com',
@subject = 'Work Order List',
@body = @tableHTML,
@body_format = 'HTML' ;
@subject = 'Work Order List',
@body = @tableHTML,
@body_format = 'HTML' ;
以上示例均测试可行。