TSQL - How To Send Email From SQL Server In HTML Format

We can send email from SQL Server in HTML format by using dbo.sp_send_dbmail stored procedure. To send email in HTML format, we have to build the body of email with HTML Tags. The below code can be used to send basis HTML formatted email. If you want to loop through some results of table and send in HTML formatted email. You can use This script for looping ( TSQL Cursor) and build the body by using below script.

--Get the Profile Name that you want to use 
--select * from msdb..sysmail_profile
DECLARE @Recipients VARCHAR(200)
SET @Recipients='aamirwarraich2001@gmail.com'
DECLARE @Subject VARCHAR(100)
SET @Subject='Test Email Subject'
DECLARE @Body NVARCHAR(2000)
DECLARE @ProfileName VARCHAR(100)
SET @ProfileName='EmailProfileName'
SET @Body=N'
<html>
 <head>
  <meta http-equiv=Content-Type content="text/html; charset=windows-1252">
  <style>p{font-size:10.0pt;font-family:Calibri,"Arial","serif";}</style>
 </head>
 <body>
 <p>Hello All,</p>
 <p>Sql Age is the blog spot to learn and share Information, Scenarios, Real Time Examples about SQL Server,<br />
  Transact-SQL (TSQL), SQL Server Database Administration (SQL DBA), Business Intelligence (BI),<br />
  SQL Server Integration Services (SSIS), SQL Server Reporting Services (SSRS) and Data Warehouse (DWH) Concepts.</p>
 <p>Thank you,<br />
  Development Team<br />
 <a href="http://sqlage.blogspot.com/"><b>sqlage.blogspot.com</b></a><br />
 </p>
 </body>
</html>'
EXEC msdb.dbo.sp_send_dbmail
  @profile_name =@ProfileName,
  @recipients = @Recipients,
  @subject = @Subject,
  @body = @Body,
  @body_format = 'HTML'


Here is the output of above script. If you want to change the fond size , format type that can be changed in above code as per requirement.
Fig 1: HTML Formatted Email send by SQL Server dbo.Sp_Send_dbMail Stored Procedure

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.