使用 Visual Studio 2010 的 SSIS 发送邮件任务脚本

Posted

技术标签:

【中文标题】使用 Visual Studio 2010 的 SSIS 发送邮件任务脚本【英文标题】:SSIS Send Mail task script with Visual Studio 2010 【发布时间】:2018-09-08 18:07:47 【问题描述】:

我在 Visual Studio 2010 中遇到了这个发送邮件脚本的挑战。

这是脚本:

#region Namespaces
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
#endregion
using System.Text.RegularExpressions;
using System.Net.Mail;
using System.IO;
namespace ST_dd466aa1cac943eb887bc0d48f753e68

    /// <summary>
    /// ScriptMain is the entry point class of the script.  Do not change the name, attributes,
    /// or parent of this class.
    /// </summary>
    [Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
    public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
    
        #region Help:  Using Integration Services variables and parameters in a script
        /* To use a variable in this script, first ensure that the variable has been added to 
         * either the list contained in the ReadOnlyVariables property or the list contained in 
         * the ReadWriteVariables property of this script task, according to whether or not your
         * code needs to write to the variable.  To add the variable, save this script, close this instance of
         * Visual Studio, and update the ReadOnlyVariables and 
         * ReadWriteVariables properties in the Script Transformation Editor window.
         * To use a parameter in this script, follow the same steps. Parameters are always read-only.
         * 
         * Example of reading from a variable:
         *  DateTime startTime = (DateTime) Dts.Variables["System::StartTime"].Value;
         * 
         * Example of writing to a variable:
         *  Dts.Variables["User::myStringVariable"].Value = "new value";
         * 
         * Example of reading from a package parameter:
         *  int batchId = (int) Dts.Variables["$Package::batchId"].Value;
         *  
         * Example of reading from a project parameter:
         *  int batchId = (int) Dts.Variables["$Project::batchId"].Value;
         * 
         * Example of reading from a sensitive project parameter:
         *  int batchId = (int) Dts.Variables["$Project::batchId"].GetSensitiveValue();
         * */

        #endregion

        #region Help:  Firing Integration Services events from a script
        /* This script task can fire events for logging purposes.
         * 
         * Example of firing an error event:
         *  Dts.Events.FireError(18, "Process Values", "Bad value", "", 0);
         * 
         * Example of firing an information event:
         *  Dts.Events.FireInformation(3, "Process Values", "Processing has started", "", 0, ref fireAgain)
         * 
         * Example of firing a warning event:
         *  Dts.Events.FireWarning(14, "Process Values", "No values received for input", "", 0);
         * */
        #endregion

        #region Help:  Using Integration Services connection managers in a script
        /* Some types of connection managers can be used in this script task.  See the topic 
         * "Working with Connection Managers Programatically" for details.
         * 
         * Example of using an ADO.Net connection manager:
         *  object rawConnection = Dts.Connections["Sales DB"].AcquireConnection(Dts.Transaction);
         *  SqlConnection myADONETConnection = (SqlConnection)rawConnection;
         *  //Use the connection in some code here, then release the connection
         *  Dts.Connections["Sales DB"].ReleaseConnection(rawConnection);
         *
         * Example of using a File connection manager
         *  object rawConnection = Dts.Connections["Prices.zip"].AcquireConnection(Dts.Transaction);
         *  string filePath = (string)rawConnection;
         *  //Use the connection in some code here, then release the connection
         *  Dts.Connections["Prices.zip"].ReleaseConnection(rawConnection);
         * */
        #endregion


        /// <summary>
        /// This method is called when this script task executes in the control flow.
        /// Before returning from this method, set the value of Dts.TaskResult to indicate success or failure.
        /// To open Help, press F1.
        /// </summary>
        /// 

        public void Main()
        
            string sSubject = "Test Subject";
            string sBody = "Test Message";
            int iPriority = 2;

            if (SendMail(sSubject, sBody, iPriority))
            
                Dts.TaskResult = (int)ScriptResults.Success;
            
            else
            
                //Fails the Task
                Dts.TaskResult = (int)ScriptResults.Failure;
            
        

        public bool SendMail(string sSubject, string sMessage, int iPriority)
        
            try
            
                string sEmailServer = Dts.Variables["sEmailServer"].Value.ToString();
                string sEmailPort = Dts.Variables["sEmailPort"].Value.ToString();
                string sEmailUser = Dts.Variables["sEmailUser"].Value.ToString();
                string sEmailPassword = Dts.Variables["sEmailPassword"].Value.ToString();
                string sEmailSendTo = Dts.Variables["sEmailSendTo"].Value.ToString();
                string sEmailSendCC = Dts.Variables["sEmailSendCC"].Value.ToString();
                string sEmailSendFrom = Dts.Variables["sEmailSendFrom"].Value.ToString();
                string sEmailSendFromName = Dts.Variables["sEmailSendFromName"].Value.ToString();

                SmtpClient smtpClient = new SmtpClient();
                MailMessage message = new MailMessage();

                MailAddress fromAddress = new MailAddress(sEmailSendFrom, sEmailSendFromName);

                //You can have multiple emails separated by ;
                string[] sEmailTo = Regex.Split(sEmailSendTo, ";");
                string[] sEmailCC = Regex.Split(sEmailSendCC, ";");
                int sEmailServerSMTP = int.Parse(sEmailPort);

                smtpClient.EnableSsl = true;
                smtpClient.Host = sEmailServer;
                smtpClient.Port = sEmailServerSMTP;

                System.Net.NetworkCredential myCredentials =
                   new System.Net.NetworkCredential(sEmailUser, sEmailPassword);
                smtpClient.Credentials = myCredentials;

                message.From = fromAddress;

                if (sEmailTo != null)
                
                    for (int i = 0; i < sEmailTo.Length; ++i)
                    
                        if (sEmailTo[i] != null && sEmailTo[i] != "")
                        
                            message.To.Add(sEmailTo[i]);
                        
                    
                

                if (sEmailCC != null)
                
                    for (int i = 0; i < sEmailCC.Length; ++i)
                    
                        if (sEmailCC[i] != null && sEmailCC[i] != "")
                        
                            message.To.Add(sEmailCC[i]);
                        
                    
                

                switch (iPriority)
                
                    case 1:
                        message.Priority = MailPriority.High;
                        break;
                    case 3:
                        message.Priority = MailPriority.Low;
                        break;
                    default:
                        message.Priority = MailPriority.Normal;
                        break;
                

                //You can enable this for Attachments.  
                //SingleFile is a string variable for the file path.
                //foreach (string SingleFile in myFiles)
                //
                //    Attachment myAttachment = new Attachment(SingleFile);
                //    message.Attachments.Add(myAttachment);
                //


                message.Subject = sSubject;
                message.IsBodyhtml = true;
                message.Body = sMessage;

                smtpClient.Send(message);
                return true;
            
            //catch (Exception ex)
            //

            //    return false;
            //

            catch (Exception ex)
            
                Dts.Events.FireError(-1, "ST_dd466aa1cac943eb887bc0d48f753e68", ex.ToString(), "", 0);
                Dts.TaskResult = (int)ScriptResults.Failure;
                return false;
            
        

        #region ScriptResults declaration
        /// <summary>
        /// This enum provides a convenient shorthand within the scope of this class for setting the
        /// result of the script.
        /// 
        /// This code was generated automatically.
        /// </summary>
        enum ScriptResults
        
            Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
            Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
        ;
        #endregion

    

这是我得到的错误:

SSIS 包“C:\Users\xxx\xxxx\visual studio 2010\projects\xxxx\xxxx\xxx.dtsx”正在启动。 错误:脚本任务中的 0xFFFFFFFF,ST_dd466aa1cac943eb887bc0d48f753e68:System.Net.Mail.SmtpException:操作已超时。 在 System.Net.Mail.SmtpClient.Send(MailMessage 消息) 在 ST_dd466aa1cac943eb887bc0d48f753e68.ScriptMain.SendMail(字符串 sSubject,字符串 sMessage,Int32 iPriority) 错误:脚本任务中的 0x6:脚本返回失败结果。 任务失败:脚本任务

SSIS 包“C:\Users\xxx\xxxx\visual studio 2010\projects\xxxx\xxxx\xxx.dtsx”完成:成功。

其次,我也想将附件作为变量。

在此期间,我使用的是 godaddy 电子邮件、Windows Server 2012R2 和 Visual Studio 2010。

【问题讨论】:

您正在发送邮件,它正在超时,因此服务器可能无法访问或 GoDaddy 服务器的响应延迟导致超时 感谢 Brad,但我已通过服务器的管理工具授予访问权限 - 我需要授予其他访问权限还是需要授予什么访问权限?干杯 不清楚,抱歉,访问意味着计算机可以访问 GoDaddy 服务器(由于防火墙、对服务器的限制,以及其他类似的东西)。它是否在您的机器上本地运行? 这里是服务器上的防火墙设置:在域、私人和公共配置文件中都允许入站和出站连接。我将尝试在我的 Mac 上运行它,看看它是否运行。再次感谢 【参考方案1】:

对于您的附件,您可以这样做,其中 EmailAttachmentPaths 是一个以逗号分隔的路径

// this is to add multipel attachments ","
            string[] ToMuliPaths = EmailAttachmentPaths.Split(',');
            foreach (string ToPathId in ToMuliPaths)
            
                // only add email if not blank
                if (ToPathId.Trim() != "")
                    mailMessage.Attachments.Add(new Attachment(ToPathId));
            // end for loop

【讨论】:

以上是关于使用 Visual Studio 2010 的 SSIS 发送邮件任务脚本的主要内容,如果未能解决你的问题,请参考以下文章

Visual Studio 2010 - 如何使用系统环境变量?

Visual Studio 2010 编辑器意外自动更正

使用带有 C#、Visual Studio 2010 的 PhoneNumbers.dll 验证电话号码

求破解版Visual Studio2010,最好百度云

Visual Studio 2010:在单个文件上运行自定义构建工具时指定工作目录

求一个靠谱的visual studio 2010 professional下载地址!