db sendmail in SQL still showing rows affected after params turned off - sql

I'm sending results through an XML variable formatted with CSS and HTML in the body of an email. I have everything exactly the way I want it and it's still showing the garbled text query at the bottom of the HTML email. I have the #exclude_query_output turned off as well as SET NOCOUNT ON; in the actual #query paramater.
I've even tried to use NOCOUNT ON in the XML part of the SELECT statement and it's not working. Everything else seems to be working great but the text query still shows at the bottom of the email.
I'm pasting partial code due to security but here is some of it:
DECLARE #xml NVARCHAR(MAX)
declare #variousothervariableshere, like #subject1
SET #subject1 = 'Send Statistics for '+ #datenamemonth + ' ' + #datenameyear
set nocount on;
SET #xml = CAST(( SELECT
'left' as [td/#align], Task AS 'td','', 'center' as [td/#align], NumofRecords AS 'td',''
FROM [mytablehere] FOR XML PATH('tr'), ELEMENTS ) AS NVARCHAR(MAX))
set #HTMLBody = '<html><head>'
+ '<style>'
+ 'th {border: solid blue 1px;padding-left:5px;padding-right:5px;padding-top:1px;padding-bottom:1px;font-size:11pt;} '
+ 'td {border: solid blue 1px;padding-left:5px;padding-right:5px;padding-top:1px;padding-bottom:1px;font-size:11pt;} '
+ '</style>'
+ '</head>'
+ '<body>'
+ '<p>'
+ '<table border="1">'
+ '<tr>'
+ '<th style="color:#fff000;">Num of Records</th>'
+ '</tr>'
set #HTMLBody = #HTMLBody + #xml + '</table></body></html>'+'<font face="Verdana" size="2" color="#333333"><p><br />Thanks,<br />My name here<p><p>'
EXEC msdb.dbo.sp_send_dbmail
#exclude_query_output = 1,
#query_result_header = 0,
#profile_name = 'myprofilename',
#recipients = 'myemail#email.com',
#subject = #subject1,
#query = 'SET NOCOUNT ON; select * from [mytablehere]; SET NOCOUNT OFF;',
#body_format = 'HTML',
#body = #htmlbody
--end
Here is what is at the bottom of the email:
Files Imported 0 Total Clean Records Imported 0 Emails Successfully Sent 0 Emails Queued or Retried to Send 0 Emails Failed 0 Number of Emails Exported for Manual Send due to No Data 0
This the exact text that is the HTML formatted table I have right above it. It looks great in the table but I'm getting these results which is the exact query in text and it shouldn't be there because it's formatted in the table above.
Any suggestions would be awesome. Also this is not the full HTML but you get the idea.

Remove the #query parameter from the dbo.sp_send_dbmail call.
EXEC msdb.dbo.sp_send_dbmail
#exclude_query_output = 1,
#query_result_header = 0,
#profile_name = 'myprofilename',
#recipients = 'myemail#email.com',
#subject = #subject1,
#body_format = 'HTML',
#body = #htmlbody

Related

SQL sending email with data

I am trying to send a table via email in a table like shape. What I mean is to style nicely the text that I am receiving in email, because now it looks ugly, not like a table. Any help would be much appreciated.
ALTER PROCEDURE [dbo].[testEmail]
AS
BEGIN
DECLARE #SubjectText VARCHAR(100) = 'Day ' + CONVERT(VARCHAR,(CONVERT(DATE,GETDATE())))
DECLARE #tab char(1) = CHAR(9);
BEGIN
EXEC msdb.dbo.sp_send_dbmail
#query = 'SELECT IDDruzyny, nazwa FROM TEST.dbo.Druzyna',
#body = '
<html>
<body>
<br/><b><font color=red>Hiho</font></b>
</body>
</html>
',
#Body_format = 'HTML',
#subject = #SubjectText,
#profile_name = 'SIT',
#recipients = 'safemail#onet.eu',
#attach_query_result_as_file = 0,
#query_result_separator = #tab,
#query_result_header = 1
END
END

sp_send_dbmail Column Header Format Issue (Incorrect syntax near '#Column1Name')

