使用部署在另一台服务器上的SSIS包从Exchange Server下载附件

时间:2017-07-05 20:37:13

标签: csv ssis exchange-server email-client

我已经构建了一个SSIS包,它从某个文件夹中读取CSV。但现在我需要从Exchange服务器下载相同的csv。而且我的机器上没有安装Outlook。我能从Exchange服务器下载CSV吗?谢谢!

1 个答案:

答案 0 :(得分:1)

我使用了链接http://sqlandbilearning.blogspot.com.au/2014/07/download-email-attachment-using-ssis.html中的一些代码,但我添加了一些新的代码,用于使用ServicePointManager删除TCP绑定错误以及添加搜索过滤器以检索特定的电子邮件,此代码也可以处理多个来自不同电子邮件的附件将保存在文件系统中。

public void Main()
        {
            string filePath = "";
            string fileName = "";
            List<SearchFilter> searchFilterCollection = new List<SearchFilter>();
            DateTime now = DateTime.Now;
            DateTime beginRecievedTime = new DateTime(now.Year, now.Month, now.Day, 7, 55, 0);
            DateTime finishRecievedTime = new DateTime(now.Year, now.Month, now.Day, 8, 15, 0);
            EmailMessage latestEmail = null;

            try
            {
                ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;

                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
                service.UseDefaultCredentials = true;
                //service.Credentials = new WebCredentials("username", "password");

                service.Url = new Uri("");


                //  10 mails per page in DESC order
                ItemView view = new ItemView(10);
                view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending);
                searchFilterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, "Scheduled search"));
                SearchFilter greaterthanfilter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, beginRecievedTime);
                searchFilterCollection.Add(greaterthanfilter);
                SearchFilter lessthanfilter = new SearchFilter.IsLessThan(ItemSchema.DateTimeReceived, finishRecievedTime);
                searchFilterCollection.Add(lessthanfilter);
                SearchFilter filter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, searchFilterCollection);
                //Find mails
                FindItemsResults<Item> fir = service.FindItems(WellKnownFolderName.Inbox, filter, view);
                Dictionary<EmailMessage, string> emailsMap = new Dictionary<EmailMessage, string>();
                foreach (Item item in fir.Items)
                {
                    item.Load(); //Load the entire message with attachment
                    EmailMessage email = item as EmailMessage;
                    if (email != null)
                    {
                        if (email.HasAttachments == true && email.Attachments.Count == 1)
                        {
                            if (email.Subject.StartsWith("Scheduled search") == true)
                            {
                                filePath = Path.Combine(Dts.Variables["User::SourceFolderPath"].Value.ToString()
                                                        , email.DateTimeReceived.Date.ToString("MM.dd.yyyy") + "_" +
                                                        email.Attachments[0].Name);
                                // fileName = email.DateTimeReceived.Date.ToString("MM.dd.yyyy") + "_" +
                                //   email.Attachments[0].Name.ToString();
                                emailsMap.Add(email, filePath);
                            }
                        }
                    }
                }

                if (emailsMap.Count > 0) {
                    foreach (var item in emailsMap) {
                        //Save attachment
                        EmailMessage email = item.Key;
                        filePath = item.Value;
                            FileAttachment fileAttachment = email.Attachments[0] as FileAttachment;
                            fileAttachment.Load(filePath);
                        string extractPath = Dts.Variables["User::SourceFolderPath"].Value.ToString() + "\\" + email.Attachments[0].Name;
                        System.IO.Compression.ZipFile.ExtractToDirectory(filePath, extractPath);
                        fileName = Dts.Variables["User::SourceFolderPath"].Value.ToString() + "\\" + email.DateTimeReceived.Date.ToString("MM.dd.yyyy") + "_" +
                          email.Attachments[0].Name.ToString();
                        if (File.Exists(fileName))
                        {
                            File.Delete(fileName);
                        }
                    }
            }

               // Dts.Variables["User::SourceFileName"].Value = fileName;

                Dts.TaskResult = (int)ScriptResults.Success;
            }
            catch(System.Runtime.InteropServices.COMException ex)
            {
                if (Dts.Variables.Locked == true)
                {
                    Dts.Variables.Unlock();
                }
                //An error occurred.
                Dts.Events.FireError(0, "Error occured", ex.Message, String.Empty, 0);
                Dts.TaskResult = (int)ScriptResults.Failure;
            }
        }