zoukankan      html  css  js  c++  java
  • 【转】:VSTO将Outlook批量邮件导出Word

    http://blog.csdn.net/jjkcom/article/details/6949394

    VSTO将Outlook批量邮件导出Word
    分类:            VSTOoutlookwordVS2010c#28人阅读评论(0)收藏举报

               VS2010将Outlook邮件导出成Word文档格式

                周末加班,整理一下outlook中的邮件,其中有个几个邮件目录中的文件都是重要的资料,想要导出成word,于是按照我的思维惯性,首先手工实现了一次,大概工序如下:

    1、首先打开邮件,ctrl+A全选邮件;

    2、然后在备份目录下新建一个word文档,黏贴进去;

    3、重命名word文件;

             手工操作了几封邮件之后,发现人肉是有点累,看到数以万封的邮件等着导出,顿感绝望,于是再次按照我的思惟惯性,需要事先一个自动化的程序来实现。

            如何来实现呢,这个功能是直接在office outlook来触发操作,一定要做一个插件,于是想到了vs2010中的VSTO,应该没问题,接下来,就是百度+google,网上搜索了一下,看看有没有现成的案例,结果还真是出乎意料,MSDN还真有:http://msdn.microsoft.com/zh-CN/library/scff9c7c.aspx。

          另外,还搜索到了一个有价值的,按照我的要求,基本实现了50%的功能了,http://www.cr173.com/html/10714_all.html"VS2010将Outlook邮件导出成Word文档格式".再次按照思维惯性,边抄、边评、边完善。

         Visual Studio允许创建Office类型的工程,用于给Office产品创建外接程序以及自定义模板等。这是一个非常实用的功能,在早期版本的Office中我们只能通过VBA代码来实现一些自定义的功能,如文本的自动替换、宏录制功能等等。VBA的功能很有限,有些时候我们希望自定义程序能够完成更多的功能,比如在Office多个不同产品之间进行文档转换、调用系统API、远程过程调用及Web Service访问等。下面是在Visual Studio 2010中创建Office类型工程的对话框。


      本例中我将向大家介绍如何通过Office外接程序将Outlook中的邮件导出到本地Word文档中。当然,你完全可以手动将Outlook中的邮件通过复制粘贴的方式拷贝到Word文档中,但是要想同时将大批的邮件导出到Word中恐怕就需要借助于程序来完成了。来看看我们如何实现这个小插件!

      首先在Visual Studio中创建Outlook 2010 Add-in类型的工程,取名为OutlookToWord。这里需要申明一下我开发和测试的环境:Visual Studio 2010 + Office 2010。当然,在Visual Studio 2008和稍低版本的Office中同样也可以实现,只是工程类型和外接程序所支持的载体版本稍有区别。

      工程创建成功后Visual Studio会自动为你生成一些文件和代码,我们只需要在代码中实现自定义的功能即可。我们希望程序通过一个按钮来实现邮件的导出,因此需要在Outlook的工具栏中创建一个自定义按钮。这个很简单,直接查MSDN,这里有非常详细的介绍,将代码拷到工程中,并做适当的修改。

    完整的代码如下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml.Linq;
    using Outlook = Microsoft.Office.Interop.Outlook;
    using Office = Microsoft.Office.Core;
    using System.Windows.Forms;
    using Word = Microsoft.Office.Interop.Word;
    using System.IO;

    namespace OutlookToWord
    {
        public partial class ThisAddIn
        {
            private Office.CommandBar newToolBar;
            private Office.CommandBarButton exportButton;
            private Outlook.Explorers selectExplorers;
            private FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();

            private void ThisAddIn_Startup(object sender, System.EventArgs e)
            {
                selectExplorers = this.Application.Explorers;
                selectExplorers.NewExplorer += new Outlook
                    .ExplorersEvents_NewExplorerEventHandler(newExplorer_Event);
                AddToolbar();
            }
            private void newExplorer_Event(Outlook.Explorer new_Explorer)
            {
                ((Outlook._Explorer)new_Explorer).Activate();
                newToolBar = null;
                AddToolbar();
            }
            private void AddToolbar()
            {
                if (newToolBar == null)
                {
                    Office.CommandBars cmdBars = this.Application.ActiveExplorer().CommandBars;
                    newToolBar = cmdBars.Add("NewToolBar", Office.MsoBarPosition.msoBarTop, false, true);
                }
                try
                {
                    Office.CommandBarButton btExportToWord = (Office.CommandBarButton)newToolBar.Controls.Add(1, missing, missing, missing, missing);
                    //btExportToWord.Style = Office.MsoButtonStyle.msoButtonCaption;
                    btExportToWord.Style = Office.MsoButtonStyle.msoButtonIconAndCaption;
                    btExportToWord.Caption = "导出word";
                    btExportToWord.Tag = "Export current mail to word";
                   
                    btExportToWord.Picture = getImage();
                    if (this.exportButton == null)
                    {
                        this.exportButton = btExportToWord;
                        exportButton.Click += new Office._CommandBarButtonEvents_ClickEventHandler(exportButton_Click);
                    }
                    newToolBar.Visible = true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            /// <summary>
            /// Create export file name from a string.
            /// </summary>
            /// <param name="sPath"></param>
            /// <param name="sFileName"></param>
            /// <returns></returns>
            private string CreateFileName(string sPath, string sFileName)
            {
                // Remove unsupport charts for file name.
                string sRst = sFileName.Replace("\\", "");
                sRst = sRst.Replace("/", "");
                sRst = sRst.Replace(":", "");
                sRst = sRst.Replace("*", "");
                sRst = sRst.Replace("?", "");
                sRst = sRst.Replace("\"\"", "");
                sRst = sRst.Replace("<", "");
                sRst = sRst.Replace(">", "");
                sRst = sRst.Replace("|", "");
                if (sRst.Length > 100)
                {
                    sRst = sRst.Substring(0, 100);
                }
                // Make sure the file name is unique.
                int i = 1;
                if (File.Exists(string.Concat(sPath, sRst, ".docx")))
                {
                    while (true)
                    {
                        if (File.Exists(string.Concat(sPath, sRst, i.ToString(), ".docx")))
                        {
                            i++;
                        }
                        else
                        {
                            sRst += i.ToString();
                            break;
                        }
                    }
                }
                 // Return *.docx file name.
                return string.Concat(sPath, sRst, ".docx");
            }
            private void exportButton_Click(Office.CommandBarButton ctrl, ref bool cancel)
            {
                //MessageBox.Show("You clicked: " + ctrl.Caption);
                object sFileName;
                string sPath = string.Empty;
                if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
                {
                    sPath = folderBrowserDialog.SelectedPath;
                    if (sPath != Path.GetPathRoot(sPath))
                    {
                        sPath += "\\";
                    }
                }
                else
                 {
                    return;
                }
                Word.Application app = new Word.Application();
                Word.Document doc = null;
                object unknow = Type.Missing;
                object format = Word.WdSaveFormat.wdFormatDocumentDefault;
                Outlook.Explorer activeExplorer = this.Application.Explorers.Application.ActiveExplorer();
                try
                {           
                    // Export all selected mail items to word.
                     foreach (object selectedItem in activeExplorer.Selection)
                     {
                         Outlook.MailItem mailItem = selectedItem as Outlook.MailItem;
                         if (mailItem != null)
                         {
                             sFileName = CreateFileName(sPath, mailItem.Subject);
                             Outlook.Inspector inspector = mailItem.GetInspector;
                             doc = (Word.Document)inspector.WordEditor;
                             doc.SaveAs(ref sFileName, ref format, ref unknow, ref unknow, ref unknow,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);
                             //附件处理方案有两个;
                             //1、直接另存附件(比较原始,当前方案);
                             //2、附件插入邮件word正文之后(优化方案,未实现);
                             if (mailItem.Attachments.Count > 0)
                             {                    
                                 for (int i = 1; i <= mailItem.Attachments.Count; i++)
                                 {
                                     mailItem.Attachments[i].SaveAsFile
                                         (sPath + //@"C:\TestFileSave\" +
                                         mailItem.Attachments[i].FileName);                            
                                    
                                 }
                             }                           
                             //doc.Close(ref unknow, ref unknow, ref unknow);
                         }
                     }
                }catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }finally
                {
                    if (app != null)
                    {
                        app.Quit(ref unknow, ref unknow, ref unknow);
                    }
                }
       
        }


            private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
            {
            }


            private stdole.IPictureDisp getImage()
            {
                stdole.IPictureDisp tempImage = null;
                try
                {
                    System.Drawing.Icon newIcon =
                        Properties.Resources.bigicon_48;


                    ImageList newImageList = new ImageList();
                    newImageList.Images.Add(newIcon);
                    tempImage = ConvertImage.Convert(newImageList.Images[0]);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                return tempImage;
            }

            #region VSTO generated code

            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InternalStartup()
            {
                this.Startup += new System.EventHandler(ThisAddIn_Startup);
                this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
            }
           
            #endregion
        }

        sealed public class ConvertImage : System.Windows.Forms.AxHost
        {
            private ConvertImage()
                : base(null)
            {
            }
            public static stdole.IPictureDisp Convert
                (System.Drawing.Image image)
            {
                return (stdole.IPictureDisp)System.
                    Windows.Forms.AxHost
                    .GetIPictureDispFromPicture(image);
            }
        }
    }

    运行效果如下:



      有几个地方需要说明一下。首先我们要得到当前已选择的邮件列表,这个是通过this.Application.Explorers.Application.ActiveExplorer().Selection来得到的,ActiveExplorer()方法返回的是当前选中的邮箱视图,比如发件箱、草稿箱、收件箱等。Selection属性得到是其中所有被选中的邮件的集合,在Outlook中你可以同时选中多封邮件。程序通过foreach便利所有当前被选中的邮件,然后依次导出到Word文档中。邮件主题被用作Word文档的名称,这里有一个CreateFileName方法用来处理并生成最终的文件名,稍后给出这个方法的代码。对于如何保存Word文档的内容,这里有几个地方需要注意:

      1. mailItem对象可以通过Body,HTMLBody,RTFBody来得到邮件的内容,但是其中的格式会有所区别。通过Body得到的是去掉所有样式之后的纯文本内容,HTMLBody得到的是转换之后的HTML格式的邮件内容,RTFBody则是包含富文本格式的二进制邮件内容。

      2. 我们可以通过doc.Content.Text或doc.Paragraphs.Last.Range.Text来给Word文档填充内容,两者的效果是一样的。但是这两种方法只能接收字符串内容,也就是说如果邮件中包含特定格式的信息都会被自动过滤掉,如邮件中的表格、文字样式、图片、超链接等内容。

      3. 通过mailItem.GetInspector将邮件的编辑器转换成Word文档可以将Outlook邮件中的所有内容无差异地保存到Word中。因为Outlook邮件编辑器使用的正是Word文档的编辑器,因此这个转换是有效的。

      4. Word文档的创建、保存方法与其它在C#中操作Word相同。需要注意的是如果使用doc.Content.Text或doc.Paragraphs.Last.Range.Text方法填充Word文档内容,完毕之后一定要关闭Word文档。另外就是程序结束后要关掉Word进程,否则每次导出都会在内存中创建一个Word进程造成资源的浪费。

      5. Word文档保存的格式选用wdFormatDocumentDefault,这个是Word文档保存的默认格式,如果选用其它格式,需要确保你所保存的内容能被选用的格式支持。

      下面来看一下CreateFileName方法。这个方法是用来处理生成的Word文档的文件名的。程序中使用了邮件主题作为Word文件名,由于Windows文件名不支持部分特殊字符,因此我们需要在生成文件名的过程中将这些特殊字符过滤掉,同时为了确保所生成的Word不会被重复覆盖,需要对文件名作差异化处理——即如果文件存在则在后面增量增加一个数字,如新建文件1、新建文件2等。另外就是如果文件名过长只截取前100个字符。



    好了,到此程序已经大功告成了,但是有两个问题:

    1、邮件选择只能以当前视图下的多选为准,没有实现邮件目录的选择;

    2、附件的方案有待优化。

    做个快乐的自己。
  • 相关阅读:
    python json模块(15)
    python random模块(14)
    python time模块(13)
    python sys模块(12)
    python zip函数(11)
    python递归函数(10)
    python 浅拷贝和深拷贝(9)
    python is 和 == 区别(8)
    python 可变数据类型和不可变数据类型(7)
    python局部变量和全局变量(6)
  • 原文地址:https://www.cnblogs.com/Jessy/p/2272283.html
Copyright © 2011-2022 走看看