Learn more about SQL Server tools

mssqltips logo
 

Tutorials          DBA          Dev          BI          Career          Categories          Webcasts          Whitepapers          Today's Tip          Join

Tutorials      DBA      Dev      BI      Categories      Webcasts

DBA    Dev    BI    Categories

 
Simplify SQL Server Database Development     ====>    Webcast Registration
 

Setting up Database Mail for SQL Server


By:   |   Read Comments (26)   |   Related Tips: 1 | 2 | 3 | More > Database Mail

Problem

Many things have changed starting with SQL Server 2005 and one of these changes is the replacement of SQL Mail with Database Mail.  This is a good thing, because SQL Mail relied on having a MAPI mail client installed such as Outlook in order for it to work.  With SQL Server 2005 and later this has changed and now the mail services use an SMTP server to send out emails which makes it a whole lot easier to setup and maintain.  So how do you setup Database Mail for SQL Server 2005 and later?

Solution

There are two ways that you can setup Database Mail, either by using the stored procedures that are included with SQL Server or by using SQL Server Management Studio.  For this exercise we will walk through how to setup Database Mail by using the GUI.

To setup Database Mail, connect to your server and expand the Management node of the tree and then right click on "Database Mail".

configure database mail from ssms

Then select "Configure Database Mail' and you will get the following welcome screen and the click "Next".

database mail wizard

The following screen will appear and select "Set up Database Mail by performing..." and click "Next".

database mail select configuration task

If Database Mail has not been enabled, you will get this following screen. Just click "Yes" to enable it.  If it has already been enabled this screen will not appear.

enable database mail features

Enter in a name for the Profile and also a description and click "Add..."

database mail new profile

The following screen will appear.  Fill out the details for your mail account that will be used to send out email from SQL Server.  When you are done click "OK".

database mail new database mail account

After you click "OK" you will be brought back to this screen and the SMTP details will now show for the account you just setup.  Click "Next" to continue.

database mail new profile

On the next screen you will see the name of the profile that you just setup.  Click on the checkbox to allow this to be a Public profile and also select "Yes" for the default profile and then click "Next".

database mail manage profile security

The following screen has some additional parameters that can be set to control how mail is sent.  You can make changes or leave the defaults.  When you are done click "Next".

database mail configure system parameters

A summary screen will appear that shows you all of the options that were selected.  If everything is correct click "Finish" or click "Back" to go back and make changes.

database mail complete the wizard

When you click "'Finish" the next screen will appear that shows you the status of installing Database Mail. When this has finished just click "Close" to close this screen.

database mail configuration success

To test Database Mail, right click on Database Mail and select "Send Test E-Mail".

database mail send test email

Fill in a "To:" email address and change the body of the email if you want and then click "Send Test E-Mail".

database mail send test email

After you have sent the email you will get this message box to confirm if the email was received or not.  If it was you can click "OK" to close the screen or click "Troubleshoot" which will launch the help information to see what the issue may be and how it can be resolved.

database mail check test email send

That's all there is to it.  As I mentioned before this can also be setup by using stored procedures. To look at this approach take a look at this article Database Mail in SQL Server.

Next Steps
  • Setting up Database Mail is not that complicated and it is much easier then SQL Mail. Take the time to see how this new approach to mail can work in your environment
  • After you setup Database Mail don't forget to setup your operators, alerts and SQL Agent alert settings


Last Update:

First Published: 2006-11-09


next webcast button


next tip button



About the author





Post a comment or let the author know this tip helped.

All comments are reviewed, so stay on subject or we may delete your comment. Note: your email address is not published. Required fields are marked with an asterisk (*).

*Name    *Email    Email me updates 


Signup for our newsletter
 I agree by submitting my data to receive communications, account updates and/or special offers about SQL Server from MSSQLTips and/or its Sponsors. I have read the privacy statement and understand I may unsubscribe at any time.



    



Tuesday, September 11, 2018 - 7:24:35 AM - Greg Robidoux Back To Top

Hi Singh,

It looks like a permission issue.  Can you try with another mail account and see if that works?

-Greg


Tuesday, September 11, 2018 - 6:37:54 AM - Singh Back To Top

Hi Greg,

I followed all the steps but I'm not able to send any email from database... How do I know if the SMTP has picked my email or not? Because if I drop a text file in SMTP pick up folder it works fine(http://www.vsysad.com/2012/04/setup-and-configure-smtp-server-on-windows-server-2008-r2/) but on database it fails.

Or Is there any permission issue?

Error message: The mail could not be sent to the recipients because of the mail server failure. (Sending Mail using Account 3 (2018-09-11T06:28:55). Exception Message: Cannot send mails to mail server. (Failure sending mail.).
)

OR

The mail could not be sent to the recipients because of the mail server failure. (Sending Mail using Account 2 (2018-09-10T11:56:38). Exception Message: Could not connect to mail server. (No connection could be made because the target machine actively refused it IPAddress:25).
)