I keep getting an "Incorrect syntax near '+' error when trying to concatenate the column header. I'm trying to follow the tutorial below:
https://www.purplefrogsystems.com/blog/2014/04/excel-doesnt-open-csv-files-correctly-from-sp_send_dbmail/
DECLARE #tab char(1) = CHAR(9)
DECLARE #Column1Name VARCHAR(255)
SET #Column1Name = '[sep=,' + CHAR(13) + CHAR(10) + 'Date]'
EXEC msdb.dbo.sp_send_dbmail
#recipients = 'test#gmail.com',
#attach_query_result_as_file = 1,
#query_attachment_filename='test.csv',
#query_result_separator=#tab,
#query_result_no_padding=1,
#body = 'See attached file',
#subject = 'Testing Data',
#query = '(SELECT CONVERT(CHAR(20), Date, 20) AS' + #Column1Name + ',
Column2 FROM testTable)'
You can't supply expressions as parameters when executing stored procedures.
Set the full result to a variable first, then simply pass that variable as the parameter:
DECLARE #tab char(1) = CHAR(9)
DECLARE #Column1Name VARCHAR(255)
SET #Column1Name = '[sep=,' + CHAR(13) + CHAR(10) + 'Date]'
DECLARE #query VARCHAR(MAX) = '(SELECT CONVERT(CHAR(20), Date, 20) AS' + #Column1Name + ', Column2 FROM testTable)'
EXEC msdb.dbo.sp_send_dbmail
#recipients = 'test#gmail.com',
#attach_query_result_as_file = 1,
#query_attachment_filename='test.csv',
#query_result_separator=#tab,
#query_result_no_padding=1,
#body = 'See attached file',
#subject = 'Testing Data',
#query = #query
PD: You might want to check if you need to add a space between concatenations when building dynamic SQL. In this case it's not needed as you already have the square brackets, but might as well get used to adding spaces.
... '20) AS ' + #Column1Name + ' , Column2 FROM testTable)'
You might need to add an extra space in.
Currently it will resolve to CONVERT(CHAR(20), Date, 20) AS#Column1Name

Using a variable as #Subject with sp_send_dbmail

I got the following Code which runs more or less smoothly.
DECLARE #MyId char(4),#MyResult varchar(max), #MySubject varchar(max);
SET #ID = 5;
SET #MyId = #ID;
SELECT #MyResult = SQL_Script FROM Table1 WHERE ID = + #MyId;
SELECT #MySubject = Subject FROM Table1 WHERE ID = + #MyId;
EXEC msdb.dbo.sp_send_dbmail
#profile_name='Operator',
#recipients= 'test#mail.com',
#subject= #MySubject,
#query_result_separator = ' ',
#query_result_no_padding= 1,
#body= 'test',
#query_attachment_filename = 'Test.csv',
#query= #MyResult ,
#mailitem_id='1',
#attach_query_result_as_file = 1
END
The result of the Query which is store in #MyResult works just fine, but when I store a String in #MySubject I won't get a Mail.
If I write:
#subject= #MySubject, <-- Doesn't work (The String is not 'NULL')
#subject = 'test', <-- works
I have to save a String, which is located in Table1, into #MySubject and then use it as Subject for my Mail.
Sadly it has to be dynamic so I somehow have to get this to work.
using variable is not the issue.
Probably, this
#MySubject varchar(max)
the #subject parameter supposed to be nvarchar(255)
what is the value of #MySubject ? is it readable text ?
Spaces seem to be the problem:
SET #Subj = 'Test Subject' <- does not work
SET #Subj = 'Test_Subject' <- works

Use send_dbmail to send an email for each row in sql table

