如何:建立 Database Mail 公用設定檔 (Transact-SQL)

使用「Database Mail 組態精靈」或 Database Mail 預存程序來建立公用的 Database Mail 設定檔。公用設定檔可以讓任何可存取 msdb 資料庫的使用者使用該設定檔來傳送電子郵件。

若要使用 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,以 'public' 作為 @principal_name,或是以 0 作為 @principal_id

範例

以下範例會建立 Database Mail 帳戶與 Database Mail 設定檔。此範例會將該帳戶加入設定檔中,並將設定檔的存取權授與 msdb 資料庫中的所有使用者。

-- Create a Database Mail account

EXECUTE msdb.dbo.sysmail_add_account_sp
    @account_name = 'AdventureWorks Public Account',
    @description = 'Mail account for use by all database users.',
    @email_address = 'db_users@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 Public Profile',
    @description = 'Profile used for administrative mail.' ;

-- Add the account to the profile

EXECUTE msdb.dbo.sysmail_add_profileaccount_sp
    @profile_name = 'AdventureWorks Public Profile',
    @account_name = 'AdventureWorks Public Account',
    @sequence_number =1 ;

-- Grant access to the profile to all users in the msdb database

EXECUTE msdb.dbo.sysmail_add_principalprofile_sp
    @profile_name = 'AdventureWorks Public Profile',
    @principal_name = 'public',
    @is_default = 1 ;