Thanks


Tuesday, June 05, 2018 - 11:05:19 AM - Perry Back To Top

Hi Greg,

 

Yes the simple test works. But the problem actually is when I am using a variable for 'like' comparison. 

 

declare @test varchar(20) = '%Perry%';
declare @query varchar(max);

 

set @query = 'SELECT id, name from master.sys.objects where name like @test'

this errors out

set @query = 'SELECT id, name from master.sys.objects where name like ' + @test

this errors out too

so what I did was add another single quote using ascii code.

set @query = 'SELECT id, name from master.sys.objects where name like ' + char(39) + @test + char(39)

and this now works.

 

Thanks,

Perry


Tuesday, June 05, 2018 - 8:00:57 AM - Greg Robidoux Back To Top

Perry,

Did you try to just do a simple test like the example I provided?  If so, did that work for you?

-Greg


Monday, June 04, 2018 - 7:02:15 PM - Perry Back To Top

Hi Greg,

 

Tried that but still get an error. 

 

Thanks for the help.


Monday, June 04, 2018 - 3:18:38 PM - Greg Robidoux Back To Top

Hi Perry,

did you save the query into a variable and then use that to send the email?  Something like this.

 

declare @test varchar(max) = 'SELECT top 10 * from '
declare @test2 varchar(max) = 'master.sys.objects'
declare @test3 varchar(max)
set @test3 = @test + @test2

EXEC msdb.dbo.sp_send_dbmail
    @profile_name = 'test',  
    @recipients = '[email protected]',  
    @query = @test3,
    @subject = 'test'


Monday, June 04, 2018 - 11:36:05 AM - Perry Back To Top

Hi Greg,

Can you help me with this SQL? This SQL works in the visual studio and also in server management studio but when I am setting it via the database mail I am getting error.

 

select @qry='

SELECT DISTINCT ABP.ProjectID, ABP.ProjectNumber, ABP.ProjectName, 

ABP.ProjectJobSiteAddress1, ABP.ProjectJobSiteAddress2, 

ABP.ProjectJobSiteCity, ABP.ProjectJobSiteState, 

ABP.ProjectJobSiteZipCode, ABP.ProjectLocation, ABP.ProjectJobCountyID, 

convert(varchar, ABP.FirstAdvBidDate, 101) as FirstAdvBidDate, 

convert(varchar, ABP.ContractAwardDate, 101) as ContractAwardDate, 

convert(varchar, ABP.ProjectStartDate, 101) as ProjectStartDate, 

convert(varchar, ABP.ProjectEndDate, 101) as ProjectEndDate, 

ABP.ContractorLicenseNumber, ABP.ContractAwardAmount, ABP.AwardingBodyID, 

ABP.ContractNumber , ABA.AwardingBodyName 

FROM AwardingBody_Projects ABP INNER JOIN AwardingBody_Agency ABA 

ON ABA.AwardingBodyName like ' + @AwardingBodyName 

+ ' AND ABA.AwardingBodyID = ABP.AwardingBodyID 

INNER JOIN AwardingBody_ProjectContractors ABPC 

ON (ABPC.Status = ' + @status1 + ' or ABPC.Status = ' + @status2 + ' ) 

AND ABPC.AwardingBodyID = ABP.AwardingBodyID 

AND ABPC.ContractNumber = ABP.ContractNumber 

AND ABPC.ProjectId = ABP.ProjectId 

AND ABPC.ProjectNumber = ABP.ProjectNumber  

AND ABPC.ContractorTypeID = ' + @ContractorTypeId 

+ ' AND ABPC.DeleteStatus = ' + @deleteStatus 

+ ' AND (ABPC.PWCRNumber IN (

SELECT CONVERT(varchar,PWCR.REGISTRATION_NUMBER) 

FROM PWCR_Contractor_vw PWCR 

WHERE  PWCR.LEGAL_NAME like ' + @ContractorName  

+ ' )  

