Technical Article

HTML Email Using SQL

,

This would help you to send HTML email using T-SQL script, you just need to provide necessary parameters and you would have HTML email.

DECLARE @From varchar(50)
DECLARE @To varchar(50)
DECLARE @CC varchar(50)
DECLARE @Subject as varchar(200)
DECLARE @vcBody  varchar(2000)
DECLARE @CurrDate datetime
DECLARE @MailServerName VARCHAR(100)
DECLARE @BodyType varchar(100)
DECLARE @iMsg int
DECLARE @hr int
DECLARE @source varchar(255)
DECLARE @description varchar(500)
DECLARE @output varchar(1000)


SET @From = 'from@yahoo.com'
SET @To = 'to@yahoo.com'
SET @CC = 'cc@yahoo.com'
SET @MailServerName = 'IP or name of mailserver'
SET @Subject = 'Subject Line'
SET @BodyType ='HTMLBODY'
SET @vcBody = 'Hello <b>How Are You</b>'
EXEC @hr = sp_OACreate 'CDO.Message', @iMsg OUT
EXEC @hr = sp_OASetProperty @iMsg,'Configuration.fields("http://schemas.microsoft.com/cdo/configuration/sendusing").Value','2'

-- Replace MailServerName by the name or IP of your SMTP Server.
EXEC @hr = sp_OASetProperty @iMsg, 'Configuration.fields("http://schemas.microsoft.com/cdo/configuration/smtpserver").Value', @MailServerName 
EXEC @hr = sp_OAMethod @iMsg, 'Configuration.Fields.Update', null
EXEC @hr = sp_OASetProperty @iMsg, 'To', @To
EXEC @hr = sp_OASetProperty @iMsg, 'From', @From
EXEC @hr = sp_OASetProperty @iMsg, 'CC', @CC
EXEC @hr = sp_OASetProperty @iMsg, 'Subject', @Subject

-- If you are using HTML e-mail, use 'HTMLBody' instead of 'TextBody'.
EXEC @hr = sp_OASetProperty @iMsg, @BodyType , @vcBody
EXEC @hr = sp_OAMethod @iMsg, 'Send', NULL
--PRINT @hr
-- Sample error handling.
IF @hr <>0 
BEGIN
select @hr
EXEC @hr = sp_OAGetErrorInfo NULL, @source OUT, @description OUT
IF @hr = 0
BEGIN
SELECT @output = ' Source: ' + @source
PRINT @output
SELECT @output = ' Description: ' + @description
PRINT @output
END
ELSE
BEGIN
PRINT ' sp_OAGetErrorInfo failed.'
RETURN
END
END
-- Do some error handling after each step if you need to.
-- Clean up the objects created.
EXEC @hr = sp_OADestroy @iMsg

Rate

1 (1)

You rated this post out of 5. Change rating

Share

Share

Rate

1 (1)

You rated this post out of 5. Change rating