Sending Email alert in SQL Server 2000 - sql-server

Hi would like to send an email alert after checking the result of a query which will return the numbers of rows in a table. Does anyone have any ideas how I could do this in SQL Server 2000 in 2005 I would use a maintenence plan but not sure how in 2000?

I did this a few years ago - hastily adapted from a MS Knowledgebase article. I changed the params to be hardcoded variables. I've removed the identifying servernames/email addresses etc etc from here but you should be able to figure it out!
CREATE PROCEDURE [dbo].[usp_SendSuccessMail]
--Adapted from a Microsoft KnowledgeBase article, Jan 16th 2006.
-- #From varchar(100) ,
-- #To varchar(100) ,
-- #Subject varchar(100)=" ",
--#Body varchar(4000) =" "
/*********************************************************************
This stored procedure takes the parameters and sends an e-mail.
All the mail configurations are hard-coded in the stored procedure.
Comments are added to the stored procedure where necessary.
References to the CDOSYS objects are at the following MSDN Web site:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cdosys/html/_cdosys_messaging.asp
***********************************************************************/
AS
Declare #From varchar(100) --origninally passed as parameter above. We want to hard-code it.
Declare #To varchar(100) --origninally passed as parameter above. We want to hard-code it.
Declare #Subject varchar(100) --origninally passed as parameter above. We want to hard-code it.
Declare #Body varchar(4000) --origninally passed as parameter above. We want to hard-code it.
Declare #iMsg int
Declare #hr int
Declare #source varchar(255)
Declare #description varchar(500)
Declare #output varchar(1000)
Set #From = 'abc#xyz.com'
Set #To = 'xyz#abc.com'
Set #Subject = 'Whatever Subject You Want'
Set #Body = 'Some useful text'
--************* Create the CDO.Message Object ************************
EXEC #hr = sp_OACreate 'CDO.Message', #iMsg OUT
IF #hr <>0 BEGIN
print 'sp_OACreate failed'
END
--***************Configuring the Message Object ******************
-- This is to configure a remote SMTP server.
-- http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cdosys/html/_cdosys_schema_configuration_sendusing.asp
EXEC #hr = sp_OASetProperty #iMsg, 'Configuration.fields("http://schemas.microsoft.com/cdo/configuration/sendusing").Value','2'
-- This is to configure the Server Name or IP address.
-- Replace MailServerName by the name or IP of your SMTP Server.
EXEC #hr = sp_OASetProperty #iMsg, 'Configuration.fields("http://schemas.microsoft.com/cdo/configuration/smtpserver").Value', 'mail.xxxxxxxxxx.com'
-- Save the configurations to the message object.
EXEC #hr = sp_OAMethod #iMsg, 'Configuration.Fields.Update', null
-- Set the e-mail parameters.
EXEC #hr = sp_OASetProperty #iMsg, 'To', #To
EXEC #hr = sp_OASetProperty #iMsg, 'From', #From
EXEC #hr = sp_OASetProperty #iMsg, 'Subject', #Subject
-- If you are using HTML e-mail, use 'HTMLBody' instead of 'TextBody'.
EXEC #hr = sp_OASetProperty #iMsg, 'TextBody', #Body
EXEC #hr = sp_OAMethod #iMsg, 'Send', NULL
IF #hr <>0
BEGIN
EXEC #hr = sp_OAGetErrorInfo NULL, #source OUT, #description OUT
IF #hr = 0
BEGIN
SELECT #output = ' Source: ' + #source
PRINT #output
SELECT #output = ' Description: ' + #description
PRINT #output
END
END
-- Do some error handling after each step if you have to.
-- Clean up the objects created.
send_cdosysmail_cleanup:
If (#iMsg IS NOT NULL) -- if #iMsg is NOT NULL then destroy it
BEGIN
EXEC #hr=sp_OADestroy #iMsg
END
ELSE
BEGIN
PRINT ' sp_OADestroy skipped because #iMsg is NULL.'
RETURN
END
GO

Because SQLMail is so useless for real world usage (MAPI, etc), we ended up using SQLAnswersMail which is very powerful and easy to use.

Perhaps CDOSYS will serve your needs, check the links below
Configuring SQL Server 2000
Notification with CDOSys
How to send e-mail without using SQL Mail in SQL Server?

Try this:
xp_smtp_sendmail
Link
http://www.sqldev.net/xp/xpsmtp.htm
I've used it before in production and it works great.

Related

How Do I Find SSL Certificate Full Path And Use in a StoredProcedure to call an API

How do I find the ssl certificate path? That one installed by VisualStudio, to be more expecific when we use .NET Core and run "dotnet dev-certs https --trust" at the console...
Could you guys help me pls?
Everything I've tried drop me in the certificate name only. I could not see the path to set on that pattern 'LOCAL_MACHINE\My\'Certificate Name'.
I want to pass it ike a parameter on the SQL code below:
EXEC #hResult = sp_OAMethod
#Object,
'setOption',
NULL,
3,
'LOCAL_MACHINE\My\'Certificate Name';
Just because I'm trying to call a API using SQL Server and I need to use that SSL certificate to run my tests.
Could you guys help me pls?
The return message I've got untill now says that it's not a valid certificate but I think it's bacause I'm not finding the full path.
I don't know if I made this clear... Just summarazing... I need to do this by sql and I need to know how to use SSL certificate path as a parameter.
There follows the code I'm using:
begin
declare #test as int;
declare #Object as int;
declare #hResult as nvarchar(256)
declare #Response as nvarchar(256)
exec #test = sp_OACreate 'MSXML2.XMLHTTP', #Object out;
select #test, #Object;
EXEC #hResult = sp_OAMethod
#Object,
'setOption',
NULL,
3,
'LOCAL_MACHINE\My\'Certificate Name';
exec #test = sp_OAMethod #Object, 'open', null, 'get',
'https://localhost:44351/api/v1/account/3215', 'false'
select #test
exec #test = sp_OAMethod #Object, 'send'
IF #test <> 0
BEGIN
EXEC sp_OAGetErrorInfo #object
RETURN
END
exec sp_OAMethod #Object, 'responseText', #Response OUTPUT;
end
print #Response
I had the same problem using the same VS-generated cert. I could find the cert called "localhost" in the certmgr ("Personal"->"Certificates"->localhost), installed when I began the project. I added this line:
EXEC #hr = sp_OAMethod #Object,'setOption',NULL,3,'LOCAL_MACHINE\My\localhost';
and it worked.
However, i found I could change the line to anything and it still worked, ie:
EXEC #hr = sp_OAMethod #Object,'setOption',NULL,3,'LOCAL_MACHINE\My\bogusfake';
So I cannot promise that will work for you, nor explain how/why, but I am able to proceed with the project of posting from a stored procedure to a local api. The only difference I see between my code and yours is I didn't surround the cert name in quotes.

Ole Automation Procedure returns null

I have the following issue. running the sql below on our server it returns the expected results. Running the same on another server it returns no values.
Did the following:
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO
USE tempdb
GO
IF OBJECT_ID('tempdb..#xml') IS NOT NULL DROP TABLE #xml
CREATE TABLE #xml ( yourXML XML )
GO
DECLARE #URL VARCHAR(8000)
--DECLARE #QS varchar(50)
-- & or ? depending if there are other query strings
-- Use this for when there is other query strings:
--SELECT #QS = '&date='+convert(varchar(25),getdate(),126)
-- Use this for when there is NO other query strings:
-- SELECT #QS = '?date='+convert(varchar(25),getdate(),126)
SELECT #URL = 'http://exampleURL' -- + #QS
DECLARE #Response varchar(8000)
DECLARE #XML xml
DECLARE #Obj int
DECLARE #Result int
DECLARE #HTTPStatus int
DECLARE #ErrorMsg varchar(MAX)
EXEC #Result = sp_OACreate 'MSXML2.XMLHttp', #Obj OUT
EXEC #Result = sp_OAMethod #Obj, 'open', NULL, 'GET', #URL, false
EXEC #Result = sp_OAMethod #Obj, 'setRequestHeader', NULL, 'Content-Type', 'application/x-www-form-urlencoded'
EXEC #Result = sp_OAMethod #Obj, send, NULL, ''
EXEC #Result = sp_OAGetProperty #Obj, 'status', #HTTPStatus OUT
INSERT #xml ( yourXML )
EXEC #Result = sp_OAGetProperty #Obj, 'responseXML.xml'--, #Response OUT
declare #input XML=(
SELECT
yourXML
from
#xml)
SELECT
Item.value('(Code)[1]', 'nvarchar(max)') as Code,
Item.value('(Description)[1]', 'varchar(max)') as Description,
Item.value('(ImageUrl)[1]', 'nvarchar(max)') as ImageUrl
from
#input.nodes('//product') AS T(Item)
Within the second server the #input returns null. There is a proxy to access the site on the server and it operates with sql server 2008.
Any ideas why the null values?
I just had a similar issue, a query using Ole Automation suddenly returns null without any error. After changing 'MSXML2.XMLHttp' to 'MSXML2.ServerXMLHTTP', it started to work again.
To know more about the difference between these two, see this article and Microsoft documentation. I copied some from Microsoft site, in case both sites are down in the future.
The ServerXMLHTTP object offers functionality similar to that of the XMLHTTP object. Unlike XMLHTTP, however, the ServerXMLHTTP object does not rely on the WinInet control for HTTP access to remote XML documents. ServerXMLHTTP uses a new HTTP client stack. Designed for server applications, this server-safe subset of WinInet offers the following advantages:
Reliability — The HTTP client stack offers longer uptimes. WinInet features that are not critical for server applications, such as URL caching, auto-discovery of proxy servers, HTTP/1.1 chunking, offline support, and support for Gopher and FTP protocols are not included in the new HTTP subset.
Security — The HTTP client stack does not allow a user-specific state to be shared with another user's session. ServerXMLHTTP provides support for client certificates.
So, it seems that my issue was that I had no access over the internet from my SQL server, so I had to use the below line to set the proxy.
exec #Result = sp_OAMethod #Obj, 'setProxy', NULL, '2', 'http://myProxy'
Once this was sorted, I managed to get my results.

Microsoft SQL Server and varbinary data type conversion

I'm not familiar with Microsoft SQL Server and the varbinary(max) data type but the database which I need to use stores images as that.
My question is what do I need to do to read that data back and convert it back to readable image type?
So far I have done was
SELECT CONVERT(VARCHAR(max), [IMAGE], 2)
FROM [demo].[dbo].[DOCIMAGES]
WHERE [TITLE] = 'test.jpg'
but what I have got it was almost the same just removed 0x from the beginning of that data when
SELECT CONVERT(VARCHAR(max), [IMAGE], 0)
FROM [demo].[dbo].[DOCIMAGES]
WHERE [TITLE] = 'test.jpg'
returns value as Lead.
Then I have tried to do stored procedure which will save it to a file like:
DECLARE #ImageData VARBINARY (max);
DECLARE #Path2OutFile NVARCHAR (2000);
DECLARE #Obj INT
SET NOCOUNT ON
SELECT #ImageData = (
SELECT CONVERT(VARBINARY(max), [IMAGE], 1)
FROM [demo].[dbo].[DOCIMAGES]
WHERE [TITLE] = 'test.jpg'
);
SET #Path2OutFile = CONCAT (
'C:\Users\MyPC\Downloads'
,'\'
,'test.jpg'
);
BEGIN TRY
EXEC sp_OACreate 'ADODB.Stream' ,#Obj OUTPUT;
EXEC sp_OASetProperty #Obj ,'Type',1;
EXEC sp_OAMethod #Obj,'Open';
EXEC sp_OAMethod #Obj,'Write', NULL, #ImageData;
EXEC sp_OAMethod #Obj,'SaveToFile', NULL, #Path2OutFile, 2;
EXEC sp_OAMethod #Obj,'Close';
EXEC sp_OADestroy #Obj;
END TRY
BEGIN CATCH
EXEC sp_OADestroy #Obj;
END CATCH
SET NOCOUNT OFF
but that fails with an error:
SQL Server blocked access to procedure 'sys.sp_OADestroy' of component
'Ole Automation Procedures' because this component is turned off as
part of the security configuration for this server. A system
administrator can enable the use of 'Ole Automation Procedures' by
using sp_configure.
Problem is that I'm not the admin of that server.
In that case can I dump content of the [IMAGE] to a file and then use Java or PHP to stream that content and save it as an image file?