OR ABPC.ContractorLicenseNumber IN (

SELECT CR.CON_ID 

FROM Contractor_ref CR 

WHERE  CR.CON_COMPANY_NAME like ' + @ContractorName 

+ ' ) 

WHERE ABP.ProjectName like ' + @ProjectName  

+ ' ORDER BY ABP.ProjectName'

 

This is the error I am getting.

Msg 22050, Level 16, State 1, Line 0

Error formatting query, probably invalid parameters

Msg 14661, Level 16, State 1, Procedure sp_send_dbmail, Line 504

Query execution failed: Msg 156, Level 15, State 1, Server OAK01SQL, Line 13

Incorrect syntax near the keyword 'AND'.

Msg 102, Level 15, State 1, Server OAK01SQL, Line 23

Incorrect syntax near ')'.

Msg 102, Level 15, State 1, Server OAK01SQL, Line 27

Incorrect syntax near ')'.

 

Thank you,

Perry


Friday, June 01, 2018 - 7:46:18 AM - Greg Robidoux Back To Top

Perry,

take a look at this tip: https://www.mssqltips.com/sqlservertip/2347/send-email-in-a-tabular-format-using-sql-server-database-mail/

-Greg


Thursday, May 31, 2018 - 5:42:48 PM - Perry Back To Top

NVM, I changed my separator to TAB and it is now displayed properly in the CSV file. Thank you.


Thursday, May 31, 2018 - 5:33:40 PM - Perry Back To Top

Hi Greg

Finally we were able to resolve the missing stored procedure. It was created on my different account.

 

I was able to send a sample query of a table using the separator ','. The CSV attachment is like a text file pasted into the CSV and unreadable. Is there a way to format the query result into columns just like excel?

Thank you,

Perry


Thursday, May 31, 2018 - 8:11:28 AM - Greg Robidoux Back To Top

Hi Perry,

not sure what that is not working.  Here is a link to an article that shows to do what you say: https://stackoverflow.com/questions/11666277/how-to-grant-sendmail-permission-to-sql-server-user

The one thing that is weird is that it says the stored procedure cannot be found.  I would think you would get a permissions error not a problem with the procedure not being found.  Can you check with your admin to make sure the procedure exists and it wasn't renamed.

-Greg


Wednesday, May 30, 2018 - 12:36:56 PM - Perry Back To Top

Hi Greg,

Great post. But how do I add database mail on a specific database/view? The admin setup database mail and added me to "DatabaseMailUserRole".

When I tried to use the "msdb.dbo.sp_send_dbmail" in a query, it says it cannot find the stored procedure.

Thank you.


Thursday, January 11, 2018 - 4:25:26 PM - Greg Robidoux Back To Top

Hi Clemens,

to be honest I have no idea why one would work and the other does not work. My guess is that it has something to do with the way Microsoft has setup those mail services.

-Greg


Wednesday, January 10, 2018 - 12:29:49 PM - clemens Back To Top

 Thanks finaly it functions.

But:

It works with a free live.com email adress but i didn't succseed with our company office365 account

Do you have an idee what whe do wrong?

Thanks

C.

 


Thursday, January 04, 2018 - 8:58:40 PM - Natanael Back To Top

Funciono correctamente!!!

It worked correctly!!!


Thursday, December 14, 2017 - 9:54:43 AM - Susan Qi Back To Top

Excellent post, it works for sql server 2017. Thank you.


Thursday, August 31, 2017 - 12:25:21 PM - Greg Robidoux Back To Top

What version and edition of SQL Server are you using?


Thursday, August 31, 2017 - 10:38:07 AM - Haim Rubin Back To Top

Hi

Is the mailer is not installed on the machine. How do I add it

Thanks

 

 


Wednesday, June 24, 2015 - 12:33:52 PM - margarett hance Back To Top

Great TIp - easy to follow  Database EMAIL


Friday, January 30, 2015 - 11:32:59 AM - Andy Bartholomew Back To Top

This was great, thanks!


Friday, April 12, 2013 - 7:02:24 AM - Dinesh Vishe Back To Top

hi,

 

select 

 

*from msdb.dbo.sysmail_profile => Profile creation details

 

select 

 

*from msdb.dbo.

sysmail_faileditems=> failed mail

 

 

select

 

 

*from msdb.dbo.sysmail_profileaccount => Profile Modify user

select

 

 

*from msdb.dbo.

 

sysmail_sentitems => send mai details

 

 

select

 

*from msdb.dbo.

sysmail_event_log => All event details.

 


Tuesday, April 02, 2013 - 5:57:31 AM - suresh y Back To Top

HI GREG,

HOW R U 

I AM SURESH.  WE ARE GIVING BEAUTIFUL TIPS FROM U R MSSQLTIPS. I AM FOLLOWING DAILY  YOUR BLOG PLEASE SOME MORE

SUGGESTIONS.  I AM DOUBTFUL "SQL MEMORY ARCHITECTURE'' I AM ASKED SO MANY AUTHORS BUT I AM NOT GETTING FULL FLDGE

KNOWLDGE ABT THAT TOPIC. LOT OF CONFUSION 32 BIT ARCHITECTURE AND 64 BIT ARCHITECTUR, AWE TOPIC ,BUFFERPOOL AND

DATA CACHE,CHECHPOINT,DIRTY PAGES

 


Friday, November 09, 2012 - 1:03:12 PM - Jacz Down Back To Top

Where accept any certificate as they use a self-signed?

Sorry for my English..

 

 


Friday, October 26, 2012 - 12:37:39 PM - anwar ahmed Back To Top

Great help


Tuesday, August 21, 2012 - 1:25:46 PM - sai Back To Top

*Very good article


Monday, July 02, 2012 - 3:43:28 AM - john the rule Back To Top

Very good guidelines with  wizard


Learn more about SQL Server tools