Sql server email

Hi all,
I have a question regarding the stored procedure results. I have two stored procedures. stored procedure  [spSync_Prod2Dev] and stored [dbo].[SpEmail_spSync_Prod2Dev]. Here stored procedure  [spSync_Prod2Dev] will load data from Production to DEV,
this will be done every week. So ones it runs I should get an email "data loaded successfull" For this I have created another stored procedure called stored [dbo].[SpEmail_spSync_Prod2Dev], So ones stored procedure runs
exec [dbo].[SpEmail_spSync_Prod2Dev]  this stored proc this willgenerate a result values either it's 0 -1 or 1 based on this output it should call this stored procedure [spSync_Prod2Dev]. If the [SpEmail_spSync_Prod2Dev] result is 0 then
it should email me an "Error message" and if the [SpEmail_spSync_Prod2Dev] result is success (1) it should go the this  [spSync_Prod2Dev]. stored proc and it should execute the SP ,and get an success email "Data loaded".
Could you please help me on this. And I think I am clear if not you can ask me for questions.
Thanks,
sidhu

Why not use a Try Catch for this???
USE [YOUR_DB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Table_Name]
AS
BEGIN TRY
INSERT [dbo].[Table_Production]
Select *
FROM [dbo].[Table_Staging]
SET NOCOUNT ON
declare @RowCount as int
declare @EmailBody as varchar(1000)
SELECT @RowCount = count(*) FROM [dbo].[Table_Staging]
set @EmailBody = 'Successfully Loaded TABLE' + cast(@RowCount as varchar(50)) + ' records loaded'
IF @RowCount > 0
BEGIN
exec msdb.dbo.sp_send_dbmail @profile_name = 'MailTest',
@recipients = '[email protected]',
@subject = 'Successfully Production',
@body = @EmailBody,
@body_format = 'HTML'
END
END TRY
BEGIN CATCH
-- SELECT ERROR_NUMBER() AS ErrorNumber;
exec msdb.dbo.sp_send_dbmail @profile_name = 'MailTest',
@recipients = '[email protected]',
@subject = 'WARNING did NOT load Production',
@body = 'WARNING did NOT load Production + @@RowCount ',
@body_format = 'HTML'
END CATCH;
Please see these links for more info.
http://www.sqlservercentral.com/blogs/querying-microsoft-sql-server/2013/09/02/sending-mail-using-sql-server-express-edition/
http://www.dotnet-tricks.com/Tutorial/sqlserver/4761260812-Remove-unsent-database-email-from-SQL-Server.html
http://www.mytechmantra.com/LearnSQLServer/Troubleshooting-SQL-Server-blocked-access-to-procedure-sp_send_dbmail.html
Knowledge is the only thing that I can give you, and still retain, and we are both better off for it.

