簡體   English   中英

使用Visual Studio 2010的SSIS發送郵件任務腳本

[英]SSIS Send Mail task script with Visual Studio 2010

我在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”開始。 錯誤:腳本任務ST_dd466aa1cac943eb887bc0d48f753e68處的錯誤為0xFFFFFFFF:System.Net.Mail.SmtpException:操作已超時。 在ST_dd466aa1cac943eb887bc0d48f753e68.ScriptMain.SendMail(String sSubject,String sMessage,Int32 iPriority)的System.Net.Mail.SmtpClient.Send(MailMessage消息)處出現錯誤:腳本任務處錯誤:0x6:腳本返回了失敗結果。 任務失敗:腳本任務

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

其次,我也希望將附件作為變量。

之間,我正在使用Godaddy電子郵件,Windows Server 2012R2和Visual Studio 2010。

對於您的附件,您可以執行以下操作,其中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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM