使用数据库邮件发送电子邮件

-1 sql-server database-mail

如何在 SQL Server 中使用数据库邮件?我在论坛上关注了很多文章,但我失败了很多错误。我在一本书中读到,我必须先安装 SMTP 服务器和 Microsoft Exchange,然后才能使用数据库邮件?这样对吗?

KAS*_*DBA 6

是的 SMTP 服务器最好配置数据库邮件。

限制和限制 在任何数据库中启用 SQL Server Service Broker 都需要一个数据库锁。如果在 msdb 中停用了 Service Broker,要启用数据库邮件,请首先停止 SQL Server 代理,以便 Service Broker 可以获得必要的锁。

还,

要配置数据库邮件,您必须是 sysadmin 固定服务器角色的成员。要发送数据库邮件,您必须是 msdb 数据库中 DatabaseMailUserRole 数据库角色的成员

只是为了测试,我使用下面的 gmail 服务器作为 smtp。

请阅读这篇关于如何设置的 MSDN 文章

使用 T-SQL 脚本配置数据库邮件

--Enabling Database Mail
sp_configure 'show advanced options', 1
reconfigure

--Creating a Profile
EXECUTE msdb.dbo.sysmail_add_profile_sp
@profile_name = 'SQLProfile',
@description = 'Mail Service for SQL Server’;

-- Create a Mail account for gmail. We have to use our company mail account.
EXECUTE msdb.dbo.sysmail_add_account_sp
@account_name = 'SQL_Email_Account',
@email_address = 'youremail@gmail.com',
@mailserver_name = 'smtp.gmail.com',
@port=587,
@enable_ssl=1,
@username='youremail',
@password='Emailid password'

-- Adding the account to the profile
EXECUTE msdb.dbo.sysmail_add_profileaccount_sp
@profile_name = 'SQLProfile',
@account_name = 'SQL_Email_Account',
@sequence_number =1 ;

-- Granting access to the profile to the DatabaseMailUserRole of MSDB
EXECUTE msdb.dbo.sysmail_add_principalprofile_sp
@profile_name = 'SQLProfile',
@principal_id = 0,
@is_default = 1 ;
Run Code Online (Sandbox Code Playgroud)

--发送测试邮件

EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'SQLProfile',
@recipients = 'youremailid@xxxx.com',
@body = 'Database Mail Testing...',
@subject = 'Databas Mail from SQL Server';
Run Code Online (Sandbox Code Playgroud)

--验证,检查状态栏

select * from sysmail_allitems
Run Code Online (Sandbox Code Playgroud)