Similar Messages

  • SQL Server 2012 Database Email is not working with AWS SES Services

    Hi Greetings to all,
    I have issue with the SQL Server Database mail Services. I have Configured Amazon Simple Email Services (AWS SES) as db profile in SQL Server and for last 2 years its working perfectly. But, from last two days on wards it is not working properly the Emails
    are queued but not sent to the recipients. the SES Services are working fine in outlook. but, not working in SQL Server. 
    Please help on this. tried changing the ports no result only one or two emails only sent remaining are failing.the info messages is as below
    Message
    The mail could not be sent to the recipients because of the mail server failure. (Sending Mail using Account 10 (2015-04-10T17:12:41). Exception Message: Cannot send mails to mail server. (The operation has timed out.).
    RehaanKhan. M

    Hello,
    Try to use port 465, port 2587 or port 587 instead of using port 25, as explained on the following articles.
    http://docs.aws.amazon.com/ses/latest/DeveloperGuide/smtp-issues.html
    http://docs.aws.amazon.com/ses/latest/DeveloperGuide/smtp-connect.html
    The first of above URLs is intended for troubleshooting SMTP issues in general.
    Verify you the mail account has not reached any limit. Limit of emails per day, per second, etc.
    Hope this helps.
    Regards,
    Alberto Morillo
    SQLCoffee.com

  • How to send PLAIN text email from sp_send_dbmail using SQL Server 2008 R2?

    I have configured Database Mail in SQL Server 2008 R2 (64) and it sends emails just fine. However the destination is recieving the body of thes message as Base 64 encoding.
    Snippet:
    EXEC msdb..sp_send_dbmail @profile_name='Outmail', @recipients = @recpts, @subject = @subj, @body_format = 'TEXT', @body=@body2;
    As you can see I set @body_format to TEXT, but it still sends Base 64. I need to send plain ASCII text. How can I change this?

    I am having this exact issue too.  I have a trigger that sends an email using a stored procedure.  The dbmail is sending the email using the Exchange 2010 server SMTP.  It does not login so the email is relayed as user = "Anonymous". 
    The SQL dbmail email header is showing the following:
    Content-Type: text/plain; charset="utf-8"
    Content-Transfer-Encoding: base64
    MIME-Version: 1.0
    X-MS-Exchange-Organization-AuthSource: MX01.domain.local
    X-MS-Exchange-Organization-AuthAs: Anonymous
    Here is the header if I send via Outlook profile using the legacy program I am trying to automate using SQL Server 2008R2:
    Content-Type: application/ms-tnef; name="winmail.dat"
    Content-Transfer-Encoding: binary
    MIME-Version: 1.0
    X-MS-Has-Attach:
    X-MS-Exchange-Organization-SCL: -1
    X-MS-TNEF-Correlator: <[email protected]>
    MIME-Version: 1.0
    X-MS-Exchange-Organization-AuthSource: MX01.domain.local
    X-MS-Exchange-Organization-AuthAs: Internal
    X-MS-Exchange-Organization-AuthMechanism: 03
    X-Originating-IP: [192.168.13.66]
    Any help would be greatly appreciated!

  • Data Driven EMail Subscription in SQL Server Reporting Services...

    Hi,
       I have a clarification in SQL Server Reporting Services Data Driven Subscription. We have a request to send an email a report based on the report parameter Site . The request is to send email For each site the report is running, email should sent to different recipients list. We have 97 different sites in the Site parameter.
       If Report is running for Site C004 the email should be sent to one recipient, if the Report is running for Site C007 , then the email should be sent to another recipient. Here we have been requested to do with Data-Driven Subscription. How to send the report as a email for each site for different Recipients using Data Driven EMail Subscription.
    Please give us a suggestion to overcome this problem.
    Thanking You...

    Hi David,
    Thanks for your comments. We understand the Data Driven subscription, but we dont know how to write query for this subscription. here is our scenario.
    There are list of sites in the table. like C004, C007, C008 etc..... in the report,
    We have Site parameter (All Sites (default), C004, C007 etc....) and also date range parameter (Start Date, End date) (which are not defaulted in the report) and other 2 parameters. Here we need to send the report to different recipients based on the site. C004 report results should be develivered to one recipient, C007 site results should be delivered to another recipient and so on....
    As we are new to Data driven subscription, can you explain how to create table that will be saving the email recipients list and the query that we are specifying in the Data Driven Subscription. Please help us to how to create the data driven subscription for the above scenarion. 
    Thanks and Regards,
    Sundarrajan.G

  • SQL server agent send email

    I set up email notification for a job completes. I configured database mail profile and mail account. This works fine and I can send out test email.
    However, the SQL agent couldn't send out email and when I tried to restart the SQL server agent, I got the following errors:
    Message
    [260] Unable to start mail session (reason: Microsoft.SqlServer.Management.SqlIMail.Server.Common.BaseException: Mail configuration information could not be read from the database. ---> System.InvalidCastException: Unable to cast object of type 'System.DBNull'
    to type 'System.Byte[]'.
       at Microsoft.SqlServer.Management.SqlIMail.Server.DataAccess.DataAccessAdapter.GetAccount(Int32 accountID)
       --- End of inner exception stack trace ---
       at Microsoft.SqlServer.Management.SqlIMail.Server.DataAccess.DataAccessAdapter.GetAccount(Int32 accountID)
    My SQL server is SQL 2008 with service pack 3.
    Anybody has any idea what's the problem is?
    Thanks

    Hi Ying,
    You could try below suggestions.And restart SQL Server Agent.
    Please refer:
    http://www.developerjoint.com/kb/9363-trouble-with-sql-2005-database-mail.aspx.
    Thanks,
    Maggie
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. This can be beneficial to other community members reading the thread.

  • Script to send email notification when sql server stops..

    Hi,
    I am looking for a script through which I can monitor sql server service status and if it down for any reason, I want to send email to Dba team.  How to achieve this? Did anyone has already done similar kind of monitoring?
    Again, I am not looking for any 3rd party monitoring system like SCOM etc.. I looking for a batch file or script outside sql which can solve this.
    Any help would be greatly appreciated.
    Thank you.

    There are two ways to do it:
    1). There is a job option wherein you can put the alert message and then in schedule option, select to alert you only when Sql Agent Services get restarted. So this way you will come to know when Sql Agent Services got restarted.
    2). From any centralize\third server apart from your database server\host, you can put a job to execute almost around every 5 minutes to check service status and then call a batch file which will call OSQL code to execute sql code for sending alert
    based on the message content you want to like below:
    Scripts below, even you can tweak more on this as per your environment requirement and even you can merge some scripts to make one out of two or similar, however keeping each separate one helps to track scripts.
    First Batch File with Name: ServiceStatusCheck.bat
    with below content
    Echo "Checking Service Status"
    :Query
    FOR /F "tokens=4 delims= " %%A IN ('SC QUERY "XXXXXXXXServiceNametobeCheckedPutHere" ^| FIND "STATE"') DO SET status=%%A
    IF "%status%"=="STOPPED" GOTO Shootout
    :Shootout
    'email for success in first attempt
    'Put path of batch file
    "D:\Script\Successemail.bat"
    Exit
    Second Batch file with below content which will call Sql file to send alert: File Name: Successemail.bat
    ECHO "Send Email Alert"
    OSQL -E -S XXXXXXXXX -i "D:\Script\Successemail.sql"
    ECHO "Done"
    Exit
    Third Sql File to send email: File Name: Successemail.sql
    Declare @bodyT varchar(200)
    Set @bodyT  =
    'Service was found in stopped status and Date & Time::'
     +replace(convert(varchar(20),GETDATE(), 102),'.','/')
     +'::'
     +convert(varchar(20),GETDATE(), 108)
    EXEC msdb.dbo.sp_send_dbmail
        @profile_name='Profilename',
        @recipients = '[email protected]',
        @body  = @bodyT,
        @subject = 'Service was found in stopped status, Check Details!!'
    GO
    Santosh Singh

  • Email alert if SQL Server Services stop abruptly

    Hi,
    I am a SQL Server DBA and I am currently working on setting up email alerts in case if SQL Server services stop abruptly.I have currently written a VB script which runs every 1 hr and checks if a SQL Server Service is running or not. This VB Script runs
    with the help of Windows Task Scheduler.In case if a SQL Server service has stopped, this VB script immediately sends an email via. SMTP Server.
    Please let me know if this is a good solution or is there any other better solution or is there any feature available in SQL/windows using which the same can be achieved. 
    Environment:
    SQL 2008 R2
    OS: Windows Server 2008
    Thanks a lot in advance :)
    Regards,
    Tauhid S Shaikh 

    Hi Tauhid,
    I do have same requirement, please could you share the code.
    Regards
    Siraj Ahmed  

  • Email for overrunning jobs for SQL Server

    Dear all,
    I'm trying to find out if there is a way within sql server or via script of emailing when a particular job or jobs has over run please?
    Thank you in advance

    SELECT 
        [sJOB].[name] AS [JobName]
        , CASE 
            WHEN [sJOBH].[run_date] IS NULL OR [sJOBH].[run_time] IS NULL THEN NULL
            ELSE CAST(
                    CAST([sJOBH].[run_date] AS CHAR(8))
                    + ' ' 
                    + STUFF(
                        STUFF(RIGHT('000000' + CAST([sJOBH].[run_time] AS VARCHAR(6)),  6)
                            , 3, 0, ':')
                        , 6, 0, ':')
                    AS DATETIME)
          END AS [LastRunDateTime]
        , CASE [sJOBH].[run_status]
            WHEN 0 THEN 'Failed'
            WHEN 1 THEN 'Succeeded'
            WHEN 2 THEN 'Retry'
            WHEN 3 THEN 'Canceled'
            WHEN 4 THEN 'Running' -- In Progress
          END AS [LastRunStatus]
        , STUFF(
                STUFF(RIGHT('000000' + CAST([sJOBH].[run_duration] AS VARCHAR(6)),  6)
                    , 3, 0, ':')
                , 6, 0, ':') 
            AS [LastRunDuration (HH:MM:SS)]
          , CASE [sJOBSCH].[NextRunDate]
            WHEN 0 THEN NULL
            ELSE CAST(
                    CAST([sJOBSCH].[NextRunDate] AS CHAR(8))
                    + ' ' 
                    + STUFF(
                        STUFF(RIGHT('000000' + CAST([sJOBSCH].[NextRunTime] AS VARCHAR(6)),  6)
                            , 3, 0, ':')
                        , 6, 0, ':')
                    AS DATETIME)
          END AS [NextRunDateTime]
    FROM 
        [msdb].[dbo].[sysjobs] AS [sJOB]
        LEFT JOIN (
                    SELECT
                        [job_id]
                        , MIN([next_run_date]) AS [NextRunDate]
                        , MIN([next_run_time]) AS [NextRunTime]
                    FROM [msdb].[dbo].[sysjobschedules]
                    GROUP BY [job_id]
                ) AS [sJOBSCH]
            ON [sJOB].[job_id] = [sJOBSCH].[job_id]
        LEFT JOIN (
                    SELECT 
                        [job_id]
                        , [run_date]
                        , [run_time]
                        , [run_status]
                        , [run_duration]
                        , [message]
                        , ROW_NUMBER() OVER (
                                                PARTITION BY [job_id] 
                                                ORDER BY [run_date] DESC, [run_time] DESC
                          ) AS RowNumber
                    FROM [msdb].[dbo].[sysjobhistory]
                    WHERE [step_id] = 0
                ) AS [sJOBH]
            ON [sJOB].[job_id] = [sJOBH].[job_id]
            AND [sJOBH].[RowNumber] = 1
    ORDER BY [LastRunDateTime] desc,
             [LastRunDuration (HH:MM:SS)] DESC
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • Can SQL Server Express Send Emails?

    I am fiddling around with one of my SQL Server Express instances, and I'm trying to get it to send me an email.  I just read these links.
    http://execsql.org/configure-send-database-email-sql-server-2012-express-edition
    http://www.databasejournal.com/features/mssql/article.php/3626056/Database-Mail-in-SQL-Server-2005.htm
    I followed all the steps there, and now, as I'm trying to send myself an email, I get this message.
    The mail could not be sent to the recipients because of the mail server failure. Exception Message: Could not connect to mail server.
    When I run this:
    SELECT * FROM msdb.dbo.sysmail_event_log;
    I see this:
    description
    The mail could not be sent to the recipients because of the mail server failure. (Sending Mail using Account 1 (2015-01-21T14:25:36). Exception Message: Could not connect to mail server. (The requested name is valid, but no data of the requested type was found).
    Any idea what's wrong?  Can SQL Server Express even send emails???
    Knowledge is the only thing that I can give you, and still retain, and we are both better off for it.

    Hello,
    You can make use of CLR Integration for sending email from SQL Server Express.
    http://www.sqlservercentral.com/articles/SQL+Server+Express/71341/
    http://www.vnypatel.com/sending-emails-with-clr-sql-server-express-editions
    SQL Server Express does not support database mail.
    https://msdn.microsoft.com/en-us/library/cc645993.aspx
    Hope this helps.
    Regards,
    Alberto Morillo
    SQLCoffee.com

  • Can SQL Server Express Send an Email When an SProc Finishes?

    I looked online for an answer to this; I didn't find anything definitive.  I'm wondering if I can get my SQL Server Express to send an email as soon as an SProc runs.  I know a more robust version of SQL Server can do it, but I don't know if the
    express version can do it.  If it can be done, can you please show me how to set it up, step by step.
    Thanks everyone!!
    Knowledge is the only thing that I can give you, and still retain, and we are both better off for it.

    if I can get my SQL Server Express to send an email as soon as an SProc runs.  I
    The SQL Server Express Edition don't support Database E-Mail feature; see
    Features Supported by the Editions of SQL Server 2012; so you can't send an e-mail.
    Olaf Helper
    [ Blog] [ Xing] [ MVP]

  • Help to resolve error in sending database email from SQL Server 2012.

    Please help to resolve error in sending email from SQL Server 2012.
    SQL Instance Version:
    Microsoft SQL Server 2012 (SP1) - 11.0.3449.0 (X64) 
    Jun 29 2014 23:15:18 
    Copyright (c) Microsoft Corporation
    Enterprise Edition: Core-based Licensing (64-bit) on Windows NT 6.3 <X64> (Build 9600: )
    Error Message: Error MeThe mail could not be sent to the recipients because of the mail server failure. (Sending Mail using Account 1 (2015-01-15T19:48:25). Exception Message:
    Cannot send mails to mail server. (The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1 Client was not authenticated).)

    The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1
    Client was not authenticated).
    I think the error message is pretty clear, you have to setup authentication for the SMTP connection in Database Mail, see
    Database Mail Configuration Objects
    Olaf Helper
    [ Blog] [ Xing] [ MVP]

  • SQL server 2012 sent job failure email when the job ran successfully

    This week we received emails from one of our productions servers indicating jobs failed. But after I checked and found they actually ran successfully.
    I was thinking this might came from some internal sql server agent errors. After I restarted SQL servr agent, I still get this false emails.
    Would like to ask help in this forum? Any ideas and suggestions will be welcomed!

    Do you use db email feature? Perhaps it is just set to send the email but mistake put into the successful step completion?
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • How to automate sql server querry and output to send via email alerts

    Hi,
    I have MS SQL 2005 server. Daily i m running sql querry at 10:30 pm. i want to automate this process & output need to send via email. Please suggest what are the options availble.
    Thanks in advance
    ...Umesh

    Create a job and put the query in , then schedule it... You can email an output by using data base email feature
    EXEC msdb.dbo.sp_send_dbmail 
         @profile_name = 'Admin', 
         @recipients = '[email protected]', 
         @query = 'SELECT COUNT(*) FROM AdventureWorks.Person.Address', 
         @subject = 'Error Log Count', 
         @attach_query_result_as_file = 1 ;
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • Email Should Receive Whenever SQL Server is Stopped.

    Hi SQL Experts,
    I have a requirement like "Email Should Receive Whenever SQL Server is Stopped", so that i can reduce the downtime or escalations.
    SQL Server Version: 2012
    Windows Server Version: 2012
    Regards
    Siraj Ahmed

    You need to do this outside of SQL server. You need some monitoring tools or you need to develop one which frequently checks SQL Server Services
    check this thread
    https://social.msdn.microsoft.com/forums/sqlserver/en-US/44eb704f-a0bb-4ceb-8470-60b2ddb0b3c6/how-to-get-an-email-notification-when-sql-server-stop
    Regards, Ashwin Menon My Blog - http:\\sqllearnings.com

  • SSRS report through data subscription - Connect to 2 different SQL server DB for excel attachment in EMail Deliery

    I need to connect to 2 different SQL server without creating linked server for generating report. Is it possible in SSRS 2008 report service?

    Yes possible
    You would just required created two data sources which points to both your SQL Servers. And inside report you can create datasets based on each of these data sources to retrieve and display the data from them. In cases where you would require merging the
    data from both the systems you can use functions like Lookup, LookupSet etc. Reports created in SSRS can be rendered in a variety of formats like Excel, PDF, CSV etc
    see
    http://www.allaboutmssql.com/2013/08/ssrs-example-for-lookup-lookupset-and.html
    http://www.sqlcircuit.com/2012/03/ssrs-2008-r2-lookup-how-to-use-multiple.html
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My Wiki User Page
    My MSDN Page
    My Personal Blog
    My Facebook Page

Maybe you are looking for

  • ANN vCam AS3

    Announcing vCam AS3 for Flash. For those of you who are unfamiliar with vCam, I'll give you a brief explanation. In 2005, Sham Bhangal and Dave Dixon released the original vCam or "virtul camera" for Flash. Let's say you are working on an animation a

  • When I plug my ipod in, nothing is in my itunes library?!

    When I plug my ipod in, nothing is in my itunes library. I have been having some computer problems, but now there is nothing in my library. When I try to add a cd to my ipod it just goes straight to my library. My library is empty...HELP!!!

  • How to remove -ve sign from the deduction wagetype in payslip

    Hi Experts, Plz tell me how i can remove the -ve sign from the deduction column in the Payslip. Regards TS

  • Microsoft Office 2007 - Installation

    Hello All I would like to know what are the exact component that needs to be tested, when I install MS Office 2007. Would there any impact on BI side, I mean BEX, WAD etc.. All these tools would work as normal ?, or is there any additional patches th

  • Error [38133] : does not join to any other logical table

    Hi, Is there a way to avoid this error. We dont have the requirement to join the table with any other table. The client wants to use the OBI Answers functionality on a single table. No joins needed or wanted. Some hidden checkbox to avoid the OBI joi