[sql] How to send email from SQL Server?

How can I send an email using T-SQL but email address is stored in a table? I want to loop through the table and be able to send email. I cannot find a good example of doing this so far.

This question is related to sql sql-server tsql sp-send-dbmail

The answer is


To send mail through SQL Server we need to set up DB mail profile we can either use T-SQl or SQL Database mail option in sql server to create profile. After below code is used to send mail through query or stored procedure.

Use below link to create DB mail profile

http://www.freshcodehub.com/Article/42/configure-database-mail-in-sql-server-database

http://www.freshcodehub.com/Article/43/create-a-database-mail-configuration-using-t-sql-script

_x000D_
_x000D_
--Sending Test Mail_x000D_
EXEC msdb.dbo.sp_send_dbmail_x000D_
@profile_name = 'TestProfile', _x000D_
@recipients = 'To Email Here', _x000D_
@copy_recipients ='CC Email Here',             --For CC Email if exists_x000D_
@blind_copy_recipients= 'BCC Email Here',      --For BCC Email if exists_x000D_
@subject = 'Mail Subject Here', _x000D_
@body = 'Mail Body Here',_x000D_
@body_format='HTML',_x000D_
@importance ='HIGH',_x000D_
@file_attachments='C:\Test.pdf';               --For Attachments if exists
_x000D_
_x000D_
_x000D_


Here's an example of how you might concatenate email addresses from a table into a single @recipients parameter:

CREATE TABLE #emailAddresses (email VARCHAR(25))

INSERT #emailAddresses (email) VALUES ('[email protected]')
INSERT #emailAddresses (email) VALUES ('[email protected]')
INSERT #emailAddresses (email) VALUES ('[email protected]')

DECLARE @recipients VARCHAR(MAX)
SELECT @recipients = COALESCE(@recipients + ';', '') + email 
FROM #emailAddresses

SELECT @recipients

DROP TABLE #emailAddresses

The resulting @recipients will be:

[email protected];[email protected];[email protected]


In-order to make SQL server send email notification you need to create mail profile from Management, database mail.

1) User Right click to get the mail profile menu and choose configure database mail

2)choose the first open (set up a database mail by following the following tasks) and press next Note: if the SMTP is not configured please refer the the URL below

http://www.symantec.com/business/support/index?page=content&id=TECH86263

3) in the second screen fill the the profile name and add SMTP account, then press next

4) choose the type of mail account ( public or private ) then press next

5) change the parameters that related to the sending mail options, and press next 6) press finish

Now to make SQL server send an email if action X happened you can do that via trigger or job ( This is the common ways not the only ones).

1) you can create Job from SQL server agent, then right click on operators and check mails (fill the your email for example) and press OK after that right click Jobs and choose new job and fill the required info as well as the from steps, name, ...etc and from notification tab select the profile you made.

2) from triggers please refer to the example below.

AS
declare @results varchar(max)
declare @subjectText varchar(max)
declare @databaseName VARCHAR(255)
SET @subjectText = 'your subject'
SET @results = 'your results'
-- write the Trigger JOB
EXEC msdb.dbo.sp_send_dbmail
 @profile_name = 'SQLAlerts',
 @recipients = '[email protected]',
 @body = @results,
 @subject = @subjectText,
 @exclude_query_output = 1 --Suppress 'Mail Queued' message
GO

You can do it with a cursor also. Assuming that you have created an Account and a Profile e.g. "profile" and an Account and you have the table that holds the emails ready e.g. "EmailMessageTable" you can do the following:

USE database_name
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE mass_email AS
declare @email nvarchar (50) 
declare @body nvarchar (255)  

declare test_cur cursor for             
SELECT email from [dbo].[EmailMessageTable]

open test_cur                                        

fetch next from test_cur into   
@email     
while @@fetch_status = 0       
begin                                    

set @body = (SELECT body from [dbo].[EmailMessageTable] where email = @email)
EXEC msdb.dbo.sp_send_dbmail
    @profile_name = 'profile',
    @recipients = @email,
    @body = @body,
    @subject = 'Credentials for Web';
fetch next from test_cur into  
@email 
end    
close test_cur   
deallocate test_cur

After that all you have to do is execute the Stored Procedure

EXECUTE mass_email
GO

You can send email natively from within SQL Server using Database Mail. This is a great tool for notifying sysadmins about errors or other database events. You could also use it to send a report or an email message to an end user. The basic syntax for this is:

EXEC msdb.dbo.sp_send_dbmail  
@recipients='[email protected]',
@subject='Testing Email from SQL Server',
@body='<p>It Worked!</p><p>Email sent successfully</p>',
@body_format='HTML',
@from_address='Sender Name <[email protected]>',
@reply_to='[email protected]'

Before use, Database Mail must be enabled using the Database Mail Configuration Wizard, or sp_configure. A database or Exchange admin might need to help you configure this. See http://msdn.microsoft.com/en-us/library/ms190307.aspx and http://www.codeproject.com/Articles/485124/Configuring-Database-Mail-in-SQL-Server for more information.


sometimes while not found sp_send_dbmail directly. You may use 'msdb.dbo.sp_send_dbmail' to try (Work fine on Windows Server 2008 R2 and is tested)


Examples related to sql

Passing multiple values for same variable in stored procedure SQL permissions for roles Generic XSLT Search and Replace template Access And/Or exclusions Pyspark: Filter dataframe based on multiple conditions Subtracting 1 day from a timestamp date PYODBC--Data source name not found and no default driver specified select rows in sql with latest date for each ID repeated multiple times ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database

Examples related to sql-server

Passing multiple values for same variable in stored procedure SQL permissions for roles Count the Number of Tables in a SQL Server Database Visual Studio 2017 does not have Business Intelligence Integration Services/Projects ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database How to create temp table using Create statement in SQL Server? SQL Query Where Date = Today Minus 7 Days How do I pass a list as a parameter in a stored procedure? SQL Server date format yyyymmdd

Examples related to tsql

Passing multiple values for same variable in stored procedure Count the Number of Tables in a SQL Server Database Change Date Format(DD/MM/YYYY) in SQL SELECT Statement Stored procedure with default parameters Format number as percent in MS SQL Server EXEC sp_executesql with multiple parameters SQL Server after update trigger How to compare datetime with only date in SQL Server Text was truncated or one or more characters had no match in the target code page including the primary key in an unpivot Printing integer variable and string on same line in SQL

Examples related to sp-send-dbmail

How to send email from SQL Server? Convert a SQL query result table to an HTML table for email 'profile name is not valid' error when executing the sp_send_dbmail command