这是我第一次尝试编写通过电子邮件发送给某人的存储过程。在尝试执行时,我遇到了这些错误:
Msg 102, Level 15, State 1, Procedure EmailTodaysErrors, Line 14
Incorrect syntax near '@MailServer'.
Msg 137, Level 15, State 2, Procedure EmailTodaysErrors, Line 26
Must declare the scalar variable "@mailserver".
Msg 137, Level 15, State 2, Procedure EmailTodaysErrors, Line 33
Must declare the scalar variable "@Body".
我正在使用的代码是:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE EmailTodaysErrors
@SenderName varchar(100),
@SenderAddress varchar(100),
@RecipientName varchar(100),
@RecipientAddress varchar(100),
@Subject varchar(200),
@Body varchar(8000)
@MailServer varchar(100) = 'localhost'
AS
SET NOCOUNT ON;
declare @oMail int --Object reference
declare @resultcode int
EXEC @resultcode = sp_OACreate 'CDONTS.NewMail', @oMail OUT
if @resultcode = 0
BEGIN
EXEC @resultcode = sp_OASetProperty @oMail, 'RemoteHost', @mailserver
EXEC @resultcode = sp_OASetProperty @oMail, 'FromName', @SenderName
EXEC @resultcode = sp_OASetProperty @oMail, 'FromAddress', @SenderAddress
EXEC @resultcode = sp_OASetProperty @oMail, 'From', @SenderAddress
EXEC @resultcode = sp_OASetProperty @oMail, 'To', @RecipientAddress
EXEC @resultcode = sp_OASetProperty @oMail, 'Subject', @Subject
EXEC @resultcode = sp_OASetProperty @oMail, 'Body', @Body
EXEC @resultcode = sp_OAMethod @oMail, 'Send', NULL
EXEC sp_OADestroy @oMail
END
set nocount off
GO
非常感谢任何帮助。提前谢谢。
答案 0 :(得分:11)
不要使用sp_oa_family发送邮件,已经有一个内置的SQL Server解决方案:Database Mail。只需在服务器上正确配置数据库邮件,然后调用sp_send_dbmail
。
答案 1 :(得分:11)
您在@body
行之后错过了一个逗号,这会丢失您的声明。
在此处添加:
@Body varchar(8000), -- HERE
@MailServer varchar(100) = 'localhost'
答案 2 :(得分:2)
您的参数中缺少逗号:
@Body varchar(8000), ---- HERE
@MailServer varchar(100) = 'localhost'
答案 3 :(得分:0)
通过SQL DB Mail发送邮件的SQL服务器代码
--Sending Test Mail
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'TestProfile',
@recipients = 'To Email Here',
@copy_recipients ='CC Email Here', --For CC Email if exists
@blind_copy_recipients= 'BCC Email Here', --For BCC Email if exists
@subject = 'Mail Subject Here',
@body = 'Mail Body Here',
@body_format='HTML',
@importance ='HIGH',
@file_attachments='C:\Test.pdf'; --For Attachments if exists

有关如何设置DB邮件的更多信息,请参阅链接
http://www.freshcodehub.com/Article/43/create-a-database-mail-configuration-using-t-sql-script