SQL Server - Ole Automation Procedures Inside Queue Activation Procedure

I want to call a Webservice when a row inserted into a table.
So I enable Ole Automation Procedures, call Webservice like below and everything goes fine.
--enabling 'Ole Automation Procedures'
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO
--calling Webservice
create PROCEDURE callwebservice
#url varchar(128)=null
AS
Declare #Object as Int;
Declare #ResponseText as varchar(8000);
Exec sp_OACreate 'MSXML2.ServerXMLHttp.3.0', #Object OUT;
Exec sp_OAMethod #Object, 'open', NULL, 'get', #url ,'false'
Exec sp_OAMethod #Object, 'send'
Exec sp_OAGetProperty #Object, 'ResponseText', #ResponseText OUTPUT
Exec sp_OADestroy #Object
return
But, Since Webservice call is extremely lengthy, I need to do it with Service Broker. so I create a new stored-procedure and pass it as an activation parameter of my Queue like this:
--declare procedure
create procedure handleNewMessageInQueue
as
begin
DECLARE #TargetDlgHandle UNIQUEIDENTIFIER
DECLARE #ReplyMessage xml
DECLARE #ReplyMessageName
BEGIN TRAN;
receive top(1)
#TargetDlgHandle =Conversation_handle
,#ReplyMessage = Message_Body
,#ReplyMessageName = Message_Type_Name
from newUserQueue;
if #ReplyMessageName = '//goodType'
begin
exec callwebservice 'http://path/to/my/webservice'
end
commit tran;
end
--declare queue
create queue myQueue
with ACTIVATION (
PROCEDURE_NAME = handleNewMessageInQueue,
MAX_QUEUE_READERS =100,
EXECUTE AS owner
);
But this time, no request sent. I checked and I realize that the sp_OACreate method does not create the Object since the value of #Object is null after execution of it. Also when I call sp_OAGetErrorInfo to get error info, everything is null
I'm using SQL Server 2016
I appreciate if you can find the problem here.
EDIT
I found that if I enable TRUSTWORTHY on that database everything goes fine. but enabling it can open security hole.
is there any better way to do that?

