SQL Mail to send emails to users specified in a query only - sql

I've about 1 month of experience when it comes to SQL and I wanted to send emails to customers based on query criteria. The challange I have is that the emails should only go to users emails that show up in the query. Below is an example of the data. I have no idea what I should do to setup the auto emailing based on a query. Any help is greatly appreciated!
My query would look like this,
select *
from [Tbl]
where [Date Certificate is Expiring]
Between getdate()-372 AND getdate()-371
OUTPUT:
USER ID | Email | Date Certificate is Expiring
NOTE: I do not have access to Visual Basic, SSRS, SSIS, or any other tool than Database Engine and dbMail

Please create DB mail profile first, then put it into below query:
DECLARE #MailRecipients NVARCHAR(MAX);
SELECT #MailRecipients = STUFF((
SELECT DISTINCT ';' + t.Email
FROM [Tbl] t
WHERE t.[Date Certificate is Expiring] BETWEEN GETDATE()-372 AND GETDATE()-371
FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)'),1,1,'')
;
IF COALESCE(#MailRecipients,'') <> ''
BEGIN
EXEC msdb.dbo.sp_send_dbmail
#profile_name = ..., -- <-- you have to create DBMailProfile first
#recipients = #MailRecipients,
#subject = 'Email about expiring stuff',
#body_format = 'HTML',
#body = 'Hi there, your something is expired',
#importance = 'Normal'
END

Related

SQL Agent runs procedure to send email with success but email doesn't arrive

Basically I have a SQL JOB that runs a procedure responsible for executing a query and sending an email with msdb.dbo.sp_send_dbmail, when I run the procedure, works as intended and the email is delivered. But when I created a job in the SQL Agent, the jos runs with success but no email is delivered.
The procedure in question is this one:
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'Active_users',
#recipients = 'teste0#teste.com;teste1#teste.com',
#subject = 'List',
#body = 'Users',
#query = 'SELECT Top 1000
[caller_id]
,[session_start_dt]
,[session_end_dt]
,[caller_address]
,[caller_type]
FROM [database].[db].[teste1]
where session_end_dt IS NULL
order by caller_id desc' ,
#attach_query_result_as_file = 1,
#query_attachment_filename = 'users.csv',
#query_result_header = 1,
#query_result_no_padding = 1,
#exclude_query_output = 1;
My first though was a permissions issue that the user SQLAgtAct didnt had acess to the database in question, but it has and has the role of db_datareader, db_datawriter, db_ddladmin.
I don't know if the user SQLAgtAct needs any more permissons, than this ones, since the job runs with sucess.

SQL Server DB_mail sending multiple counts

I am using db_mail in SQL Server 2008 r 2 to send counts of mail daily.
How can I send 1 email daily that has 3 counts ( Count A, Count B, Count C) included?
You can use a query with multiple columns as you want.
[ #query = ] 'query'
Is a query to execute. The results of the query can be attached as a file, or included in the body of the e-mail message. The query is of type nvarchar(max), and can contain any valid Transact-SQL statements. Note that the query is executed in a separate session, so local variables in the script calling sp_send_dbmail are not available to the query.
Sample query:
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'Adventure Works Administrator',
#recipients = 'danw#Adventure-Works.com',
#query = 'SELECT COUNT(*) As CountA, 1 As CountB, 2 As CountC
FROM AdventureWorks2012.Production.WorkOrder
WHERE DueDate > ''2004-04-30''
AND DATEDIFF(dd, ''2004-04-30'', DueDate) < 2' ,
#subject = 'Work Order Count',
#attach_query_result_as_file = 1 ;
You can also use a variable to set in the body.

Stored procedure using sp_send_dbmail to send emails to multiple recipients queried from database

Like the title says, I'm trying to make a stored procedure used to send emails to addresses stored in the database, often including multiple recipients. I've tried a few approaches to this, but I think I'm hitting a wall and would appreciate any input anyone has. The main issue I've had is querying the database for the addresses and passing that to sp_send_dbmail in a way that works.
The address table is pretty simple, looks something like this, but much larger. Both columns are varchars:
idNumber | email
__________________________
a123 | steve#test.com
a123 | carol#test.com
1-100 | mary#test.com
So if we're sending to ID number "a123", an email needs to go to both Steve and Carol.
Here's a super simple procedure. It's not verbatim since this is all on my work computer, but more of a skeletal gist of what I'm going after.
CREATE PROCEDURE sendMail
#idNumber varchar(MAX),
#subject varchar(MAX),
#body varchar(MAX)
EXEC msdb.dbo.sp_send_dbmail
#recipients = "EXEC SELECT email FROM emailTable WHERE idNumber = " + #idNumber + "';",
#subject = #subject,
#body = #body;
It throws and error; it doesn't seem to like concatenating the ID parameter into the query. I tried making a separate procedure to query emails, but passing the ID parameter to the procedure didn't seem to work either. Even if I did successfully pass the parameter and get the query to execute successfully, I'd still need to join the two results in a single string and delimit them with semicolons so they'll play nice with sp_send_dbmail. I think?
SQL wizards, how would you approach this? I'm not wildly experienced, so is there something simple and syntactic I'm doing wrong? Is my approach flawed fundamentally?
I appreciate your input. Thank you.
EDIT: Here's Kritner's working solution! Thanks a bunch!
CREATE PROCEDURE testMail2
#idNumber varchar(MAX)
AS
BEGIN
DECLARE #recipientList varchar(MAX)
SET #recipientList = (STUFF((SELECT ';' + email FROM emailTable WHERE idNumber = #idNumber FOR XML PATH(' ')),1,1,''))
EXEC msdb..sp_send_dbmail
#recipients=#recipientList,
#subject='Subject Line',
#body='Body Text'
END
You can do a query and assign the values to a variable as such:
DECLARE #myRecipientList varchar(max)
SET #myRecipientList = (STUFF((SELECT ';' + emailaddress FROM table FOR XML PATH('')),1,1,''))
This will set your #myRecipientLIst to a ";" delimited list of the recipients specified your query.
You could also do the same sort of idea with a SP, just throw them into a temp/variable table and stuff into a semi colon separated list.
EDIT:
Finally to send the mail you could do:
EXEC msdb.dbo.sp_send_dbmail
#recipients = #recipientList,
#subject = #subject,
#body = #body // ........
COMMENT EDIT:
based on your original query, your stuff query should look something like this:
DECLARE #myRecipientList varchar(max)
SET #myRecipientList = STUFF((SELECT ';' + email FROM emailTable WHERE idNumber = #idNumber FOR XML PATH('')),1,1,'')
The idea behind this is - for every email found in the email table append to #myrecipientList the email found and a semi colon.

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.
Step 1) Create Profile and Account
You need to create a profile and account using the Configure Database Mail Wizard which can be accessed from the Configure Database Mail context menu of the Database Mail node in Management Node. This wizard is used to manage accounts, profiles, and Database Mail global settings.
Step 2)
RUN:
sp_CONFIGURE 'show advanced', 1
GO
RECONFIGURE
GO
sp_CONFIGURE 'Database Mail XPs', 1
GO
RECONFIGURE
GO
Step 3)
USE msdb
GO
EXEC sp_send_dbmail #profile_name='yourprofilename',
#recipients='test#Example.com',
#subject='Test message',
#body='This is the body of the test message.
Congrates Database Mail Received By you Successfully.'
To loop through the table
DECLARE #email_id NVARCHAR(450), #id BIGINT, #max_id BIGINT, #query NVARCHAR(1000)
SELECT #id=MIN(id), #max_id=MAX(id) FROM [email_adresses]
WHILE #id<=#max_id
BEGIN
SELECT #email_id=email_id
FROM [email_adresses]
set #query='sp_send_dbmail #profile_name=''yourprofilename'',
#recipients='''+#email_id+''',
#subject=''Test message'',
#body=''This is the body of the test message.
Congrates Database Mail Received By you Successfully.'''
EXEC #query
SELECT #id=MIN(id) FROM [email_adresses] where id>#id
END
Posted this on the following link http://ms-sql-queries.blogspot.in/2012/12/how-to-send-email-from-sql-server.html
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='user#yourdomain.com',
#subject='Testing Email from SQL Server',
#body='<p>It Worked!</p><p>Email sent successfully</p>',
#body_format='HTML',
#from_address='Sender Name <sender#yourdomain.com>',
#reply_to='sender#yourdomain.com'
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.
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
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 ('foo#foobar.com')
INSERT #emailAddresses (email) VALUES ('bar#foobar.com')
INSERT #emailAddresses (email) VALUES ('buzzlightyear#foobar.com')
DECLARE #recipients VARCHAR(MAX)
SELECT #recipients = COALESCE(#recipients + ';', '') + email
FROM #emailAddresses
SELECT #recipients
DROP TABLE #emailAddresses
The resulting #recipients will be:
foo#foobar.com;bar#foobar.com;buzzlightyear#foobar.com
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 = 'xxxx#xxxx.com',
#body = #results,
#subject = #subjectText,
#exclude_query_output = 1 --Suppress 'Mail Queued' message
GO
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)
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
--Sending Test Mail
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'TestProfile',
#recipients = 'To Email Here',
#copy_recipients ='CC Email Here', --For CC Email if exists
#blind_copy_recipients= 'BCC Email Here', --For BCC Email if exists
#subject = 'Mail Subject Here',
#body = 'Mail Body Here',
#body_format='HTML',
#importance ='HIGH',
#file_attachments='C:\Test.pdf'; --For Attachments if exists

SQL mail ------DATABASE MAIL

Dear all,
I am using SQL Server 2008.
I am facing a scenario where I have to send mail to single or multiple user depending on the query. I tried this stmt to send mail to multiple recipients
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'imran' ,
#recipients= 'imran.khan#bbraun.com;amol.puranik#bbraun.com',
#subject = 'Test mail'
It succesfully sent mail.
Now I want to send mail depending on query. With single employee it is no issue, but if it is more then one employee how can I mail to multiple recipients.
That is my question is in this sp to send multiple recipients one has to separate addresses with ; . How can I arrange recipients so that the ; comes in between.
Thank you.
Unfortunately, you're not giving us a lot to go on - you don't show us the query to select your employees, you're not telling us anything about what the Employee table looks like, so all we can do is guessing - at best.
So here's my guess: you want to somehow select multiple employees, and their e-mail addresses should be concatenated together, separated by a semicolon (;), and then used for your sp_send_dbmail call.
One method to do this could be this:
DECLARE #recipients VARCHAR(4000)
SELECT
#recipients = STUFF((SELECT ';' + EMail
FROM dbo.Employees
WHERE (some condition here to find the right employees)
FOR XML PATH('')
), 1, 1, '')
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'imran',
#recipients,
#subject = 'Test mail'
Use a function like this -
CREATE FUNCTION coltocsv
(
--your input parameters
)
RETURNS nvarchar(3000)
AS
BEGIN
-- Declare the return variable here
declare #keywords nvarchar(3000)
--Build your csv string of keywords
Select #keywords = null
SELECT #Keywords = Coalesce(#Keywords + '; ', '') +
ColumnName
from Table
where <some condition>
--- Return the result of the function
RETURN #keywords
END
for the recipients, you can seggregate the miultiple email id's by [];
declare #ccmailid varchar(2000);
select #ccmailid = stuff((select '],['+ mailid from table_name
order by '],['+ mailid
for xml path('')),1,2,'')+']'
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'imran' ,
#recipients= #ccmailid,
#subject = 'Test mail'