Msdb.dbo.sp_send_dbmail

A popular SQL Server stored procedure!

msdb.dbo.sp_send_dbmail is a stored procedure in SQL Server that allows you to send an email message from a SQL Server database. It's a part of the SQL Server Database Mail feature, which enables you to send emails from your database using a variety of protocols, such as SMTP, POP3, and more.

Here's a brief overview of the stored procedure:

Syntax:

sp_send_dbmail 
    @profile_name = 'profile_name', 
    @recipients = 'recipient_email_address', 
    @subject = 'subject_line', 
    @body = 'email_body', 
    @body_format = 'html' | 'text', 
    @importance = 'high' | 'normal' | 'low', 
    @sp_nosql = 0 | 1

Parameters:

  1. @profile_name: The name of the Database Mail profile to use for sending the email.
  2. @recipients: The email address of the recipient(s) to send the email to.
  3. @subject: The subject line of the email.
  4. @body: The body of the email.
  5. @body_format: The format of the email body (HTML or text).
  6. @importance: The importance level of the email (high, normal, or low).
  7. @sp_nosql: A flag to indicate whether to send the email as a SQL Server job (0) or as a standalone email (1).

How it works:

  1. You create a Database Mail profile in SQL Server Management Studio (SSMS) or using the sp_configure stored procedure.
  2. You execute the sp_send_dbmail stored procedure, passing in the required parameters.
  3. The stored procedure uses the specified Database Mail profile to send the email to the recipient(s).

Common use cases:

  1. Sending notifications to users or administrators about database events, such as errors, warnings, or completed jobs.
  2. Sending reports or data extracts to users or stakeholders.
  3. Sending automated emails as part of a SQL Server job or scheduled task.

Tips and considerations:

  1. Make sure you have a Database Mail profile set up and configured correctly.
  2. Be mindful of email size limits and formatting requirements.
  3. Use parameterized queries to avoid SQL injection attacks.
  4. Consider using a separate email account or profile for your Database Mail configuration.