Thursday, 23 April 2015

SQL Server - How To Send Email From 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='John2015@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>Body Here</p>
 <p>Thank you,
  Development Team<br />
 </p>
 </body>
</html>'
 
 EXEC msdb.dbo.sp_send_dbmail
  @profile_name =@ProfileName,
  @recipients = @Recipients,
  @subject = @Subject,
  @body = @Body,
  @body_format = 'HTML'


If you want to change the fond size, format type that can be changed in above code as per requirement.

No comments:

Post a Comment