在 SMO 中,Database Mail 子系統是由 SqlMail 屬性所參考 Mail 的物件表示。 藉由使用 SMO SqlMail 物件,您可以設定 Database Mail 子系統,以及管理配置檔和郵件帳戶。 SMO SqlMail 對象屬於 Server 物件,這表示郵件帳戶的範圍位於伺服器層級。
範例
若要使用提供的任何程式代碼範例,您必須選擇程式設計環境、程式設計範本,以及用來建立應用程式的程式設計語言。 如需詳細資訊,請參閱 在 Visual Studio .NET 中建立 Visual Basic SMO 專案 或 在 Visual Studio .NET 中建立 Visual C# SMO 專案。
對於使用 SQL Server Database Mail 的程式,您必須包含 Imports 語句來限定 Mail 命名空間。 將 語句插入其他 Imports 語句之後,在應用程式中的任何宣告之前,例如:
Imports Microsoft.SqlServer.Management.Smo
Imports Microsoft.SqlServer.Management.Common
Imports Microsoft.SqlServer.Management.Smo.Mail
使用 Visual Basic 建立 Database Mail 帳戶
此程式代碼範例示範如何在 SMO 中建立電子郵件帳戶。 Database Mail 是由 物件表示,SqlMail並由 對象的 屬性Server所參考Mail。 SMO 可用來以程式設計方式設定 Database Mail,但無法用來傳送或處理已接收的電子郵件。
VB.NET
使用 Visual C 建立 Database Mail 帳戶#
此程式代碼範例示範如何在 SMO 中建立電子郵件帳戶。 Database Mail 是由 物件表示,SqlMail並由 對象的 屬性Server所參考Mail。 SMO 可用來以程式設計方式設定 Database Mail,但無法用來傳送或處理已接收的電子郵件。
{
//Connect to the local, default instance of SQL Server.
Server srv = default(Server);
srv = new Server();
//Define the Database Mail service with a SqlMail object variable
//and reference it using the Server Mail property.
SqlMail sm;
sm = srv.Mail;
//Define and create a mail account by supplying the Database Mail
//service, name, description, display name, and email address
//arguments in the constructor.
MailAccount a = default(MailAccount);
a = new MailAccount(sm, "AdventureWorks2012 Administrator", "AdventureWorks2012 Automated Mailer", "Mail account for administrative e-mail.", "dba@Adventure-Works.com");
a.Create();
}
使用 PowerShell 建立 Database Mail 帳戶
此程式代碼範例示範如何在 SMO 中建立電子郵件帳戶。 Database Mail 是由 物件表示,SqlMail並由 對象的 屬性Server所參考Mail。 SMO 可用來以程式設計方式設定 Database Mail,但無法用來傳送或處理已接收的電子郵件。
#Connect to the local, default instance of SQL Server.
#Get a server object which corresponds to the default instance
$srv = New-Object -TypeName Microsoft.SqlServer.Management.SMO.Server
#Define the Database Mail; reference it using the Server Mail property.
$sm = $srv.Mail
#Define and create a mail account by supplying the Database Mail service,
#name, description, display name, and email address arguments in the constructor.
$a = New-Object -TypeName Microsoft.SqlServer.Management.SMO.Mail.MailAccount -ArgumentList $sm, `
"Adventure Works Administrator", "Adventure Works Automated Mailer",`
"Mail account for administrative e-mail.", "dba@Adventure-Works.com"
$a.Create()