如何建立SQL Server資料庫郵件

來源:互聯網
上載者:User

USE msdb
GO

DECLARE @ProfileName VARCHAR(255)
DECLARE @AccountName VARCHAR(255)
DECLARE @SMTPAddress VARCHAR(255)
DECLARE @EmailAddress VARCHAR(128)
DECLARE @DisplayUser VARCHAR(128)

SET @ProfileName = 'DBMailProfile';
SET @AccountName = 'DBMailAccount';
SET @SMTPAddress = 'mail.yoursmtpserver.com';
SET @EmailAddress = 'DBMail@yoursmtpserver.com';
SET @DisplayUser = 'The Mail Man';

-- Deleting Profile Account, if exists Profile Account
IF EXISTS ( SELECT  1
            FROM    msdb.dbo.sysmail_profileaccount pa
                    JOIN msdb.dbo.sysmail_profile p ON pa.profile_id = p.profile_id
                    JOIN msdb.dbo.sysmail_account a ON pa.account_id = a.account_id
            WHERE   p.name = @ProfileName
                    AND a.name = @AccountName ) 
    BEGIN        
        EXECUTE sysmail_delete_profileaccount_sp @profile_name = @ProfileName,
            @account_name = @AccountName
    END

-- Deleting Profile, if exists Profile
IF EXISTS ( SELECT  1
            FROM    msdb.dbo.sysmail_profile p
            WHERE   p.name = @ProfileName ) 
    BEGIN   
        EXECUTE sysmail_delete_profile_sp @profile_name = @ProfileName
    END

-- Deleting Account, if exists Account
IF EXISTS ( SELECT  1
            FROM    msdb.dbo.sysmail_account a
            WHERE   a.name = @AccountName ) 
    BEGIN   
        EXECUTE sysmail_delete_account_sp @account_name = @AccountName
    END

-- Create Account
EXECUTE msdb.dbo.sysmail_add_account_sp @account_name = @AccountName,
    @email_address = @EmailAddress, @display_name = @DisplayUser,
    @mailserver_name = @SMTPAddress

-- Create Profile
EXECUTE msdb.dbo.sysmail_add_profile_sp @profile_name = @ProfileName 

-- Create Profile Account
EXECUTE msdb.dbo.sysmail_add_profileaccount_sp @profile_name = @ProfileName,
    @account_name = @AccountName, @sequence_number = 1;

--Turn On Database Mail XPs, if the configuration is turn off
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Database Mail XPs', 1;
GO
RECONFIGURE
GO

-- Test send email
EXEC msdb.dbo.sp_send_dbmail @recipients = 'test@gmail.cn',
    @body = 'Test Email Body', @subject = 'Test Email Subject',
    @profile_name = 'DBMailProfile'

-- Search the result that send email
SELECT * FROM msdb.dbo.sysmail_allitems

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.