Showing posts with label Databse mail. Show all posts
Showing posts with label Databse mail. Show all posts

21 March 2020

How to configure database mail in sql server 2016 and above

GO
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Database Mail XPs', 1;
GO
RECONFIGURE
GO

EXECUTE msdb.dbo.sysmail_add_profile_sp 
    @profile_name = 'TestDB_Mail', 
    @description = 'Profile used for sending outgoing notifications using Gmail.' ; 
GO

-- Grant access to the profile to the DBMailUsers role  
EXECUTE msdb.dbo.sysmail_add_principalprofile_sp 
    @profile_name = 'TestDB_Mail', 
    @principal_name = 'public', 
    @is_default = 1 ;
GO

-- Create a Database Mail account  
EXECUTE msdb.dbo.sysmail_add_account_sp 
    @account_name = 'Gmail', 
    @description = 'Test mail.', 
    @email_address = 'XXXXXXXX', 
    @display_name = 'Automated Mailer', 
    @mailserver_name = 'smtp.gmail.com',
    @port = 25,
    @enable_ssl = 1,
    @username = 'XXXXXXX',
    @password = 'XXXXXX' ; 
GO

EXECUTE msdb.dbo.sysmail_add_profileaccount_sp 
    @profile_name = 'TestDB_Mail', 
    @account_name = 'Gmail', 
    @sequence_number =1 ; 
GO

--To Send email

EXEC msdb.dbo.sp_send_dbmail
     @profile_name = 'TestDB_Mail',
     @recipients = 'XXXXXX',
     @body = 'The database mail configuration was completed successfully1.',
     @subject = 'Automated Success Message';
GO

----Rrecall Everything

EXECUTE msdb.dbo.sysmail_delete_profileaccount_sp @profile_name = 'TestDB_Mail'
EXECUTE msdb.dbo.sysmail_delete_principalprofile_sp @profile_name = 'TestDB_Mail'
EXECUTE msdb.dbo.sysmail_delete_account_sp @account_name = 'Gmail'
EXECUTE msdb.dbo.sysmail_delete_profile_sp @profile_name = 'TestDB_Mail'
GO