views:

92

answers:

3

In my stored procedure, I send emails with sp_send_email. My stored procedure will be run in different environments; some will have emailing enabled, some won't.

If I run sp_send_email without it being enabled, I (quite rightly) get this error message

SQL Server blocked access to procedure 'dbo.sp_send_dbmail' of component 'Database Mail XPs' because this component is turned off as part of the security configuration for this server.

I want to check whether emailing is enabled first, so I can avoid the error by doing the following:

IF @is_enabled
BEGIN
    EXEC sp_send_email ...
END

How do I correctly set @is_enabled?

A: 

BOL says:

To send Database mail, users must be a user in the msdb database and a member of the DatabaseMailUserRole database role in the msdb database. To add msdb users or groups to this role use SQL Server Management Studio or execute the following statement for the user or role that needs to send Database Mail.

So, you can give to user the appropriate role:

EXEC msdb.dbo.sp_addrolemember @rolename = 'DatabaseMailUserRole'
    ,@membername = '<user or role name>'; GO
Alex_L
That's not what I asked. I want to check if it is enabled, and only attempt to send if it is. I don't need to know how to set it up, as it will be done already on the relevant servers.
harriyott
but it is the first part of the solution.using SELECT CURRENT_USER you can get current user name, and then check the role of this user using sp_helpuser. If he has role DatabaseMailUserRole - this user can send emails.
Alex_L
@Alex_L: this is not an answer to the question at all.
gbn
Yes, I see now.
Alex_L
A: 
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Database Mail XPs';
GO

The sp_send_mail falls under the 'Database Mail XPs' umbrella. You application may not have the rights to run sp_configure and RECONFIGURE, so in the end you may be better if you simply try to invoke the sp_send_mail and handle the error.

Remus Rusanu
+2  A: 

You can query sys.configurations

IF EXISTS (SELECT *
       FROM sys.configurations
       WHERE name = 'Database Mail XPs' AND value_in_use = 1)
    PRINT 'enabled'
ELSE
    PRINT 'no luck'

The downside is that it may not be visible to non-sysadmin users because of "MetaData Visibility"

gbn
+1 yes, actually sys.configurations is better than sp_configure output
Remus Rusanu
BTW the sysadmin issue can be addressed by code signing the check.
Remus Rusanu
Or off-load to a start-up procedure, that sets a flag in a user table in a user database. The code signing idea is useful though.
gbn
sys.configurations actually is visible to the public role so it shouldn't require anything special under normal conditions.
Remus Rusanu
@Remus: thanks. I haven't tried it but this is good to know.
gbn