Beispiel #1
0
        /// <summary>
        /// zip作成ボタン押下処理
        /// </summary>
        private void btnZipCreate_Click(object sender, RibbonControlEventArgs e)
        {
            try
            {
                Outlook.Inspector   inspector   = base.Context as Outlook.Inspector;
                Outlook.MailItem    item        = inspector.CurrentItem as Outlook.MailItem;
                Outlook.Attachments attachments = item.Attachments;
                if (attachments.Count > 0)
                {
                    item.Attachments.Add(Zip.zipPath); // zip化したファイルを添付
                    File.Delete(Zip.zipPath);

                    // zip化する前の元のファイルを添付ファイル一覧から削除
                    for (int i = 0; i < m_fileList.Count; i++)
                    {
                        File.Delete(m_fileList[i].filePath);
                        item.Attachments.Remove(1);
                    }
                    // リストからも削除する
                    int zipIndex = m_fileList.FindIndex(x => x.fileName.EndsWith(".zip"));
                    if (zipIndex != -1)
                    {
                        string zipDirectoryPath = m_fileList[zipIndex].filePath.Substring(0, m_fileList[zipIndex].filePath.Length - 4);
                        Directory.Delete(zipDirectoryPath, true);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("zip作成ボタン押下処理でエラーが発生しました。",
                                "エラー",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Hand);
            }
        }
Beispiel #2
0
        public void Inspectors_NewInspector(Microsoft.Office.Interop.Outlook.Inspector Inspector)
        {
            try
            {
                Outlook.MailItem mailItem = Inspector.CurrentItem as Outlook.MailItem;

                //InitializeComObjects();

                //Calling the event before Attachment is fully added to the mail item
                mailItem.BeforeAttachmentAdd += MailItem_BeforeAttachmentAdd;

                //Calling the event when attachment is removed
                mailItem.AttachmentRemove += MailItem_AttachmentRemove;

                //Calling the event not to save the email as draft after sent
                //mailItem.Write += MailItem_Write;

                //Initializing the olRecipients which is not marked as Clear Message recipients
                olRecipients = olMailItem.Recipients;

                //Initializing the outlook email attachments object
                olAttachments = olMailItem.Attachments;
            }
            catch (Exception e)
            {
                ResetMailObjects();
                //ReleaseComObjects();
            }
        }
Beispiel #3
0
        /// <summary>
        /// 設定したメール情報を取得
        /// </summary>
        public void file_data()
        {
            Dictionary <int, string> dicFile = new Dictionary <int, string>();

            // Inspectorを取得、MailItemを取得、Attchmentを取得
            Outlook.Inspector   ins        = app.ActiveInspector();
            Outlook.MailItem    item       = ins.CurrentItem as Outlook.MailItem;
            Outlook.Attachments attchments = item.Attachments;

            if (attchments.Count == 0)
            {
                MessageBox.Show("添付ファイルなし", AddInsLibrary.Properties.Resources.msgError, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            else
            {
                foreach (Outlook.Attachment attach in attchments)
                {
                    string name         = attach.FileName;
                    string display_name = attach.DisplayName;
                    string path         = attach.GetTemporaryFilePath();
                    string path_name    = attach.PathName;
                    int    hash         = attach.GetHashCode();

                    MessageBox.Show(name + "\r\n" + display_name + "\r\n" + path, AddInsLibrary.Properties.Resources.msgError, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }
            }
        }
        private void AddAttachmentsMenu(Button b, Outlook.MailItem mailItem)
        {
            ContextMenuStrip menuStrip = b.ContextMenuStrip;

            if (null == menuStrip)
            {
                menuStrip          = new ContextMenuStrip();
                b.ContextMenuStrip = menuStrip;
            }
            Outlook.Attachments attachments = mailItem.Attachments;
            if (attachments.Count == 0)
            {
                ToolStripMenuItem noAttachmentsItem = new ToolStripMenuItem();
                noAttachmentsItem.Text      = "(No Attachments)";
                noAttachmentsItem.ForeColor = Color.DarkGray;
                noAttachmentsItem.Enabled   = true;
                noAttachmentsItem.Click    += new System.EventHandler(this.NoAttachmentsMenuItem_Click);
                menuStrip.Items.Add(noAttachmentsItem);
            }
            else
            {
                ToolStripMenuItem attachmentsItem = new ToolStripMenuItem();
                attachmentsItem.Text = "Attachments";
                menuStrip.Items.Add(attachmentsItem);

                // make the save all attachments item and pass info through Tag
                ToolStripMenuItem saveAllAttachmentItem = new ToolStripMenuItem();
                saveAllAttachmentItem.Text   = "Save All";
                saveAllAttachmentItem.Click += new System.EventHandler(this.SaveAllAttachmentsMenuItem_Click);
                MailItemAttachments mias = new MailItemAttachments();
                foreach (Outlook.Attachment att in attachments)
                {
                    mias.Add(new MailItemAttachment(mailItem, att));
                }
                saveAllAttachmentItem.Tag = mias;
                attachmentsItem.DropDownItems.Add(saveAllAttachmentItem);

                // make an entry for each attachment to be saved individually and pass info through Tag
                foreach (Outlook.Attachment att in attachments)
                {
                    ToolStripMenuItem attachmentItem = new ToolStripMenuItem();
                    attachmentItem.Text = att.DisplayName;

                    ToolStripMenuItem saveAttachmentItem = new ToolStripMenuItem();
                    saveAttachmentItem.Text   = "Save";
                    saveAttachmentItem.Tag    = new MailItemAttachment(mailItem, att);
                    saveAttachmentItem.Click += new System.EventHandler(this.SaveAttachmentMenuItem_Click);
                    attachmentItem.DropDownItems.Add(saveAttachmentItem);

                    ToolStripMenuItem saveAndOpenAttachmentItem = new ToolStripMenuItem();
                    saveAndOpenAttachmentItem.Text   = "Save and Open";
                    saveAndOpenAttachmentItem.Tag    = new MailItemAttachment(mailItem, att);
                    saveAndOpenAttachmentItem.Click += new System.EventHandler(this.SaveAndOpenAttachmentMenuItem_Click);
                    attachmentItem.DropDownItems.Add(saveAndOpenAttachmentItem);

                    attachmentsItem.DropDownItems.Add(attachmentItem);
                }
            }
        }
Beispiel #5
0
        public void mySaveAttachAs(Office.IRibbonControl control, bool cancelDefault)
        {
            /*
             * var context = control.Context;
             * if (isContextInspector(context))
             * {
             *  Outlook.Inspector insp = (Outlook.Inspector)context;
             *  //insp.Application.
             *  var currentItem = insp.CurrentItem;
             *  if (currentItem is Outlook.MailItem)
             *  {
             *      Outlook.MailItem mi = (Outlook.MailItem)currentItem;
             *
             *  }
             * }
             */
            //string typeName = GetTypeName(control);
            Outlook.Explorer explorer = Globals.OutlookTagBarAddin.Application.ActiveExplorer();
            if (explorer != null && explorer.Selection != null && explorer.Selection.Count > 0)
            {
                object item = explorer.Selection[1];
                if (item is Outlook.MailItem)
                {
                    Outlook.MailItem    mailItem    = item as Outlook.MailItem;
                    Outlook.Attachments attachments = mailItem.Attachments;
                    Outlook.Attachment  a           = attachments[1];
                    logger.Debug("a.displayName : " + a.DisplayName + "\n");
                    logger.Debug("a.pathName : " + a.PathName + "\n");
                    logger.Debug("a.fileName : " + a.FileName + "\n");
                    SaveFileDialog sfd = new SaveFileDialog();
                    sfd.Title      = "Save Attachment";
                    sfd.FileName   = a.FileName;
                    sfd.Filter     = "All files(*.*) | *.*";
                    sfd.DefaultExt = System.IO.Path.GetExtension(a.FileName);

                    sfd.ShowDialog();
                    String resourceName = sfd.FileName;

                    logger.Debug("resourceName : " + resourceName + "\n");
                    a.SaveAsFile(sfd.FileName);
                    Backend.AddResource(Utils.RESOURCE_TYPE_FILE, resourceName);
                    Utils.TagResourceForMailItem(mailItem.EntryID, resourceName);
                    //a.SaveAsFile(@"C:\Users\sudo\Downloads");
                    cancelDefault = true;
                }
                else
                {
                    cancelDefault = false;
                }
            }
            else
            {
                cancelDefault = false;
            }
            // nlog
        }
Beispiel #6
0
        /// <summary>
        /// Add attach for a mail item
        /// </summary>
        /// <param name="mItem">Mail item</param>
        /// <param name="attachs">Attach files</param>
        /// <returns>Outlook MailItem with attachment</returns>
        public static Outlook.MailItem RemoveAttachsToEmail(Outlook.MailItem mItem)
        {
            Outlook.MailItem    oMailItem = mItem;
            Outlook.Attachments attas     = oMailItem.Attachments;

            if (attas.Count > 0)
            {
                attas.Remove(1);
            }

            return(oMailItem);
        }
        public string getAttachemmentsName(Outlook.Attachments otlAttachements)
        {
            string att = "";

            try
            {
                foreach (Outlook.Attachment otlatt in otlAttachements)
                {
                    att = att + otlatt.FileName + " , ";
                }
            }
            catch
            {
            }
            return(att);
        }
Beispiel #8
0
        //gavdcodeend 04

        //gavdcodebegin 05
        private void btnSaveAttachments_Click(object sender, RibbonControlEventArgs e)
        {
            Outlook.Application myApplication = Globals.ThisAddIn.Application;
            Outlook.Inspector   myInspector   = myApplication.ActiveInspector();

            Outlook.MailItem myMailItem = myInspector.CurrentItem as Outlook.MailItem;
            if (myMailItem != null)
            {
                Outlook.Attachments allItemAttachments = myMailItem.Attachments;
                foreach (Outlook.Attachment oneItemAttachment in allItemAttachments)
                {
                    oneItemAttachment.SaveAsFile(@"C:\Temporary\" +
                                                 oneItemAttachment.FileName);
                }
            }
        }
        public void ScanAllMailItems()
        {
            listOfMailIDs = new List <string>();
            int    count    = 0;
            string mailItem = string.Empty;

            Outlook.MAPIFolder inbox = Globals.ThisAddIn.Application.Session.DefaultStore.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);

            Outlook.Recipient    recip;
            Outlook.ExchangeUser exUser;
            string sAddress;
            string reciepient;

            Outlook.Attachments attachments = null;


            foreach (object item in inbox.Items)
            {
                Outlook.MailItem mail = item as Outlook.MailItem;

                if (mail != null && mail.Subject != null)
                {
                    try
                    {
                        mailItem = mail.Subject;
                        recip    = Globals.ThisAddIn.Application.GetNamespace("MAPI").CreateRecipient(mail.SenderEmailAddress);
                        exUser   = recip.AddressEntry.GetExchangeUser();
                        sAddress = Convert.ToString(exUser.PrimarySmtpAddress);

                        reciepient = GetSMTPAddressForRecipients(mail);
                        mailItem   = sAddress + "\t" + mail.Subject + "\t" + reciepient;
                        listOfMailIDs.Add(mailItem);

                        //  attachments = mail.Attachments;

                        //  listOfMailIDs.Add(encryptMailData(mailItem));
                        count++;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
            }
            saveTicketID(listOfMailIDs);
        }
Beispiel #10
0
        private string getAttachmentCategories(Outlook.Attachments atts)
        {
            List <string>            cats = new List <string>();
            List <AutoTagAttachment> atas = getAllAutoTagAttachmentList();
            string attcats = "";

            foreach (Outlook.Attachment att in atts)
            {
                string pat = @"image\d\d\d\.[png|jpg]";
                Regex  r   = new Regex(pat, RegexOptions.IgnoreCase);
                try
                {
                    if (att.Type == Outlook.OlAttachmentType.olEmbeddeditem || att.Type == Outlook.OlAttachmentType.olOLE)
                    {
                        continue;
                    }
                    // Those annoying imbedded images are all named imageXXX.jpg/png
                    Match m = r.Match(att.FileName);
                    if (m.Success)
                    {
                        continue;
                    }
                    String            ext    = System.IO.Path.GetExtension(att.FileName);
                    AutoTagAttachment result = atas.Find(ata => ata.extension.Equals(ext));
                    if (result != null)
                    {
                        cats.Add(result.tag);
                    }
                }
                catch (System.Exception e) { System.Windows.Forms.MessageBox.Show(att.Type.ToString() + "\n" + e.ToString(), "Error - setAttachmentCategories"); }
            }

            var enumCats = cats.Distinct();

            foreach (var item in enumCats)
            {
                attcats += ThisAddIn.CATEGORY_SEPERATOR + (string)item;
            }
            return(attcats);
        }
        private void SaveAttachment_Click(object sender, RibbonControlEventArgs e)
        {
            bool firstPrompt      = false;
            int  itemCountTotal   = 0;
            int  itemCountSaved   = 0;
            int  validAttachments = 0;
            int  min      = 0;
            var  explorer = (Microsoft.Office.Interop.Outlook.Explorer)e.Control.Context;

            Outlook.Selection selected = explorer.Selection;
            string            path     = null;

            foreach (Object obj in selected)
            {
                // Outlook.MailItem mailItem = (Outlook.MailItem)obj;
                itemCountTotal++;
                if (obj is Outlook.MailItem)
                {
                    min = 0;
                    Outlook.MailItem    mailItem    = (Outlook.MailItem)obj;
                    Outlook.Attachments attachments = mailItem.Attachments;
                    if (attachments != null && attachments.Count > 0)
                    {
                        int attachmentCount = attachments.Count;
                        // Iterate through attachments of this email
                        for (int i = 1; i <= attachmentCount; i++)
                        {
                            Outlook.Attachment attachment = attachments[i];
                            var    flags    = attachment.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x37140003");
                            String fileName = attachments[i].DisplayName;
                            // To ignore embedded attachments
                            if (flags != 4)
                            {
                                // To ignore embedded attachments in RTF mail with type 6
                                if ((int)attachment.Type != 6)
                                {
                                    if (firstPrompt != true)
                                    {
                                        // Prompt for Outlook folder path
                                        DialogResult result = folderBrowserDialog1.ShowDialog();
                                        if (result == DialogResult.OK)
                                        {
                                            path = folderBrowserDialog1.SelectedPath;
                                        }
                                        else if (result == DialogResult.Cancel)
                                        {
                                            return;
                                        }
                                        firstPrompt = true;
                                    }
                                    validAttachments++;
                                    // If file exists, prompt user to overwrite; otherwise save the file. If user clicks yes, overwrite; user clicks no, do nothing.
                                    if (File.Exists(path + "\\" + fileName))
                                    {
                                        DialogResult dialogResult = MessageBox.Show("A file named \"" + fileName + "\" already exists in this directory. Would you like to save this as an additional copy?", "File exists", MessageBoxButtons.YesNo);
                                        if (dialogResult == DialogResult.Yes)
                                        {
                                            int count = 1;
                                            min = 1;
                                            string fullPath     = path + "\\" + fileName;
                                            string fileNameOnly = Path.GetFileNameWithoutExtension(fullPath);
                                            string extension    = Path.GetExtension(fullPath);
                                            path = Path.GetDirectoryName(fullPath);
                                            string newFullPath = fullPath;
                                            while (File.Exists(newFullPath))
                                            {
                                                string tempFileName = string.Format("{0}({1})", fileNameOnly, count++);
                                                newFullPath = Path.Combine(path, tempFileName + extension);
                                            }
                                            attachments[i].SaveAsFile(newFullPath);
                                        }
                                        else if (dialogResult == DialogResult.No)
                                        {
                                        }
                                    }
                                    else
                                    {
                                        attachments[i].SaveAsFile(path + "\\" + fileName);
                                        min = 1;
                                    }
                                }
                            }
                        }
                        if (min == 1)
                        {
                            itemCountSaved++;
                        }
                    }
                }
            }
            if (validAttachments == 0)
            {
                MessageBox.Show("There are no attachments to save.");
            }
            else
            {
                MessageBox.Show("Saved attachments from " + itemCountSaved + " out of " + itemCountTotal + " emails.");
            }
        }
Beispiel #12
0
 private static void ArchivosAdjuntos(Outlook.MAPIFolder folder, string ruta, DateTime fec)
 {
     Outlook.Items fi = folder.Items;
     // Se ordenan los correos por fecha de entrega para evitar leer todos los correos que no sean del d�a actual.
     fi.Sort("[ReceivedTime]", true);
     if ((fi.ToString() != null))
     {
         foreach (Outlook.MailItem item in fi)
         {
             Outlook.MailItem mi = item;
             // Se listan todos los adjuntos del buzon.
             Outlook.Attachments attachments = mi.Attachments;
             string   nombreRemitente;
             DateTime fecha;
             // Se aplica un margen minimo y maximo el cual busque los correos.
             DateTime intervaloMenor = fec.AddHours(1);
             DateTime intervaloMayor = fec.AddHours(12);
             fecha           = mi.ReceivedTime;
             nombreRemitente = mi.SenderName;
             //fechaHora = fecha.Split(' ');
             //MessageBox.Show(fecha.Date.ToString());
             if (nombreRemitente.ToLower().Contains(ConfigurationManager.AppSettings.Get("remitente").ToLower()) && fecha.Date.Equals(fec.Date) && (mi.Subject.ToLower().Contains("CERTIFICACION POSTVENTA DIARIA".ToLower()) || mi.Subject.ToLower().Contains("BACKLOG OCEANE (ibermatica)".ToLower()) || mi.Subject.ToLower().Contains("COMENTARIOS OCEANE- TICKETS CERRADOS - POSTVENTA CONECTA PYMES".ToLower()) || mi.Subject.ToLower().Contains("COMENTARIOS OCEANE- TICKETS ABIERTOS - POSTVENTA CONECTA PYMES".ToLower())) && fecha.Hour >= intervaloMenor.Hour && fecha.Hour <= intervaloMayor.Hour)
             {
                 // Comprobamos si hay algun adjunto dentro del email recibido.
                 if ((attachments.Count != 0))
                 {
                     for (int i = 1; (i <= mi.Attachments.Count); i++)
                     {
                         // Guardamos el nombre del adjunto en "fn"
                         string fn = mi.Attachments[i].FileName.ToLower();
                         for (int j = 0; (j <= (extensionsArray.Length - 1)); j++)
                         {
                             // Utilizamos el array de extensiones para comprobar su compatibilidad y poder descargarlo.
                             if (fn.Contains(extensionsArray[j].ToString()))
                             {
                                 //  MessageBox.Show("Dia: " + fechaHora(0) + " Hora: " + fechaHora(1) & vbNewLine & "Adjunto: " + mi.Attachments(i).FileName, "Dato Adjunto")
                                 //Se realiza la comprobacion del archivo descargado (El primer if puede ser confuso, pero se realiza para evitar hacer una comrpobacion o insercion errónea de datos).
                                 if (mi.Attachments[i].FileName.Contains("Tickets Oceane Cerrados dia anterior - P.Segundo nivel"))
                                 {
                                 }
                                 else
                                 {
                                     if (mi.Attachments[i].FileName.ToLower().Contains("COMENTARIOS OCEANE- TICKETS CERRADOS - POSTVENTA CONECTA PYMES".ToLower()))
                                     {
                                         LOGS.Log("InsercionCOTA (InsercionData) --> Se Descarga el fichero 'COMENTARIOS OCEANE- TICKETS CERRADOS - POSTVENTA CONECTA PYMES'");
                                         // Se guarda el documento en la ruta especificada (se especifica en App.Config).
                                         mi.Attachments[i].SaveAsFile(ruta + "" + mi.Attachments[i].FileName);
                                         LecturaAdjuntos.LeerFicheroOceane(mi.Attachments[i].FileName, fec);
                                     }
                                     else if (mi.Attachments[i].FileName.ToLower().Contains("CERTIFICACION POSTVENTA REVISION DIARIA".ToLower()))
                                     {
                                         LOGS.Log("InsercionCOTA (InsercionData) --> Se Descarga el fichero 'Certificacion Postventa'");
                                         //Se guarda el documento en la ruta especificada (se especifica en App.Config).
                                         mi.Attachments[i].SaveAsFile(ruta + "" + mi.Attachments[i].FileName);
                                         LecturaAdjuntos.LeerFicheroOceane(mi.Attachments[i].FileName, fec);
                                     }
                                     else if (mi.Attachments[i].FileName.ToLower().Contains("BACKLOG OCEANE (ibermatica)".ToLower()))
                                     {
                                         if (comp < 1)
                                         {
                                             LOGS.Log("InsercionCOTA (InsercionData) --> Se Descarga el fichero 'BACKLOG OCEANE (ibermatica)'");
                                             // Se guarda el documento en la ruta especificada (se especifica en App.Config).
                                             mi.Attachments[i].SaveAsFile(ruta + "" + mi.Attachments[i].FileName);
                                             LecturaAdjuntos.LeerFicheroOceane(mi.Attachments[i].FileName, fec);
                                             comp++;
                                         }
                                     }
                                     else if (mi.Attachments[i].FileName.ToLower().Contains("COMENTARIOS OCEANE- TICKETS ABIERTOS - POSTVENTA CONECTA PYMES".ToLower()))
                                     {
                                         LOGS.Log("InsercionCOTA (InsercionData) --> Se Descarga el fichero 'COMENTARIOS OCEANE- TICKETS ABIERTOS - POSTVENTA CONECTA PYMES'");
                                         // Se guarda el documento en la ruta especificada (se especifica en App.Config).
                                         mi.Attachments[i].SaveAsFile(ruta + "" + mi.Attachments[i].FileName);
                                         LecturaAdjuntos.LeerFicheroOceane(mi.Attachments[i].FileName, fec);
                                     }
                                     j = extensionsArray.Length;
                                 }
                             }
                         }
                     }
                 }
             }
             else if (fecha.Date < fec.Date)
             {
                 break;
             }
         }
     }
 }
Beispiel #13
0
        /// <summary>
        /// 添付ファイルの取得
        /// </summary>
        /// <param name="item">添付されたファイル</param>
        /// <returns>true:成功、false:失敗</returns>
        private bool GetAttachments(Outlook.Attachments item)
        {
            bool zipError = false;

            if (m_tempPath == "")
            {
                Outlook.Attachment attachment = item[1];
                Zip.zipFilePath = "";
                string   path = attachment.GetTemporaryFilePath();
                string[] arr  = path.Split('\\');
                for (int i = 0; i < arr.Length - 1; i++)
                {
                    m_tempPath += arr[i] + "\\";
                    if (i < arr.Length - 2)
                    {
                        Zip.zipFilePath += arr[i] + "\\";
                    }
                }
            }
            try
            {
                foreach (var AttachmentObj in item)
                {
                    Outlook.Attachment Attachment         = (Outlook.Attachment)AttachmentObj;
                    string             path               = Attachment.PathName;
                    string             attachmentFileName = Attachment.FileName;
                    path = Path.Combine(m_tempPath, attachmentFileName);
                    string   extension      = Path.GetExtension(path);
                    string[] tempfolderList = Directory.GetFiles(m_tempPath);

                    if (!attachmentList.Contains(Attachment))
                    {
                        attachmentList.Add(Attachment);

                        if (extension != ".zip")
                        {
                            File.Copy(path, Path.Combine(m_copyFolderPath, attachmentFileName), true);
                            m_fileList.Add(new ClsFilePropertyList {
                                attachment = Attachment, fileName = attachmentFileName, filePath = Path.Combine(m_tempPath, attachmentFileName), fileExtension = extension
                            });
                        }
                        // zipの場合は解凍して中身のファイルを確認する
                        else
                        {
                            m_fileList.Add(new ClsFilePropertyList {
                                attachment = Attachment, fileName = attachmentFileName, filePath = path, fileExtension = extension, file_list = zip.UnZip(path, m_tempPath, m_fileList, ref zipError)
                            });
                            string sourceFilePath    = Path.Combine(m_tempPath, attachmentFileName.Substring(0, attachmentFileName.Length - 4));
                            string copyDirectoryPath = Path.Combine(m_copyFolderPath, attachmentFileName.Substring(0, attachmentFileName.Length - 4));

                            File.Copy(path, Path.Combine(m_copyFolderPath, attachmentFileName), true);

                            int count = m_fileList.Count();
                        }
                    }
                }
                // 正常に取得できているか確認用表示部分
                string attachmentFile = "";
                for (int i = 0; i < m_fileList.Count; i++)
                {
                    attachmentFile += m_fileList[i].fileName + "\r\n";
                }
                MessageBox.Show(attachmentFile, "添付ファイル名");
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
            return(zipError);
        }
Beispiel #14
0
        public void OnFileAction(Office.IRibbonControl control)
        {
            //Event handler for view contacts clicked
            Outlook.Inspector   insp        = null;
            Outlook.MailItem    m           = null;
            Outlook.Attachments attachments = null;
            Issue issue = null;

            try {
                Tools.CustomTaskPane ctp       = null;
                IssueSelector        ie        = null;
                Outlook.Inspector    inspector = (Outlook.Inspector)control.Context;
                if (Globals.ThisAddIn.InspectorWrappers.ContainsKey(inspector))
                {
                    InspectorWrapper iw = Globals.ThisAddIn.InspectorWrappers[inspector];
                    ctp = iw.CustomTaskPane;
                    if (ctp != null)
                    {
                        ie = (IssueSelector)ctp.Control;
                    }
                }
                switch (control.Id)
                {
                case "btnNew":
                    //Add the current outlook message as an issue action in a new issue
                    //Show explorer if not visible
                    ctp.Visible = true;

                    //Get the current email item and any associated attachments
                    insp        = Globals.ThisAddIn.Application.ActiveInspector();
                    m           = (Outlook.MailItem)insp.CurrentItem;
                    attachments = m.Attachments;

                    //Get a new issue; allow user interaction
                    issue         = CRGFactory.GetIssue(0);
                    issue.Subject = m.Subject;
                    issue.Actions.ActionTable[0].Comment = m.Body;
                    if (new dlgIssue(issue).ShowDialog() == DialogResult.OK)
                    {
                        //Save (create) the new issue
                        issue.Save();
                        if (ie != null)
                        {
                            ie.SelectedID = issue.ID;
                        }
                    }
                    break;

                case "btnAdd":
                    //Add the current outlook message as an issue action
                    issue = ie != null ? ie.SelectedIssue : null;
                    if (issue == null)
                    {
                        App.ReportError(new ApplicationException("Could not determine selected issue."), true, LogLevel.Error);
                    }
                    else
                    {
                        //Get the current email item and any associated attachments
                        insp        = Globals.ThisAddIn.Application.ActiveInspector();
                        m           = (Outlook.MailItem)insp.CurrentItem;
                        attachments = m.Attachments;

                        //Get a new action and add attachments
                        Issue.Action action = issue.Item(0);
                        action.Comment = m.Body;
                        foreach (Outlook.Attachment a in attachments)
                        {
                            Issue.Attachment attachment = action.Item(0);
                            attachment.Filename = CRGFactory.TempFolder + a.FileName;
                            action.Add(attachment);
                        }

                        //Allow user interaction
                        if (new dlgAction(action).ShowDialog() == DialogResult.OK)
                        {
                            //Save selected attachments to TEMP dir
                            foreach (Outlook.Attachment a in attachments)
                            {
                                try {
                                    if (action.Item(CRGFactory.TempFolder + a.FileName) != null)
                                    {
                                        a.SaveAsFile(CRGFactory.TempFolder + a.FileName);
                                    }
                                }
                                catch (Exception ex) { App.ReportError(new ApplicationException("Unexpected error while saving mail attachments to temporary storage; continuing...", ex), true, LogLevel.Error); }
                            }

                            //Save the action
                            issue.Add(action);
                            ie.SelectedID = issue.ID;
                        }
                    }
                    break;
                }
            }
            catch (ApplicationException ex) { throw ex; }
            catch (Exception ex) { App.ReportError(new ApplicationException("Unexpected error while handling File actions in the Issue Mgt ribbon extension.", ex), true, LogLevel.Error); }
            finally { this.mRibbonUI.Invalidate(); }
        }
Beispiel #15
0
        private static void SaveAttachment(Microsoft.Office.Interop.Outlook.NameSpace ns, String folder, String EntryID)
        {
            Console.WriteLine("[*] Try to SaveAttachment");
            Console.WriteLine("[*] Folder:" + folder);
            Console.WriteLine("[*] EntryID:" + EntryID);
            Console.WriteLine();

            Microsoft.Office.Interop.Outlook.MAPIFolder mapifolder = null;
            if (folder == "Inbox")
            {
                mapifolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
            }
            else if (folder == "Drafts")
            {
                mapifolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderDrafts);
            }
            else if (folder == "SentItems")
            {
                mapifolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderSentMail);
            }
            else if (folder == "DeletedItems")
            {
                mapifolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderDeletedItems);
            }
            else if (folder == "Outbox")
            {
                mapifolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderOutbox);
            }
            else if (folder == "JunkEmail")
            {
                mapifolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderJunk);
            }
            else
            {
                Console.WriteLine("[!] The folder is not supported yet.\r\n");
                return;
            }
            Microsoft.Office.Interop.Outlook.Items items = mapifolder.Items;
            Console.WriteLine("[!] Notice:When the antivirus software is inactive or out-of-date,it will pop up a Outlook security prompt.\r\n");

            foreach (var item in items)
            {
                var mail = item as Microsoft.Office.Interop.Outlook.MailItem;

                if (mail != null)
                {
                    if (mail.EntryID == EntryID)
                    {
                        Console.WriteLine("[+] Catch the mail.");
                        Console.WriteLine("Subject:" + mail.Subject);
                        Console.WriteLine("From:" + mail.SenderName);
                        Console.WriteLine("To:" + mail.To);
                        Console.WriteLine("CC:" + mail.CC);
                        Console.WriteLine("ReceivedTime:" + mail.ReceivedTime);
                        if (mail.Attachments.Count > 0)
                        {
                            Console.WriteLine("Attachments:" + mail.Attachments.Count);
                            Microsoft.Office.Interop.Outlook.Attachments attachments = mail.Attachments;
                            foreach (Microsoft.Office.Interop.Outlook.Attachment att in attachments)
                            {
                                Console.WriteLine("    Name:" + att.FileName);
                                att.SaveAsFile(System.Environment.CurrentDirectory + "\\" + att.FileName);
                            }
                        }
                    }
                }
            }
        }
Beispiel #16
0
        private static void ListMail(Microsoft.Office.Interop.Outlook.NameSpace ns, String folder, String mode)
        {
            Console.WriteLine("[*] Try to list mail");
            Console.WriteLine("[*] Folder:" + folder);
            Console.WriteLine("[*] Mode:" + mode);
            Console.WriteLine();
            Microsoft.Office.Interop.Outlook.MAPIFolder mapifolder = null;
            if (folder == "Inbox")
            {
                mapifolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
            }
            else if (folder == "Drafts")
            {
                mapifolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderDrafts);
            }
            else if (folder == "SentItems")
            {
                mapifolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderSentMail);
            }
            else if (folder == "DeletedItems")
            {
                mapifolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderDeletedItems);
            }
            else if (folder == "Outbox")
            {
                mapifolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderOutbox);
            }
            else if (folder == "JunkEmail")
            {
                mapifolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderJunk);
            }
            else
            {
                Console.WriteLine("[!] The folder is not supported yet.\r\n");
                return;
            }
            Microsoft.Office.Interop.Outlook.Items items = mapifolder.Items;
            Console.WriteLine("[+] Folder size:" + mapifolder.Items.Count + "\r\n");
            if (mode == "all")
            {
                Console.WriteLine("[!] Notice:When the antivirus software is inactive or out-of-date,it will pop up a Outlook security prompt.\r\n");
            }
            foreach (var item in items)
            {
                var mail = item as Microsoft.Office.Interop.Outlook.MailItem;

                if (mail != null)
                {
                    if (mail.UnRead == true)
                    {
                        Console.WriteLine("[+] UnRead Mail");
                    }
                    else
                    {
                        Console.WriteLine("[+] Mail");
                    }
                    if (mode == "short")
                    {
                        Console.WriteLine("Subject:" + mail.Subject);
                        Console.WriteLine("ReceivedTime:" + mail.ReceivedTime);
                        if (mail.Attachments.Count > 0)
                        {
                            Console.WriteLine("Attachments:" + mail.Attachments.Count);
                            Microsoft.Office.Interop.Outlook.Attachments attachments = mail.Attachments;
                            foreach (Microsoft.Office.Interop.Outlook.Attachment att in attachments)
                            {
                                Console.WriteLine("    Name:" + att.FileName);
                            }
                        }
                        Console.WriteLine("OutlookVersion:" + mail.OutlookVersion);
                        Console.WriteLine("EntryID:" + mail.EntryID);
                        Console.WriteLine();
                        continue;
                    }
                    else if (mode == "all")
                    {
                        Console.WriteLine("Subject:" + mail.Subject);
                        Console.WriteLine("From:" + mail.SenderName);
                        Console.WriteLine("To:" + mail.To);
                        Console.WriteLine("CC:" + mail.CC);
                        Console.WriteLine("ReceivedTime:" + mail.ReceivedTime);
                        if (mail.Attachments.Count > 0)
                        {
                            Console.WriteLine("Attachments:" + mail.Attachments.Count);
                            Microsoft.Office.Interop.Outlook.Attachments attachments = mail.Attachments;
                            foreach (Microsoft.Office.Interop.Outlook.Attachment att in attachments)
                            {
                                Console.WriteLine("    Name:" + att.FileName);
                            }
                        }
                        Console.WriteLine("Body:\r\n" + mail.Body);
                        Console.WriteLine("OutlookVersion:" + mail.OutlookVersion);
                        Console.WriteLine("EntryID:" + mail.EntryID);
                        Console.WriteLine();
                    }
                }
            }
        }
        private void RemoveAttachment_Click(object sender, RibbonControlEventArgs e)
        {
            int itemCountTotal   = 0;
            int itemCountRemoved = 0;
            int min      = 0;
            var explorer = (Outlook.Explorer)e.Control.Context;

            Outlook.Selection selected  = explorer.Selection;
            DialogResult      dr_delete = MessageBox.Show("Are you sure you want to delete all attachments from the selected items?", "Warning", MessageBoxButtons.YesNo);

            if (dr_delete == DialogResult.Yes)
            {
                foreach (Object obj in selected)
                {
                    string msg = null;
                    itemCountTotal++;
                    if (obj is Outlook.MailItem)
                    {
                        min = 0;
                        Outlook.MailItem    mailItem    = (Outlook.MailItem)obj;
                        Outlook.Attachments attachments = mailItem.Attachments;
                        if (attachments != null && attachments.Count > 0)
                        {
                            int attachmentCount = attachments.Count;
                            int position        = 1;
                            // Iterate through the attachments of this email
                            for (int i = 1; i <= attachmentCount; i++)
                            {
                                Outlook.Attachment attachment = attachments[position];
                                var    flags    = attachment.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x37140003");
                                String fileName = attachments[position].DisplayName;
                                // To ignore embedded attachments
                                if (flags != 4)
                                {
                                    // To ignore embedded attachments in RTF mail with type 6
                                    if ((int)attachment.Type != 6)
                                    {
                                        // Delete attachment and append a message to the body.
                                        attachments[position].Delete();
                                        min  = 1;
                                        msg += fileName + ", ";
                                    }
                                }
                                else
                                {
                                    position++;
                                    flags = attachment.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x37140003");
                                }
                            }
                            if (min == 1)
                            {
                                itemCountRemoved++;
                            }
                        }
                        if (itemCountRemoved >= 1)
                        {
                            if (msg != null)
                            {
                                msg = msg.Remove(msg.Length - 2);
                                mailItem.HTMLBody = "<p>ATTACHMENTS REMOVED: [" + msg + "]</p>" + mailItem.HTMLBody;
                                mailItem.Save();
                            }
                        }
                    }
                }
                if (itemCountRemoved == 0)
                {
                    MessageBox.Show("There are no attachments to remove.");
                }
                else
                {
                    MessageBox.Show("Removed attachments from " + itemCountRemoved + " out of " + itemCountTotal + " emails.");
                }
            }
            else if (dr_delete == DialogResult.No)
            {
            }
        }