Sending HTML formatted email in SQL Server using the SSIS Script Task

By:   |   Comments (35)   |   Related: 1 | 2 | More > Integration Services Development


Problem

In part 1 of this tip series, I discussed using the built-in Send Mail Task which is quite simple to use and can be used in a scenario where you need to send plain text email with less development efforts. In this second tip, I am going to discuss the use of the Script Task to overcome the limitations imposed by the Send Mail Task. In this tip, I will show how you can send HTML formatted emails from SSIS using the Script Task or rather sending emails using the .Net capabilities from your SSIS package.

Solution

I will start my discussion on using the Script Task to send email (both non-HTML and HTML formatted) with an example. First I will create a database table (MailsToBeSent) which will hold the information about the emails which are to be sent by the Script Task and then insert a few records in this table. Next I will create a stored procedure to retrieve the records from the above created tables.

So here is the script for creating these database objects.

--Create a table to store mails to be sent details
CREATE TABLE MailsToBeSent
(
[MailID] INT PRIMARY KEY,
[From] VARCHAR(200),
[TO] VARCHAR(200),
[CC] VARCHAR(200),
[BCC] VARCHAR(200),
[Subject] VARCHAR(200),
[Body] VARCHAR(MAX),
[IsHTMLFormat] BIT,
[Priority] CHAR(1)
) 
GO
  
--Insert a non-HTML mail details to be sent
INSERT INTO MailsToBeSent([MailID], [From], [TO], [CC], [BCC], [Subject], [Body], [IsHTMLFormat], [Priority])
VALUES(1, '[email protected]', '[email protected]', '[email protected];[email protected]','', 
'Sending Non-HTML Mail Using Script Task', 'This Non-HTML mail has been sent using SSIS Script task.', 0, 'L')
GO  

--Insert a HTML formatted mail details to be sent
INSERT INTO MailsToBeSent([MailID], [From], [TO], [CC], [BCC], [Subject], [Body], [IsHTMLFormat], [Priority])
VALUES(2, '[email protected]', '[email protected]', '[email protected];[email protected]','', 
'Sending HTML formatted Mail Using Script Task', 
'This <strong><span style="font-size:130%;color:#006600;">HTML formatted</span></strong> 
mail has been sent using <em><span style="color:#ff6600;">SSIS Script task</span></em>.', 
1, 'H')
GO
 
--Create a procedure to retrieve all the records 
--from MailsToBeSent table to send mails
CREATE PROCEDURE GetMailsToBeSent
AS
BEGIN
SELECT [MailID], [From], [TO], [CC], [BCC], [Subject], 
[Body], [IsHTMLFormat], [Priority]
FROM MailsToBeSent
END
GO  

EXEC GetMailsToBeSent
GO 

Once you are done with the database object creation, let's move on to create a package with Script Task to send emails.

Create a new project of Integration Services type in the Business Intelligence Development Studio. Drag a Script Task from the toolbox and drop it onto the Control Flow area of the Designer interface, right click on Script Task component and then select Edit, a screen similar to one as given below will come up. This is a screen shot from SSIS 2008. If you are still using SSIS 2005 it will say "Design Script..." instead of "Edit Script...".

ssis script task