Scheduled job not sending emails

I believe that dbMail is properly set up, I can send an email to myself using it.
But I have a scheduleded job which looks like;
DECLARE #Forename VARCHAR(50)
DECLARE #EmailAddress VARCHAR(50)
DECLARE #subject VARCHAR(500)
DECLARE #emailsubject VARCHAR(500)
Declare #bodypre as varchar(5000)
DECLARE #body VARCHAR(5000)
declare #recipients VARCHAR(5000)
Declare #emailStop as int
declare #replaceApproverName as varchar(20)
declare #link as varchar(100)
declare #replaceNextLine as varchar(20)
declare #profile_name as varchar(50)
declare #bodypost as varchar(5000)
declare #footerMessage as varchar(1000)
set #replaceApproverName ='$Approver'
set #replaceNextLine ='$NextLine'
set #link ='$Link'
DECLARE #NewLineChar AS CHAR(1) = CHAR(13)
select #emailsubject=EmailMessageSubject,
#bodypre = EmailMessageBody,
#emailStop = EmailStop_Flag
from STAS.dbo.MC_STAS_EmailMessage where TimeSheetStatusID = 2
SET #bodypre =Replace(#bodypre ,#link, 'http://liveweb.website.com/stas');
select #footerMessage =EmailMessageBody from STAS.dbo.MC_STAS_EmailMessage where MessageType='Footer'
SET #bodypre += #footerMessage;
SET #bodypre =Replace(#bodypre ,#replaceNextLine, #NewLineChar) ;
DECLARE emailCursor CURSOR FOR
SELECT distinct EmailAddress,Forename from [STAS].[dbo].[NotifictationEmailID_View] vw
OPEN emailCursor FETCH NEXT FROM
emailCursor INTO #EmailAddress,#Forename WHILE ##FETCH_STATUS = 0
BEGIN
if(#emailStop = 1)
set #EmailAddress = 'xxx.xxxx#xxxxx.co.uk'
set #bodypost = Replace(#bodypre,#replaceApproverName,#Forename)
EXEC msdb.dbo.sp_send_dbmail
#profile_name='STAS Alert',
#recipients =#EmailAddress,
#subject=#emailsubject,
#body =#bodypost;
FETCH NEXT FROM emailCursor INTO #EmailAddress,#Forename END
CLOSE emailCursor
DEALLOCATE emailCursor
When I look at the Database mail error log I see this;
The mail could not be sent to the recipients because of the mail server failure. (Sending Mail using Account 1 (2013-09-04T14:03:48). Exception Message: Cannot send mails to mail server. (The operation has timed out.).
Sending Mail using Account 1 . Exception Message: Cannot send mails to mail server. (Failure sending mail.).
Yet the profile 'STAS Alert' is set up and I can send an email using it to myself.
So why is this happening and what should I do to fix it?
Did you check out SQL Server Agent Properties/alert system ?
Mail profile should be enabled and your mail profile should be chosen correctly.

Resources