SQL Server’s Database Mail has a stored procedure called sp_send_dbmail
that you can use to send emails from SQL Server.
By default, emails are sent as text, but you can easily change this, so that they’re sent in HTML format.
The @body_format
argument is what you use to switch over to HTML format.
Example
Here’s an example of sending an HTML email.
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'DB Admin Profile',
@recipients = '[email protected]',
@body = 'Potential candidates for an <strong>Admin</strong> job, perhaps?',
@body_format = 'HTML',
@subject = 'As discussed';
The part that goes @body_format = 'HTML'
is what sends the email in HTML format.
In this example, I’ve applied a trivial amount of HTML. I’ve simply enclosed the word Admin
in <strong>
tags. I’ve kept it as simple as possible so that it’s easy to read the example.
Save the HTML to a Variable
In the previous example, I applied the HTML code directly to the @body
argument. This wasn’t much of a problem, given the shortness of the body content. But it’s nice to separate the HTML code from the sp_send_dbmail
procedure.
To do this, we can save the HTML code to a variable, then use that variable as the value for the @body
argument.
Like this:
DECLARE @body_content varchar(255);
SET @body_content = 'Potential candidates for an <strong>Admin</strong> job, perhaps?';
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'DB Admin Profile',
@recipients = '[email protected]',
@body = @body_content,
@body_format = 'HTML',
@subject = 'As discussed';
For a full list of HTML elements, see HTML Tags over at Quackit.