如何用SQL Server来自动发送邮件
前提: SQL Server所在的主机必须能上网……
如果有什么意外发不出去, 请先检查用 Foxmail 客户端软件能不能发出去。
1. 准备一个允许 'SMTP' 邮件协议的邮箱, 163或者qq邮箱等都可以。
下面以qq为例。
2. 在 SQL Server 中设置:
[sql] EXEC sp_configure 'show advanced options',1 RECONFIGURE WITH OVERRIDE GO EXEC sp_configure 'database mail xps',1 RECONFIGURE WITH OVERRIDE GO
--2.创建邮件帐户信息
EXEC msdb..sysmail_add_account_sp
@ACCOUNT_NAME = 'ETLErrorMailLog', -- 邮件帐户名称
@EMAIL_ADDRESS = '223@qq.com', -- 发件人邮件地址
@DISPLAY_NAME = '系统管理员', -- 发件人姓名
@REPLYTO_ADDRESS = NULL,
@DESCRIPTION = NULL,
@MAILSERVER_NAME = 'smtp.qq.com', -- 邮件服务器地址
@MAILSERVER_TYPE = 'SMTP', -- 邮件协议
@PORT = 25, -- 邮件服务器端口
@USERNAME = '223@qq.com', -- 用户名
@PASSWORD = ' ', -- 密码
@USE_DEFAULT_CREDENTIALS = 0,
@ENABLE_SSL = 0,
@ACCOUNT_ID = NULL
GO
--3.
数据库配置文件
IF EXISTS(
SELECT NAME
FROM msdb..sysmail_profile
WHERE NAME = N'ETLErrorProfileLog'
)
BEGIN
EXEC msdb..sysmail_delete_profile_sp @profile_name = 'ETLErrorProfileLog'
END
EXEC msdb..sysmail_add_profile_sp
@profile_name = 'ETLErrorProfileLog', -- profile 名称
@description = '数据库邮件配置文件', -- profile 描述
@profile_id = NULL
GO
--4.用户和邮件配置文件相关联
EXEC msdb..sysmail_add_profileaccount_sp
@profile_name = 'ETLErrorProfileLog', -- profile 名称
@account_name = 'ETLErrorMailLog', -- account 名称
@sequence_number = 1 -- account 在 profile 中顺序
--5.发送文本测试邮件
EXEC msdb..sp_send_dbmail
@profile_name = 'ETLErrorProfileLog',
@recipients = '223@qq.com', --收件人
@subject = 'Test title this is test ',
@body = N'z中文邮件内容 中文邮件内容'
GO