如何在 SSIS 包中添加条件以仅在附件可用时发送邮件

How to add condition in SSIS package to send mails only if attachments are available

我创建了一个 SSIS 包,其中包含一个脚本任务,用于在“|”后的变量中添加新的附件名称和路径并 运行 在 foreach 循环下将其包含在变量值中的所有附件名称和路径。然后我将该变量作为附件传递给发送邮件任务。这个包 运行 通过批处理文件执行和发送一封包含多个文件的电子邮件很好。

现在,我想将该批处理文件安排到每小时 运行,为此,我需要在包中添加逻辑以仅在有 2 个附件可用时才发送邮件。如果没有附件或只有一个附件,它不应发送任何电子邮件。这样我想删除手动作业执行。你能帮忙吗?我是 SSIS 开发的新手。脚本任务代码如下:

if (Dts.Variables["User::FileNamesList"].Value.ToString() == "")
            {
                Dts.Variables["User::FileNamesList"].Value = Dts.Variables["User::InputPath"].Value.ToString() + Dts.Variables["User::Year"].Value.ToString() +"\" + Dts.Variables["User::FileName"].Value.ToString();
            }
            else
            { 
                Dts.Variables["User::FileNamesList"].Value = Dts.Variables["User::FileNamesList"].Value.ToString() + "|" + Dts.Variables["User::InputPath"].Value.ToString() + Dts.Variables["User::Year"].Value.ToString() + "\" + Dts.Variables["User::FileName"].Value.ToString();
            }

任何涉及邮件的事情在脚本任务中处理得更好。

让我解释一下“更好”。您对“收件人”、“抄送”、“密件抄送”、“回复收件人”等有更多的控制权。还可以发送 html 格式的正文。

这应该 运行 您的整个应用程序:

    {
        var fis = Directory.GetFiles(@"C:\folder"); //a 2nd param can be added for search pattern (ex. "*.xls")
        //Check for number of files
        if(fis.Length>1)
        {
            SendEmail("Where's it going", "Here are some files", "What you want in the body", fis);
            //Archive
            foreach (var f in fis)
                File.Move(f, @"archive folder path" + new FileInfo(f).Name);
        }

    }

    public static void SendEmail(string to, string subject, string body, string[] filePaths)
    {
        string from = "SendingMail@blah.com";
        
        using (MailMessage mail = new MailMessage())
        {
            SmtpClient SmtpServer = new SmtpClient("YourSMTPClient");

            mail.From = new MailAddress(from);

            mail.To.Add(new MailAddress(to));

            mail.Subject = subject;

            mail.IsBodyHtml = true;
            mail.Body = body;

            foreach (var f in filePaths)
            {
                Attachment file;
                file = new Attachment(f);
                mail.Attachments.Add(file);
            }

            SmtpServer.Port = 9999; //Your SMTP port
            SmtpServer.Credentials = new NetworkCredential(from, pword);

            SmtpServer.EnableSsl = true;

            SmtpServer.Send(mail);
        }
    }

这已在同一天解决。我能够在我的脚本任务中添加变量来计算文件数量(基本上它会在每次循环执行时增加 1),然后我在连接到邮件发送任务的箭头中添加了一个简单的条件以首先检查变量值是否与匹配预期值(在 SSIS 中创建了一个变量并分配了最大预期文件数),所以它现在只有在文件夹中有 2 个文件可用时才会发送邮件。我添加了一个块,只是为了重置变量,并且如果条件不匹配,它还附有从 foreach loop 到 运行 的第二个箭头。该工具现在仅发送一年的邮件,这将同时存在两个文件或跳过该循环。我也能安排那个。

箭头条件为真:发送邮件任务之前:

脚本任务重新发送变量 2 的箭头条件:

柜台: