DBMAIL
Send simple email
Section titled “Send simple email”This code sends a simple text-only email to recipient@someaddress.com
EXEC msdb.dbo.sp_send_dbmail @profile_name = 'The Profile Name', @recipients = 'recipient@someaddress.com', @body = 'This is a simple email sent from SQL Server.', @subject = 'Simple email'Send results of a query
Section titled “Send results of a query”This attaches the results of the query SELECT * FROM Users and sends it to recipient@someaddress.com
EXEC msdb.dbo.sp_send_dbmail @profile_name = 'The Profile Name', @recipients = 'recipient@someaddress.com', @query = 'SELECT * FROM Users', @subject = 'List of users', @attach_query_result_as_file = 1;Send HTML email
Section titled “Send HTML email”HTML content must be passed to sp_send_dbmail
DECLARE @html VARCHAR(MAX);SET @html = CONCAT( '<html><body>', '<h1>Some Header Text</h1>', '<p>Some paragraph text</p>', '</body></html>')DECLARE @html VARCHAR(MAX);SET @html = '<html><body>' + '<h1>Some Header Text</h1>' + '<p>Some paragraph text</p>' + '</body></html>';Then use the @html variable with the @body argument. The HTML string can also be passed directly to @body, although it may make the code harder to read.
EXEC msdb.dbo.sp_send_dbmail @recipients='recipient@someaddress.com', @subject = 'Some HTML content', @body = @html, @body_format = 'HTML';