如何:建立 Database Mail 私人設定檔 (Transact-SQL)

使用「Database Mail 組態精靈」或 Database Mail 預存程序可建立私人的 Database Mail 設定檔,以便傳送 Simple Mail Transfer Protocol (SMTP) 郵件。使用者或角色可以使用私人設定檔。為角色授與設定檔的存取權限時,會建立能夠更輕鬆維護的架構。

若要使用 Transact-SQL 建立 Database Mail 設定檔

  1. 替該設定檔建立一或多個 Database Mail 帳戶。如需有關建立 Database Mail 帳戶的詳細資訊,請參閱<如何:建立 Database Mai 帳戶 (Transact-SQL)>。

  2. 執行預存程序 msdb.dbo.sysmail_add_profile_sp 以建立設定檔,指定:

    • 要建立之設定檔的名稱。

    • 設定檔的選擇性描述。

  3. 對於每個帳戶,執行 msdb.dbo.sysmail_add_profileaccount_sp 以將帳戶加入設定檔。

  4. 對於要使用此設定檔傳送郵件的每一個資料庫角色或使用者,執行 msdb.sysmail_add_principalprofile_sp 授與設定檔的存取權。

範例

以下範例會建立 Database Mail 帳戶與 Database Mail 設定檔。此範例會新增該帳戶到設定檔,並將設定檔的存取權授與 msdb 資料庫中的 DBMailUsers 資料庫角色。

-- Create a Database Mail account
EXECUTE msdb.dbo.sysmail_add_account_sp
    @account_name = 'AdventureWorks Administrator',
    @description = 'Mail account for administrative e-mail.',
    @email_address = 'dba@Adventure-Works.com',
    @replyto_address = 'danw@Adventure-Works.com',
    @display_name = 'AdventureWorks Automated Mailer',
    @mailserver_name = 'smtp.Adventure-Works.com' ;

-- Create a Database Mail profile
EXECUTE msdb.dbo.sysmail_add_profile_sp
    @profile_name = 'AdventureWorks Administrator Profile',
    @description = 'Profile used for administrative mail.' ;

-- Add the account to the profile
EXECUTE msdb.dbo.sysmail_add_profileaccount_sp
    @profile_name = 'AdventureWorks Administrator Profile',
    @account_name = 'AdventureWorks Administrator',
    @sequence_number =1 ;

-- Grant access to the profile to the DBMailUsers role
EXECUTE msdb.dbo.sysmail_add_principalprofile_sp
    @profile_name = 'AdventureWorks Administrator Profile',
    @principal_name = 'ApplicationUser',
    @is_default = 1 ;