Sending SQL Notifications with CDOSYS

  • A friend of mine took the Microsoft example proc and produced a more robust version. It defaults to using the servername from @@servername if one is not provided, and it can send file attachments:





    PROCEDURE [dbo].[sp_sendmail_CDOSYS]


    varchar(100) ,


    varchar(100)=" ",


    varchar(4000) =" ",


    int = 1, -- 0=low, 1=normal, 2=high


    varchar(100)= " " ,


    varchar(100)= " " ,


    varchar(8000)=NULL, /* seperated by ; */


    int = 0,


    varchar(100)= null ,


    varchar(255) = null,


    varchar(255) = null,


    varchar(255) = null

    Created by : Corey Embry
    Description: Use CDOSYS to Send Mail using smtp
    Base Code was obtained from MS Article Q312839
    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:
    exec sp_sendmail_CDOSYS
    @To = ''
    , @Subject = 'CDOSYStest' -- Optional
    , @Body ='this is a test' -- Optional
    , @Importance int = 1 -- Optional
    , @cc = '' -- Optional
    , @Bcc = '' -- Optional
    , @Attachments = 'c:\test.txt' -- Optional ; Delimited
    , @HTMLFormat = 0 -- Optional Default Text
    -- , @From = '' -- Optional
    , @Server='avalafs1' -- Optional
    -- , @UserName= -- Optional
    -- , @Password= -- Optional


    SELECT @Server = isnull(@Server, @@SERVERNAME)

    Select @From = isnull(@From, @@SERVERNAME)

    Declare @iMsg int

    Declare @hr int

    Declare @int int

    Declare @Tmp varchar(8000)

    Declare @source varchar(255)

    Declare @description varchar(500)

    Declare @output varchar(1000)

    --************* Create the CDO.Message Object ************************

    EXEC @hr = sp_OACreate 'CDO.Message', @iMsg OUT

    --***************Configuring the Message Object ******************
    -- This is to configure a remote SMTP server.

    EXEC @hr = sp_OASetProperty @iMsg, 'Configuration.fields("").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("").Value', @Server

    if @UserName is not null and @password is not null


    EXEC @hr = sp_OASetProperty @iMsg, 'Configuration.fields("").Value', @UserName

    EXEC @hr = sp_OASetProperty @iMsg, 'Configuration.fields("").Value', @Password


    -- 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

    EXEC @hr = sp_OASetProperty @iMsg, 'CC', @cc

    EXEC @hr = sp_OASetProperty @iMsg, 'BCC', @BCC

    /* if there are any attachments */




    while len(@Attachments)>0


    set @int = charindex(';',@Attachments)

    if @int > 0


    set @Tmp = left(@Attachments,@int-1)

    set @Attachments = right(@Attachments,(len(@Attachments)-@int))

    end else


    set @Tmp = @Attachments

    set @Attachments = ''

    end /* Add the Attachment */

    Print @Tmp

    EXEC @hr= sp_OAMethod @iMsg, 'AddAttachment', NULL, @Tmp




    -- If you are using HTML e-mail, use 'HTMLBody' instead of 'TextBody'.


    @HTMLFormat <> 1


    EXEC @hr = sp_OASetProperty @iMsg, 'TextBody', @Body


    EXEC @hr = sp_OASetProperty @iMsg, 'HTMLBody', @Body


    -- Save the configurations to the message object.

    EXEC @hr = sp_OAMethod @iMsg, 'Configuration.Fields.Update', null

    EXEC @hr = sp_OAMethod @iMsg, 'Send', NULL

    -- Sample error handling.

    IF @hr <>0

    select @hr


    EXEC @hr = sp_OAGetErrorInfo NULL, @source OUT, @description OUT

    IF @hr = 0


    SELECT @output = ' Source: ' + @source

    PRINT @output

    SELECT @output = ' Description: ' + @description

    PRINT @output




    PRINT ' sp_OAGetErrorInfo failed.'




    -- Do some error handling after each step if you have to.
    -- Clean up the objects created.

    EXEC @hr = sp_OADestroy @iMsg


    Kindest Regards,


  • Comments posted to this topic are about the item Sending SQL Notifications with CDOSYS

  • This technique is an oldie but a goodie.

    One of Clinton Herring's contributions to "Script of the Day" a while back (I can't remember the date, but the script is dated 08/22/2001) does this too, and, might I add, is a bit more thorough than both examples posted above (Perhaps it gets overlooked because the script title is potentially misleading). 

    In any event, Clinton's version of this idea uses an OLE automation implementation of the CDOSYS dll, includes error handling, a help/usage message, a clever technique to verify attachments, and, IMHO, is very well-factored.

    In addition to any attachments you specify, Clinton's script can also perform a user-defined SQL Query (passed as a parameter to the SPROC), pipe the query results out to a text file (to the drive wih the most free space!), and attach the report to the email!  A great idea for automating server reports and emailing them to the DBA, or, generating application-specific reports and emailing them to your business stakeholders.

    See what you think!

    SQL 2K SMTP mail on Windows 2K

    Script Rating   Total number of votes [86]

    By: Clinton Herring

    SP_SQLSMTPMail is an OLE automation implementation of the CDOSYS dll for Windows 2000 which utilizes a network SMTP server rather than an Exchange server/Outlook client. The stored procedure functions similar to xp_sendmail including the ability to run a query and attach the results. No MAPI profile is required. It is also a working, detailed example of an OLE automation implementation. This update corrects a problem when the proc is called twice in the same batch without an intervening 'Go'. The cause is the sp_OAStop. It needs to be removed or commented out. The stated method of operation in the BOL is incorrect. 11/5/2002 Some people have reported errors when running this stored procedure. They have not been failures of the stored procedure. They are errors related to improper configuration/permissions for the SQL server to use the local network SMTP relay server for either internal or out going mail. 11/20/2002 Fixes a problem related to the OSQL call to send an attached query. OSQL was not releasing its lock on the first output file it created until the session ended, hence, calling the proc in a cursor or loop prevented subsequent query attachments. 04/09/2003 Comment correction.



  • Works great, just do not forget to remove the space in this line!

    EXEC @hr = sp_OASetProperty @iMsg, 'Configuration.fields("http://schemas.").Value', 'MailServerName'

  • I recently saw your article at and it solved my problem perfectly.

    Just wanted to say thanks.

    Windows 2008 Server | SQL Server 2008

  • I am using very simple VBscript to achieve the same thing, and attachements are allowed as well after small modification


    Set oMsg = CreateObject("CDONTS.NewMail")

     oMsg.From = "abc"

     oMsg.To = "abc"

     oMsg.Subject = "you message"

     oMsg.Body = "you message"


     Set oMsg = Nothing




  • Hi Clayton,

    I can't see how the Importance flag will work. You didn't call the method anywhere in the code?



  • I like the suggestions, and the ability to attach a SQL query output to an email.


    I know the following works - EXEC ('master..xp_cmdshell ''isql /o' + @filename + ' /d' + @database + ' /Q"' + @sqlquery + '" /E''')


    But the only problem with the above is that you need SYSADMIN access to run XP_CMDSHELL


    I also do NOT want to use XP_SENDMAIL as it uses MAPI .


    Is there any other way to attach SQL queries to an email ??

  • Has anyone been able to make the "Importance" or "Priority" work using CDOSYS ?

  • I was using the sqlsmtpmail code and attaching a step to all of my jobs to exec the proc on failures.  Problem is, how can I put the Job Name and/or step name that failed in the subject and/or body of the emails?  I have everything else working.


    Thanks all!

  • Anyone?

  • double bump

  • I have also been unable to find an answer to this question. Can anyone answer this?

  • I would like to reccomend to not send email by port using CDOSYS in a stored proceedure. There are problems with doing this which may not manifest until right away. If you do so, you will probably run into an issue when setting one of the items in the configuration's fields collection (ie an access violation). Its best to send via pickup directory when calling CDOSYS via a stored proceedure. Another alternative is to put the codd into a vb script and to call via DTS. Over all sending using a pickup directory of a locally installed smtp server is better than sending via port: the proc code won't have to connect to a remote server, it will be more reliable (still works and is relaible if the networks or remote server has issues or is down) and will be much faster since the code can fire-and-forget (CDOSYS will just write the message file out to the local directory and your code is done). The SMTP server will handle things from there. I know many people don't want to install SMTP on a SQL server, however it does not take up many resources/processing time, its a system component and you get a much better and reliable configuration.

    A quick thing to remember for CDOSYS: 1 if by land (pickup) 2 if by sea (port)

    You may want to read my blog posting on issues with using CDOSYS under a stored proceedure.

    I'll probably add more to the above blog entry later....



  • Thanks You!

    Works very well.

    Regards, Emito.:D

Viewing 15 posts - 1 through 15 (of 16 total)

You must be logged in to reply to this topic. Login to reply