On the Script page of "Script Task Editor" click on "Edit Script" button, it will bring up VSTA environment (On SSIS 2005 it's VSA environment) for writing .Net code for sending emails.

Copy the code from the below tables and paste it in the VSA/VSTA code editor. There are two sets of code one for 2005 and one for 2008, so make sure you use the right version based on your version of Business Intelligence Development Studio, not the version of SQL Server you are connecting to.  Because of changes in the scripting environment between SQL Server 2005 and 2008, there would is a slight change in the code that's why I am providing the below separate code to be used on SQL Server 2005 and on SQL Server 2008. If you are running the below code in your Script Task in SSIS 2005 environment, you may need to reference the System.XML.dll. By default it is included and referenced dll in SSIS 2008, so you would not have to worry if you are using it on SSIS 2008.

Here are the objects that are referenced with the System.XML highlighted below.

ssis script task system.xml

Please note you need to change the connection string in the code pointing to the server and database where you have created the above database objects and also change the SMTP server name which will be used to send emails.  The two lines of code are as follows:

ConnString = "Data Source=ARALI-LAPTOP;Initial Catalog=Learning;Integrated Security=True;"
mySmtpClient = New SmtpClient("smtpserver")

Also, I have commented out the section that allows you to send emails using authentication to your mail server.  So if you want to use a user and password this can be supplied as well.

Script : VB .Net Code for Script Task for SQL Server 2005

Imports System
Imports System.Data
Imports System.Math
Imports Microsoft.SqlServer.Dts.Runtime
Imports System.Net
Imports System.Net.Mail
Imports System.Data.SqlClient
Imports System.Xml
Public Class ScriptMain
    ' The execution engine calls this method when the task executes.
    ' To access the object model, use the Dts object. Connections, variables, events,
    ' and logging features are available as static members of the Dts class.
    ' Before returning from this method, set the value of Dts.TaskResult to indicate success or failure.
    ' 
    ' To open Code and Text Editor Help, press F1.
    ' To open Object Browser, press Ctrl+Alt+J.
    Enum ScriptResults
        Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success
        Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
    End Enum
    Public Sub Main()
        Dim mySmtpClient As SmtpClient
        Dim ConnString As String
        ConnString = "Data Source=ARALI-LAPTOP;Initial Catalog=Learning;Integrated Security=True;"
        Try
            Dim SqlQuery As String = "GetMailsToBeSent"
            Using conn As New SqlConnection(ConnString)
                conn.Open()
                Dim comm As New SqlCommand(SqlQuery, conn)
                comm.CommandType = CommandType.StoredProcedure
                Dim adap As New SqlDataAdapter(comm)
                Dim ds As New DataSet()
                adap.Fill(ds)
                If ds.Tables(0).Rows.Count > 0 Then
                    Dim intCount As Integer
                    Dim intCCCounter As Integer
                    Dim intBCCCounter As Integer
                    For intCount = 0 To ds.Tables(0).Rows.Count - 1
                        'Create an instance of MailMessage class and pass "From EmailID" and "To EmailID" to the constructor
                        '"To" list can accept multiple email address deliminated by comma
                        Using myMessage As New MailMessage(ds.Tables(0).Rows(intCount).Item("From").ToString(), Replace(ds.Tables(0).Rows(intCount).Item("To").ToString(), ";", ","))
                            'CC List
                            'MailMessage.CC property is a collection of type MailAddressCollection so you need to add one email address at a time in this collection as I am doing it in a loop for multiple address
                            'Also you can create a MailAddressCollection first, add all the CC email address to it and finally assign it to MailMessage.CC property
                            Dim CCAddressList As MailAddress
                            If ds.Tables(0).Rows(intCount).Item("Cc").ToString().Length > 0 Then
                                If ds.Tables(0).Rows(intCount).Item("Cc").ToString().IndexOf(";") > 0 OrElse ds.Tables(0).Rows(intCount).Item("Cc").ToString().IndexOf(",") > 0 Then
                                    Dim strEmails As String()
                                    strEmails = Split(Replace(ds.Tables(0).Rows(intCount).Item("Cc").ToString(), ";", ","), ",")
                                    For intCCCounter = 0 To strEmails.Length - 1
                                        CCAddressList = New MailAddress(strEmails(intCCCounter))
                                        myMessage.CC.Add(CCAddressList)
                                    Next
                                Else
                                    CCAddressList = New MailAddress(Replace(ds.Tables(0).Rows(intCount).Item("Cc").ToString(), ";", ","))
                                    myMessage.CC.Add(CCAddressList)
                                End If
                            End If
                            'BCC List
                            'MailMessage.BCC property is a collection of type MailAddressCollection so you need to add one email address at a time in this collection as I am doing it in a loop below for multiple address
                            'Also you can create a MailAddressCollection first, add all the BCC email address to it and finally assign it to MailMessage.BCC property
                            Dim BCCAddressList As MailAddress
                            If ds.Tables(0).Rows(intCount).Item("Bcc").ToString().Length > 0 Then
                                If ds.Tables(0).Rows(intCount).Item("Bcc").ToString().IndexOf(";") > 0 OrElse ds.Tables(0).Rows(intCount).Item("Bcc").ToString().IndexOf(",") > 0 Then
                                    Dim strEmails As String()
                                    strEmails = Split(Replace(ds.Tables(0).Rows(intCount).Item("Bcc").ToString(), ";", ","), ",")
                                    For intBCCCounter = 0 To strEmails.Length - 1
                                        BCCAddressList = New MailAddress(strEmails(intBCCCounter))
                                        myMessage.Bcc.Add(BCCAddressList)
                                    Next
                                Else
                                    BCCAddressList = New MailAddress(Replace(ds.Tables(0).Rows(intCount).Item("Bcc").ToString(), ";", ","))
                                    myMessage.Bcc.Add(BCCAddressList)
                                End If
                            End If
                            myMessage.Subject = ds.Tables(0).Rows(intCount).Item("Subject").ToString()
                            myMessage.Body = ds.Tables(0).Rows(intCount).Item("Body").ToString()
                            If ds.Tables(0).Rows(intCount).Item("IsHTMLFormat").ToString().ToUpper() = "TRUE" Then
                                myMessage.IsBodyHtml = True
                            Else
                                myMessage.IsBodyHtml = False
                            End If
                            If ds.Tables(0).Rows(intCount).Item("Priority").ToString().ToUpper() = "L" Then
                                myMessage.Priority = Mail.MailPriority.Low
                            ElseIf ds.Tables(0).Rows(intCount).Item("Priority").ToString().ToUpper() = "H" Then
                                myMessage.Priority = Mail.MailPriority.High
                            Else
                                myMessage.Priority = Mail.MailPriority.Normal
                            End If
                            'To be used for sending attachements
                            'myMessage.Attachments.Add(New Attachment("c:\example1.txt"))
                            'myMessage.Attachments.Add(New Attachment("c:\example2.txt"))
                            mySmtpClient = New SmtpClient("smtpserver")
                            'You can set the SMTP port number if it is not listening on default port
                            'mySmtpClient.Port = 26
                            'The credentials returned by DefaultNetworkCredentials represents the authentication credentials for the current security context in which the application is running.
                            mySmtpClient.Credentials = CredentialCache.DefaultNetworkCredentials
                            'If you don't want to use windows authentication to connect to your SMTP host and want to specify a different username and password, you can then use NetworkCredential class as shown below
                            'The NetworkCredential class is a base class that supplies credentials in password-based authentication schemes such as basic, digest, NTLM, and Kerberos.
                            'mySmtpClient.Credentials = New NetworkCredential("arshad", "abcd", "corpnet")
                            mySmtpClient.Send(myMessage)
                        End Using
                    Next
                End If
                conn.Close()
            End Using
        Catch E As Exception
            Dts.Events.FireError(-1, "Failure in Script Task while sending mails.", E.Message.ToString(), "", 0)
            Dts.TaskResult = ScriptResults.Failure
        End Try
        Dts.TaskResult = ScriptResults.Success
    End Sub
End Class

Script : VB .Net Code for Script Task for SQL Server 2008

Imports System
Imports System.Data
Imports System.Math
Imports Microsoft.SqlServer.Dts.Runtime
Imports System.Net
Imports System.Net.Mail
Imports System.Data.SqlClient
Imports System.Xml
<SYSTEM.ADDIN.ADDIN("SCRIPTMAIN", ) Description:="" , Publisher:="" Version:="1.0"> _
<SYSTEM.CLSCOMPLIANTATTRIBUTE(FALSE)> _
Partial Public Class ScriptMain
    Inherits Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
    Enum ScriptResults
        Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success
        Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
    End Enum
    Public Sub Main()
        Dim mySmtpClient As SmtpClient
        Dim ConnString As String
        ConnString = "Data Source=ARALI-LAPTOP;Initial Catalog=Learning;Integrated Security=True;"
        Try
            Dim SqlQuery As String = "GetMailsToBeSent"
            Using conn As New SqlConnection(ConnString)
                conn.Open()
                Dim comm As New SqlCommand(SqlQuery, conn)
                comm.CommandType = CommandType.StoredProcedure
                Dim adap As New SqlDataAdapter(comm)
                Dim ds As New DataSet()
                adap.Fill(ds)
                If ds.Tables(0).Rows.Count > 0 Then
                    Dim intCount As Integer
                    Dim intCCCounter As Integer
                    Dim intBCCCounter As Integer
                    For intCount = 0 To ds.Tables(0).Rows.Count - 1
                        'Create an instance of MailMessage class and pass "From EmailID" and "To EmailID" to the constructor
                        '"To" list can accept multiple email address deliminated by comma
                        Using myMessage As New MailMessage(ds.Tables(0).Rows(intCount).Item("From").ToString(), Replace(ds.Tables(0).Rows(intCount).Item("To").ToString(), ";", ","))
                            'CC List
                            'MailMessage.CC property is a collection of type MailAddressCollection so you need to add one email address at a time in this collection as I am doing it in a loop for multiple address
                            'Also you can create a MailAddressCollection first, add all the CC email address to it and finally assign it to MailMessage.CC property
                            Dim CCAddressList As MailAddress
                            If ds.Tables(0).Rows(intCount).Item("Cc").ToString().Length > 0 Then
                                If ds.Tables(0).Rows(intCount).Item("Cc").ToString().IndexOf(";") > 0 OrElse ds.Tables(0).Rows(intCount).Item("Cc").ToString().IndexOf(",") > 0 Then
                                    Dim strEmails As String()
                                    strEmails = Split(Replace(ds.Tables(0).Rows(intCount).Item("Cc").ToString(), ";", ","), ",")
                                    For intCCCounter = 0 To strEmails.Length - 1
                                        CCAddressList = New MailAddress(strEmails(intCCCounter))
                                        myMessage.CC.Add(CCAddressList)
                                    Next
                                Else
                                    CCAddressList = New MailAddress(Replace(ds.Tables(0).Rows(intCount).Item("Cc").ToString(), ";", ","))
                                    myMessage.CC.Add(CCAddressList)
                                End If
                            End If
                            'BCC List
                            'MailMessage.BCC property is a collection of type MailAddressCollection so you need to add one email address at a time in this collection as I am doing it in a loop below for multiple address
                            'Also you can create a MailAddressCollection first, add all the BCC email address to it and finally assign it to MailMessage.BCC property
                            Dim BCCAddressList As MailAddress
                            If ds.Tables(0).Rows(intCount).Item("Bcc").ToString().Length > 0 Then
                                If ds.Tables(0).Rows(intCount).Item("Bcc").ToString().IndexOf(";") > 0 OrElse ds.Tables(0).Rows(intCount).Item("Bcc").ToString().IndexOf(",") > 0 Then
                                    Dim strEmails As String()
                                    strEmails = Split(Replace(ds.Tables(0).Rows(intCount).Item("Bcc").ToString(), ";", ","), ",")
                                    For intBCCCounter = 0 To strEmails.Length - 1
                                        BCCAddressList = New MailAddress(strEmails(intBCCCounter))
                                        myMessage.Bcc.Add(BCCAddressList)
                                    Next
                                Else
                                    BCCAddressList = New MailAddress(Replace(ds.Tables(0).Rows(intCount).Item("Bcc").ToString(), ";", ","))
                                    myMessage.Bcc.Add(BCCAddressList)
                                End If
                            End If
                            myMessage.Subject = ds.Tables(0).Rows(intCount).Item("Subject").ToString()
                            myMessage.Body = ds.Tables(0).Rows(intCount).Item("Body").ToString()
                            If ds.Tables(0).Rows(intCount).Item("IsHTMLFormat").ToString().ToUpper() = "TRUE" Then
                                myMessage.IsBodyHtml = True
                            Else
                                myMessage.IsBodyHtml = False
                            End If
                            If ds.Tables(0).Rows(intCount).Item("Priority").ToString().ToUpper() = "L" Then
                                myMessage.Priority = Mail.MailPriority.Low
                            ElseIf ds.Tables(0).Rows(intCount).Item("Priority").ToString().ToUpper() = "H" Then
                                myMessage.Priority = Mail.MailPriority.High
                            Else
                                myMessage.Priority = Mail.MailPriority.Normal
                            End If
                            'To be used for sending attachements
                            'myMessage.Attachments.Add(New Attachment("c:\example1.txt"))
                            'myMessage.Attachments.Add(New Attachment("c:\example2.txt"))
                            mySmtpClient = New SmtpClient("smtpserver")
                            'You can set the SMTP port number if it is not listening on default port
                            'mySmtpClient.Port = 26
                            'The credentials returned by DefaultNetworkCredentials represents the authentication credentials for the current security context in which the application is running.
                            mySmtpClient.Credentials = CredentialCache.DefaultNetworkCredentials
                            'If you don't want to use windows authentication to connect to your SMTP host and want to specify a different username and password, you can then use NetworkCredential class as shown below
                            'The NetworkCredential class is a base class that supplies credentials in password-based authentication schemes such as basic, digest, NTLM, and Kerberos.
                            'mySmtpClient.Credentials = New NetworkCredential("arshad", "abcd", "corpnet")
                            mySmtpClient.Send(myMessage)
                        End Using
                    Next
                End If
                conn.Close()
            End Using
        Catch E As Exception
            Dts.Events.FireError(-1, "Failure in Script Task while sending mails.", E.Message.ToString(), "", 0)
            Dts.TaskResult = ScriptResults.Failure
        End Try
        Dts.TaskResult = ScriptResults.Success
    End Sub
End Class

You should make sure you properly dispose of the instance of MailMessage class especially if you are sending attachments with the email otherwise you will end up having your files locked by Windows OS and you will not be able to delete them. The easiest way to avoid overhead of disposing of the unused objects is to use the USING statement and write your code inside its block, similar to the way it has been done in the above code.

So now for the execution of the above created package, two emails are sent to the intended audience as shown below. As expected the first email (MailMessage.IsBodyHtml = False) is non-HTML email whereas the second email (MailMessage.IsBodyHtml = True) is HTML formatted, look at color in the message body.

ssis send email text format
ssis send email html format

Notes

  • If you are running the above code in your Script Task in SSIS 2005 environment, you may need to make reference to System.Xml.dll. By default it is included and referenced dll in SSIS 2008, so you would not have to worry if you are using it on SSIS 2008.
  • You need to reference System.Net.Mail namespace in your code which contains MailMessage and SmtpClient classes which are required for sending emails.
  • There are three differences to note here between SSIS 2005 and SSIS 2008 in terms of the Script Task.
    • Now you have two language options to write your code i.e. Visual Basic .Net and C# .Net in SSIS 2008 whereas you had only one language option in SSIS 2005.
    • The scripting environment in SSIS 2008 is VSTA and it is VSA in SSIS 2005. It means almost full .Net capabilities in SSIS
    • In SSIS 2008, in Script Task Editor Dialog box, the Script page has got preference over other pages and is the first page in list on the left side, it means it saves one more click to reach to your development environment to write your code.
Next Steps


sql server categories

sql server webinars

subscribe to mssqltips

sql server tutorials

sql server white papers

next tip



About the author
MSSQLTips author Arshad Ali Arshad Ali is a SQL and BI Developer focusing on Data Warehousing projects for Microsoft.

This author pledges the content of this article is based on professional experience and not AI generated.

View all my tips



Comments For This Article




Tuesday, September 19, 2023 - 5:37:45 PM - ashish Back To Top (91580)
I have deployed a package in SQL Server and created a job in SQL Server Agent. But when job is executing Send Mail Task is getting failed which is in SSIS package. Manually it is running fine in visual Studio and SQL Server also sending mail through inbuilt Store Procedure in msdb db. Any Idea will be appreciable. Thanks in Advance.

Sunday, January 24, 2021 - 5:13:45 AM - Victor J�uregui Back To Top (88093)
Hey Arshad! Great article. I know it's not that new and perhaps there are new version but the thing is thar I've been working similarly to this approach but using sp_send_dbmail, created a couple of jobs for this and calling them from an execute sql task on SSIS. This way the sp can be used both inside SSIS or from the database. I'd like to know you opinión on this

Friday, June 5, 2020 - 10:56:39 AM - Mubasshir Farooque Back To Top (85847)

Hi Arshad,

I followed your tips and codes to send mail, as it was a part of my project and it worked perfectly fine and I also learnt many things in very easy way.

Could you please help me, as i have a requirement to send mail to 5000 people at once but want to add all the 5000 mail ID's in Bcc Column of table rather than creating 5000 rows in that table.

Thanks & Regards,

Mubasshir


Wednesday, February 5, 2020 - 11:39:40 AM - eltiti Back To Top (84182)

Hi Arshad

nice post

I would like to generate a script from an xml colun in a table like these sample

<Document>

  <id>29</id>

  <currency_id>false</currency_id>

  <code>240010</code>

  <deprecated>false</deprecated>

  <used>false</used>

  <user_type_id>6</user_type_id>

  <user_type_id>Non-current Assets</user_type_id>

  <internal_type>other</internal_type>

  <internal_group>asset</internal_group>

  <reconcile>false</reconcile>

  <note>false</note>

  <company_id>1</company_id>

  <company_id>Leymarie S.A.</company_id>

  <group_id>false</group_id>

  <root_id>50052</root_id>

  <root_id>24</root_id>

  <opening_debit>0.0</opening_debit>

  <opening_credit>0.0</opening_credit>

  <name>Mobilier des bâtiments administratifs et commerciaux</name>

  <display_name>240010 Mobilier des bâtiments administratifs et commerciaux</display_name>

  <create_uid>1</create_uid>

  <create_uid>OdooBot</create_uid>

  <create_date>2019-12-05 08:28:54</create_date>

  <write_uid>1</write_uid>

  <write_date>2019-12-05 08:28:54</write_date>

  <__last_update>2019-12-05 08:28:54</__last_update>

</Document>

from this xml info generate a one shot tsql to generate a view or another table like this sample

SELECT       [currency_id] = [xml].value('(/Document/currency_id)[1]', 'varchar(max)')

  ,[code]= [xml].value('(/Document/code)[1]', 'varchar(max)')

  ,[name]= [xml].value('(/Document/name)[1]', 'varchar(max)')

  ,[display_name]= [xml].value('(/Document/display_name)[1]', 'varchar(max)')

  ,[internal_type]= [xml].value('(/Document/internal_type)[1]', 'varchar(max)')

  ,[internal_group]= [xml].value('(/Document/internal_group)[1]', 'varchar(max)')

  ,[create_date]= [xml].value('(/Document/create_date)[1]', 'varchar(max)')

  ,[write_date]= [xml].value('(/Document/write_date)[1]', 'varchar(max)')

  ,[type]= [xml].value('(/Document/type)[1]', 'varchar(max)')

  ,[active]= [xml].value('(/Document/active)[1]', 'varchar(max)')

  ,[company_id]= [xml].value('(/Document/company_id)[1]', 'varchar(max)')

FROM           dbo.mytest_sync

WHERE        (model = 'account.account')


Thursday, October 4, 2018 - 11:48:32 AM - Ronak Shah Back To Top (77846)

 Hi Arshad,

 

I am trying to implement similar thing but am unsuccessful. i have a table with execution times. details below 

packagename executiontime

ssis1              1 hr 5 min

ssis2              1 hr 4 min

 

now this i need to send in an email 

 

i have the query. 

created an execute sql task, created 4 parameters (queryresult,packagename,executiontime,emailmessage)

but the forloop fails. 

 

can u please suggest me the steps 

 


Tuesday, August 22, 2017 - 4:46:08 PM - pETER Back To Top (65165)

 

 tHANKS FOR THE HELP!! iT WAS AMAZING eXAMPLE.


Monday, July 31, 2017 - 4:58:04 PM - Luis Back To Top (63651)

 Hi,

if you have the error:

'ScriptMain' is not CLS-compliant because it derives from 'VSTARTScriptObjectModelBase', which is not CLS-compliant

please enter the next code  after the imports:

<System.AddIn.AddIn("ScriptMain", Version:="1.0", Publisher:="", Description:="")> <System.CLSCompliantAttribute(False)> _

Partial Public Class ScriptMain

 

    Inherits Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase

 


Thursday, February 2, 2017 - 9:01:48 PM - Alaeddin Back To Top (45826)

Hi Arshad, 

Thanks for the great post. 

Actually i've been using the script task to send emails for long time, but the problem i have is that when i publish the SSIS project to the SQL Server Integration Services Catalogs it gives an error. If i delete the script task and publish again, the process works with no problems. 
I also have other script tasks for zipping the files, these script task also cause errors when i run it from SSISDB, when i delete these tasks the process runs with no errors. 

I'm not sure but it seems like when it runs from the SSISDB, it doesn't have permession to connect to the internet or move files. Do you have any tips for that? 

 

Cheers,

Alaeddin 

 


Friday, June 10, 2016 - 10:15:20 AM - Mark Charles Oliver Back To Top (41657)

 For gmail the "ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;" line was necessary for me. 

                SmtpClient mailer = new SmtpClient();

                mailer.Host = "smtp.gmail.com";

                mailer.Port = 587;

                mailer.EnableSsl = true;

                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

 

 


Thursday, July 2, 2015 - 7:40:18 AM - Superman Back To Top (38105)

Hey what about creating a table which includes css tagging like ids and classes. Then give the values of variables for data cell.

 

Ex. 

H1|H2|H3|H4|

V1|V2|V3|V4

 

V - variable

H - Heading.


Monday, June 15, 2015 - 2:08:36 PM - Mark Freeman Back To Top (37925)

It's hard to believe that no one had already submitted a Connect Feature Suggestion for this, so I just did. Please upvote https://connect.microsoft.com/SQLServer/feedback/details/1437047/ssis-send-mail-task-needs-additional-parameters.


Sunday, January 19, 2014 - 1:56:50 PM - Robert Back To Top (28136)

I am also getting the following error message, 'ScriptMain' is not CLS-compliant because it derives from 'VSTARTScriptObjectModelBase', which is not CLS-compliant.


Wednesday, November 27, 2013 - 11:43:23 PM - anamika Back To Top (27633)
Read The Tip

I am also getting the following error message, 'ScriptMain' is not CLS-compliant because it derives from 'VSTARTScriptObjectModelBase', which is not CLS-compliant. 


Thursday, September 26, 2013 - 11:32:36 PM - Carlos Back To Top (26967)

Hello! Please, help me!

I have a CSV file. It has 2 columns: ID and Name.

1,Juan

2,Pedro

3,Carlos

I need to build a HTML table into mail body and send it. How can I read each row in file? May I to use Task Scripts?

I'm begginer in SSIS, can you help me?

Thanks very much!


Tuesday, September 3, 2013 - 11:22:11 AM - Rob Back To Top (26596)

A minor issue:

Dts.TaskResult = ScriptResults.Success

should be before the Catch block.

 


Thursday, August 1, 2013 - 11:40:04 AM - Alex Back To Top (26089)

Hi Arshad,

Thanks for the post.

I need to send html links to files in the body of an email via SSIS (instead of file attachments) and therefore this method will do the trick.

Alex

 


Thursday, July 18, 2013 - 10:27:01 AM - Lindsay Back To Top (25896)

Can you show how to use variables in your SQL 2005 script task? I would like to add results from a SQL query in the html email body.


Monday, April 29, 2013 - 3:49:29 PM - Mike Brown Back To Top (23622)

Getting the following error message, 'ScriptMain' is not CLS-compliant because it derives from 'VSTARTScriptObjectModelBase', which is not CLS-compliant.  Am I forgetting something?  Thanks!

 

This is the same as for Phil Katzenberger.

 

thanks


Tuesday, January 22, 2013 - 5:28:11 PM - Phil Katzenberger Back To Top (21629)

Getting the following error message, 'ScriptMain' is not CLS-compliant because it derives from 'VSTARTScriptObjectModelBase', which is not CLS-compliant.  Am I forgetting something?  Thanks!


Monday, October 29, 2012 - 9:37:39 AM - Ryan Barrett Back To Top (20128)

Hi Arshad.

What about using SQL Mail (msdb.dbo.sp_send_dbmail) to send the HTML?


Wednesday, September 5, 2012 - 8:46:38 AM - Richard Schaefer Back To Top (19396)

Why directly read the database in the Script task? Doesn't it make more sense from an ETL architecture perspective to read the data into a variable using an Execute SQL task and then in the Script task simply iterate over the variable as a set of rows? This eliminates the need for a connection in the Script task and keeps with the overall architecture of having your database connections defined in the Connections tab.


Wednesday, June 27, 2012 - 7:45:41 AM - Suresh Back To Top (18222)

I landed on your post when searching for the option to send HTML formated email using script task in SSIS. THanks for the useful post.                           

I am doing a development in my local laptop and would like to send failure email when core logic in SSIS fails. Also, since i don't know my office SMTP server, i have tried to use gmail server to send test emails and have below necessary changes in your script posted. However, i am getting error saying "Error on sending email".

Please go thotough my below code changes and let me know if i am wrong anywhere.

-----------------------------------------------------------------------------------------------------------------------------------------------

 mySmtpClient = New SmtpClient("smtp.gmail.com")
                            mySmtpClient.Port = 587
                            mySmtpClient.Credentials = New NetworkCredential("[email protected]", "myPwd")
                            mySmtpClient.Send(myMessage)

=========================================================================================


Tuesday, November 15, 2011 - 4:36:19 PM - Lena Back To Top (15122)

Dear Arshad,

 

Awesome writing. This worked like a charm! (SQL 2005) and does exactly what I need. Thanks a lot for sharing the code!!


Tuesday, July 5, 2011 - 2:46:33 AM - Harry Back To Top (14125)

Hey Arshad,

Just my 2 cents : we could use a ForEachADOEnumerator with an object variable to loop through the table with message details. This would reduce the code for dataset population and looping table datarows.

Great article!! Thanks!!


Tuesday, April 19, 2011 - 10:22:18 AM - Mark Back To Top (13639)

^^ Nevermind! Figured it out! I've been working on this since Friday. I tried setting up the SSIS service to run as Administrator. It made no difference.

And my code/job has been completing successfully all this time. So I finally got the idea to check the mail server. It was receiving a connection from the SQL server, but the connection was closing before it was completed sending. Even though I am using the .Send method, it is still terminating too soon before flushing the buffer when run as an SSIS job.

So the solution is simply to add:

System.Threading.Thread.Sleep(5000)

After the .Send, and it finally goes through! We are using Mdaemon as our mail server. I think the problem is in the SMTP client though. Doesn't matter, it works now!


Tuesday, April 19, 2011 - 10:02:52 AM - Mark Back To Top (13638)

Hi and thank you for the very good example, my first attempt at setting up an SSIS job.

When I run the package from the design studio, I receive an email and it works fine. But when I set up the package as an SQL Job, it executes but I receive no email! I have been searching extensively, and it appears that this only seems to happen on SQL 2008, and it seems to be a permissions issue.

Any advice?

Thanks!
Mark

 


Thursday, December 23, 2010 - 12:33:23 PM - admin Back To Top (12462)

The code has been updated and should be correct now.


Wednesday, December 22, 2010 - 1:11:27 PM - Arshad Back To Top (11863)

Thanks Denise Dreher for pointing out this,

It seems the HTLML formatter has eaten up some whitespaces.

Thanks once again!

 

 


Wednesday, December 22, 2010 - 12:31:15 PM - Denise Dreher Back To Top (11862)

Typo: in 2008 version, should the For begin on a new line instead of being on the same line as Dim?

If ds.Tables(0).Rows.Count > 0 Then
     Dim intCount As Integer
     Dim intCCCounter As Integer
     Dim intBCCCounter As Integer
     For intCount = 0 To ds.Tables(0).Rows.Count - 1 


Wednesday, December 22, 2010 - 12:25:13 PM - Denise Dreher Back To Top (11861)

Typo: in 2008 version, line: Dim intBCCCounter As IntegerFor intCount = 0 To ds.Tables(0).Rows.Count - 1

Should read Integer For instead of IntegerFor


Wednesday, December 22, 2010 - 12:23:32 PM - Denise Dreher Back To Top (11860)

Typo:  in 2008 version, line: If ds.Tables(0).Rows.Count > 0 ThenDim intCount As Integer

Should read Then Dim instead of ThenDim. 


Friday, September 17, 2010 - 3:16:55 AM - Ann Back To Top (10168)
This blog Is very informative , I am really pleased to post my comment on this blog . It helped me with ocean of knowledge so I really belive you will do much better in the future.


Monday, July 12, 2010 - 1:18:16 PM - arshad0384 Back To Top (5815)

Hi,

Can you please give me the exact name of the namespace, which is giving you error or which is missing?

BTW, you need to reference System.Net.Mail namespace in your code which contains MailMessage and SmtpClient classes which are required for sending emails.

Thanks,

Arshad 

 


Monday, July 12, 2010 - 12:06:16 PM - ajroylance Back To Top (5814)

 Hi,

 I am trying to implemen this code is BIDS2008 but continually get an error:

 "A namespace does not directly contain members such as fields or methods"

which I can't figure out why.

Any ideas?

 

A


Tuesday, November 3, 2009 - 8:29:39 AM - Rashid Back To Top (4358)

Hi,

   Its a wondurfull writing, i didn't use or applied it yet, but i know somewhere down the road this post really gonna help me as i am not a .Net developer.

Thanks for sharing it.

Rashid















get free sql tips
agree to terms