I am having difficulties figuring out how to make send_dbmail loop through my table and send a new email for each record. My table is dropped and re-created each time this package runs, sometimes it will have zero records, other times it may have a few (never anything significant, always < 10).
This works fine when I have a single row but when I add a second row the subquery fails as it doesn't produce a unique result, so my question is how can I make this send a separate email for each row that might exists and how do I make it not send a message if no rows exists?
I have to send this via a TEXT body format as it is being grabbed by a third party mail eater that only supports text.
Thanks for any suggestions!
use automationdb
declare #bodytext as nvarchar(max)
set #bodyText = ( SELECT
N'%z_Curr_Contact_Number =
%string1 = na
%string1 = na
%string2 = na
%zneed_by_date = '+ CONVERT(VARCHAR(20), dateadd(day,1,GETDATE()),100) + N'
' + '%Description=' + 'ID: ' + isnull(id,'Unknown') + N'
' + '%Description=' + 'Name: ' + isnull(name,'Unknown') + N'
' + '%Description=' + 'Login: ' + isnull(login,'Unknown') + N'
' + '%Description=' + 'Status: ' + isnull(status,'Unknown') + N'
' + '%Description=' + 'Note One: ' + isnull(note_one,'Unknown') + N'
' + '%Description=' + 'Role: ' + isnull(role_id,'Unknown') + N'
' + '%Description=' + 'Role Name: ' + isnull(role_name,'Unknown') + N'
' + '%Description=' + 'Location: ' + isnull(Location,'Unknown') + N''
FROM dbo.mpt)
EXEC msdb.dbo.sp_send_dbmail
#profile_name = 'test',
#body = #bodyText,
#body_format ='TEXT',
#recipients = 'random#email.com',
#subject = 'send_dbmail test' ;
1) You could use a LOCAL FAST_FORWARD cursor to read every row and then to execute sp_send_dbmail
or
2) You could dynamically generate a sql statement that includes the list of EXEC sp_send_dbmail statements like this:
DECLARE #SqlStatement NVARCHAR(MAX) = N'
EXEC msdb.dbo.sp_send_dbmail #recipients=''dest01#domain.com'', ...;
EXEC msdb.dbo.sp_send_dbmail #recipients=''dest02#domain.com'', ...;
EXEC msdb.dbo.sp_send_dbmail #recipients=''dest03#domain.com'', ...;
...';
EXEC(#SqlStatement);
or
DECLARE #bodyText NVARCHAR(MAX);
SET #bodyText = ...;
DECLARE #SqlStatement NVARCHAR(MAX) = N'
EXEC msdb.dbo.sp_send_dbmail #recipients=''dest01#domain.com'', #body = #pBody, ...;
EXEC msdb.dbo.sp_send_dbmail #recipients=''dest02#domain.com'', #body = #pBody, ...;
EXEC msdb.dbo.sp_send_dbmail #recipients=''dest03#domain.com'', #body = #pBody, ...;
...';
EXEC sp_executesql #SqlStatement, N'#pBody NVARCHAR(MAX)', #pBody = #bodyText;

The body of the email can't be seen when using sp_send_dbmail in sql server 2005

I create a procedure to send automatic emails. The email gets to the address and everything seems working fine but the body can not be seen. I'm using sql 2005 and MS exchange server 2007. The part of the procedure that writes the body is as follow.
declare #bodymsg as varchar(1000)
set #bodymsg = 'The application '
set #bodymsg = #bodymsg + #appnum
set #bodymsg = #bodymsg + ' have been auto assign to you by the call center auto assign program.'
set #bodymsg = #bodymsg + CHAR(13)
set #bodymsg = #bodymsg + 'The borrower information is as follow:'
set #bodymsg = #bodymsg + CHAR(13)
set #bodymsg = #bodymsg + 'Name: '
set #bodymsg = #bodymsg + #borrower
set #bodymsg = #bodymsg + CHAR(13)
set #bodymsg = #bodymsg + 'Email: '
set #bodymsg = #bodymsg + #borremail
set #bodymsg = #bodymsg + CHAR(13)
set #bodymsg = #bodymsg + 'Phone: '
set #bodymsg = #bodymsg + #borrhome
set #bodymsg = #bodymsg + CHAR(13)
set #bodymsg = #bodymsg + 'Cellphone: '
set #bodymsg = #bodymsg + #borrcell
set #bodymsg = #bodymsg + CHAR(13)
set #bodymsg = #bodymsg + CHAR(13)
set #bodymsg = #bodymsg + 'Please contact the borrower ASAP.'
execute [msdb].[dbo].[sp_send_dbmail]
#profile_name = 'CallCenter',
#recipients = #email,
#subject = #subjectmsg,
#body = #bodymsg,
#body_format = 'TEXT'
Just to add to kevchadders reply, when you call PRINT #bodymsg, if it prints nothing at all then you know that it's a null-concatenation problem.
If you wrap each variable you append in the ISNULL() function, then it will be easier to find which variable is causing the problem.
eg.
set #bodymsg = #bodymsg + ISNULL(#appnum,'')
Then the body of the email will be printed, but there will be a missing parameter. Then you need to find out why the parameter is missing.
Just before you execute the sp_send_dbmail PRINT the #bodymsg parameter out so that you know the data has been built correctly.
e.g.
PRINT #bodymsg
execute [msdb].[dbo].[sp_send_dbmail]
#profile_name = 'CallCenter',
#recipients = #email,
#subject = #subjectmsg,
#body = #bodymsg,
#body_format = 'TEXT'
As you passing a number of parameters to it one of them could be setting the #bodymsg to NULL
Generally when I have this problem with the sp_send_dbmail, it is related to passing more characters or data then the #body variable can handle. SQL Server throws an error saying that the data would be truncated. The error is not fatal, so the stored procedure continues running resulting in an email without a body.