首页 > 解决方案 > 如何在 SSIS 包中添加条件以仅在附件可用时发送邮件

问题描述

我创建了一个 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();
            }

包装图片

标签: ssis

解决方案


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

让我解释一下“更好”。您可以对 To、Cc、Bcc、ReplyTo 等进行更多控制,并且能够发送 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);
        }
    }

推荐阅读