Exemplo n.º 1
0
        public static void LoadItemsAttachmentsListLv(Item oItem, ref ListView oListView)
        {
            oListView.Clear();
            oListView.View          = View.Details;
            oListView.GridLines     = true;
            oListView.FullRowSelect = true;
            oListView.Columns.Add("Id", 70, HorizontalAlignment.Left);

            oListView.Columns.Add("ContentId", 70, HorizontalAlignment.Left);
            oListView.Columns.Add("ContentLocation", 70, HorizontalAlignment.Left);
            oListView.Columns.Add("ContentType", 70, HorizontalAlignment.Left);
            oListView.Columns.Add("Name", 140, HorizontalAlignment.Left);
            oListView.Columns.Add("IsInline", 50, HorizontalAlignment.Left);  // Exchange 2010 and later.
            //oListView.Columns.Add("LastModifiedTime", 70, HorizontalAlignment.Left); // Exchange 2010 and later.
            //oListView.Columns.Add("Size", 70, HorizontalAlignment.Right);    // Exchange 2010 and later.


            ListViewItem oListItem        = null;
            int          iAttachmentCount = 0;

            foreach (Attachment oAttachment in oItem.Attachments)
            {
                oItem.Service.ClientRequestId = Guid.NewGuid().ToString();  // Set a new GUID
                oAttachment.Load();
                if (oAttachment is ItemAttachment)
                {
                    ItemAttachment oItemAttachment = oAttachment as ItemAttachment;

                    // Load attachment into memory so we can get to the item properties (such as subject).
                    oItem.Service.ClientRequestId = Guid.NewGuid().ToString();  // Set a new GUID
                    oItemAttachment.Load();

                    oListItem = new ListViewItem(oAttachment.Id, 0);

                    oListItem.SubItems.Add(oItemAttachment.ContentId);
                    oListItem.SubItems.Add(oItemAttachment.ContentLocation);
                    oListItem.SubItems.Add(oItemAttachment.ContentType);
                    oListItem.SubItems.Add(oItemAttachment.Name);
                    oListItem.SubItems.Add(oItemAttachment.IsInline.ToString());



                    oListItem.Tag = iAttachmentCount;
                    oListView.Items.AddRange(new ListViewItem[] { oListItem });
                    oListItem = null;
                }

                if (oAttachment is FileAttachment)
                {
                }
            }
            iAttachmentCount++;
        }
        public EWSIncomingItemAttachment(ItemAttachment attachment)
        {
            _attachment = attachment;
            Logger.DebugFormat("Loading attachment");
            var additionalProperties = new PropertySet {
                ItemSchema.MimeContent
            };

            _attachment.Load(additionalProperties);

            Logger.DebugFormat("Attachment name is {0}", _attachment.Name);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Demonstrates three ways to get file attachments and how to get an item attachment.
        /// </summary>
        /// <param name="service">An ExchangeService object with credentials and the EWS URL.</param>
        private static void GetAttachments(ExchangeService service)
        {
            // Return a single item.
            ItemView view = new ItemView(1);

            string querystring = "HasAttachments:true Subject:'Message with Attachments' Kind:email";

            // Find the first email message in the Inbox that has attachments. This results in a FindItem operation call to EWS.
            FindItemsResults <Item> results = service.FindItems(WellKnownFolderName.Inbox, querystring, view);

            if (results.TotalCount > 0)
            {
                EmailMessage email = results.Items[0] as EmailMessage;

                // Request all the attachments on the email message. This results in a GetItem operation call to EWS.
                email.Load(new PropertySet(EmailMessageSchema.Attachments));

                foreach (Attachment attachment in email.Attachments)
                {
                    if (attachment is FileAttachment)
                    {
                        FileAttachment fileAttachment = attachment as FileAttachment;

                        // Load the file attachment into memory. This gives you access to the attachment content, which
                        // is a byte array that you can use to attach this file to another item. This results in a GetAttachment operation
                        // call to EWS.
                        fileAttachment.Load();
                        Console.WriteLine("Load a file attachment with a name = " + fileAttachment.Name);

                        // Load attachment contents into a file. This results in a GetAttachment operation call to EWS.
                        fileAttachment.Load("C:\\temp\\" + fileAttachment.Name);

                        // Put attachment contents into a stream.
                        using (FileStream theStream = new FileStream("C:\\temp\\Stream_" + fileAttachment.Name, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                        {
                            //This results in a GetAttachment operation call to EWS.
                            fileAttachment.Load(theStream);
                        }
                    }
                    else // Attachment is an item attachment.
                    {
                        ItemAttachment itemAttachment = attachment as ItemAttachment;

                        // Load the item attachment properties. This results in a GetAttachment operation call to EWS.
                        itemAttachment.Load();
                        Console.WriteLine("Loaded an item attachment with Subject = " + itemAttachment.Item.Subject);
                    }
                }
            }
        }
Exemplo n.º 4
0
        //gavdcodeend 16

        //gavdcodebegin 17
        static void GetAttachments(ExchangeService ExService)
        {
            SearchFilter myFilter = new SearchFilter.SearchFilterCollection(
                LogicalOperator.And,
                new SearchFilter.IsEqualTo(
                    EmailMessageSchema.Subject,
                    "Email with Attachments"));
            ItemView myView = new ItemView(1);
            FindItemsResults <Item> findResults = ExService.FindItems(
                WellKnownFolderName.Inbox, myFilter, myView);

            ItemId myEmailId = null;

            foreach (Item oneItem in findResults)
            {
                myEmailId = oneItem.Id;
            }

            PropertySet myPropSet = new PropertySet(BasePropertySet.IdOnly,
                                                    ItemSchema.Attachments);
            EmailMessage emailWithAttachments =
                EmailMessage.Bind(ExService, myEmailId, myPropSet);

            foreach (Attachment oneAttachment in emailWithAttachments.Attachments)
            {
                if (oneAttachment is FileAttachment) // Attachment is a File
                {
                    FileAttachment myAttachment = oneAttachment as FileAttachment;

                    FileStream attStream = new FileStream(@"C:\Temporary\Attch_" +
                                                          myAttachment.Name, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                    myAttachment.Load(attStream);
                    attStream.Close();
                    attStream.Dispose();
                }
                else // Attachment is an Item
                {
                    ItemAttachment itemAttachment = oneAttachment as ItemAttachment;
                    itemAttachment.Load();
                    Console.WriteLine("Subject: " + itemAttachment.Item.Subject);
                }
            }
        }
Exemplo n.º 5
0
        public EmailAttachDTO(object attach, bool loadContent = true)
        {
            byte[] content = null;
            if (attach.GetType() == typeof(FileAttachment))
            {
                FileAttachment fAttach = (FileAttachment)attach;
                if (loadContent)
                {
                    if (fAttach.Content is null)
                    {
                        fAttach.Load();
                    }
                    content = fAttach.Content;
                }

                cargar_datos(fAttach.Id, fAttach.Name, fAttach.ContentType, fAttach.Size, content, fAttach.IsInline);
            }
            else if (attach.GetType() == typeof(ItemAttachment))
            {
                ItemAttachment iAttach = (ItemAttachment)attach;
                if (loadContent)
                {
                    iAttach.Load(ItemSchema.MimeContent);
                    if (iAttach.Item is object && iAttach.Item.GetType() == typeof(EmailMessage))
                    {
                        EmailMessage mAttach = (EmailMessage)iAttach.Item;
                        if (loadContent)
                        {
                            content = mAttach.MimeContent.Content;
                        }
                        cargar_datos(iAttach.Id, iAttach.Name + ".eml", iAttach.ContentType, iAttach.Size, content, iAttach.IsInline);
                    }
                    else
                    {
                        cargar_datos(iAttach.Id, iAttach.Name, iAttach.ContentType, iAttach.Size, null, iAttach.IsInline);
                    }
                }
                else
                {
                    cargar_datos(iAttach.Id, iAttach.Name, iAttach.ContentType, iAttach.Size, null, iAttach.IsInline);
                }
            }
        }
Exemplo n.º 6
0
        public static void downloadWithUniqueName(this Microsoft.Exchange.WebServices.Data.Attachment att, ref string path, int mtaNum)
        {
            try
            {
                Directory.CreateDirectory(path);
                path += ("\\" + EvaultWin.Common.evWinHash.MD5Hasing.GetMD5HashFromText(mtaNum.ToString() + EvaultWin.Common.evWinRandom.winRandomNumber.GetRandomName(DateTime.Now.ToString())) + Path.GetExtension(att.Name));

                if (att is FileAttachment)
                {
                    FileAttachment fa = att as FileAttachment;
                    fa.Load(path);
                }
                else
                {
                    ItemAttachment itemAtt = att as ItemAttachment;
                    itemAtt.Load(new PropertySet(EmailMessageSchema.MimeContent));
                    MessageBox.Show("is item Att with path : " + path);
                    //path += ".eml";

                    byte[] mc = itemAtt.Item.MimeContent.Content;
                    using (FileStream fs = File.Open(path, FileMode.Create, FileAccess.Write))
                    {
                        fs.Write(mc, 0, mc.Length);
                    }
                }
            }
            catch (Exception err)
            {
                path = string.Empty;


                WinEventLog.WriteEventLog("MTA failed to download attachment for scanning, error = " + err.Message, EventLogEntryType.FailureAudit);

                EvaultWin.DLP.evWinExceptionHandlingCMC.ExceptionHandling.DetailEventLog(true, false,
                                                                                         EvaultWin.DLP.evWinExceptionHandlingCMC.EventExceptionType.UnexpectedResult, EvaultWin.DLP.evWinExceptionHandlingCMC.EventSeverityLevel.Error,
                                                                                         err.Message, err.Source.ToString() + " : " + err.TargetSite.ToString(), err.ToString().Replace("\r", "").ToString());

                //MessageBox.Show("Failed to download attachment, err : " + err.Message);
            }
        }
        private void ProcesarAdjuntos(Item item)
        {
            if (item.HasAttachments)//solo si tenemos adjuntos
            //obtenemos cada uno de los adjuntos contenidos en la collection Attachments
            {
                foreach (Attachment adjunto in item.Attachments)
                {
                    if (adjunto is FileAttachment)// si es un archivo adjunto
                    {
                        FileAttachment archivoAdjunto = adjunto as FileAttachment;

                        // Load the attachment into a file.
                        // This call results in a GetAttachment call to EWS.
                        archivoAdjunto.Load("C:\\temp\\" + archivoAdjunto.Name);

                        Console.WriteLine("nombre del archivo adjunto: " + archivoAdjunto.Name);
                    }
                    else // si es un item adjunto
                    {
                        ItemAttachment itemAdjunto = adjunto as ItemAttachment;

                        //cargamos el adjunto en memoria.
                        //esta llamada resulta en una llamada GetAttachment a EWS
                        itemAdjunto.Load();

                        Console.WriteLine("nombre del item adjunto: " + itemAdjunto.Name);
                    }
                    FolderId folderID = getFolderID("procesados");

                    if (folderID != null)    //si encontramos la carpeta la
                    {
                        item.Move(folderID); //movemos el item.
                        Console.WriteLine("Item Movido.");
                    }
                }
            }
        }
        private void MnuSaveAttach_Click(object sender, EventArgs e)
        {
            // Don't do anything if a content row is not selected
            if (this.ContentsGrid.SelectedRows.Count == 0)
            {
                return;
            }

            Attachment attach = this.ContentsGrid.SelectedRows[0].Cells[ColNameAttachmentObj].Value as Attachment;

            // If we can't get the attachment object bail out
            if (attach == null)
            {
                return;
            }

            // Get the file name we'll save to and bail out if we don't succeed
            // Create a file path to save the item properties to
            string fileName = null;

            //fileName = string.Format(
            //System.Globalization.CultureInfo.CurrentCulture,
            //    "{0}\\{1}.xml",
            //    destinationFolderPath,
            //    FileHelper.SanitizeFileName(item.Subject));

            fileName = this.GetTargetFileName(fileName);
            if (fileName == string.Empty)
            {
                return;
            }

            this.Cursor = Cursors.WaitCursor;

            System.Diagnostics.Debug.WriteLine("ItemClass of Mesage: " + currentParentItem.ItemClass);


            // If the attachment is a FileAttachment then simply save the content
            FileAttachment fileAttach = attach as FileAttachment;

            if (fileAttach != null)
            {
                if (fileAttach.Content == null)
                {
                    ErrorDialog.ShowWarning("Cannot save FileAttachment because FileAttachment.Content is NULL.");
                    return;
                }

                try
                {
                    this.Cursor = Cursors.WaitCursor;

                    System.IO.File.WriteAllBytes(fileName, fileAttach.Content);
                }
                finally
                {
                    this.Cursor = Cursors.Default;
                }
            }
            else
            {
                ItemAttachment itemAttachment = attach as ItemAttachment;
                if (itemAttachment != null)
                {
                    if (itemAttachment.Item == null)
                    {
                        ErrorDialog.ShowWarning("Cannot save ItemAttachment because ItemAttachment.Item is NULL.");
                        return;
                    }

                    try
                    {
                        this.Cursor = Cursors.WaitCursor;
                        //if (currentParentItem.ItemClass == "")
                        //{
                        //}

                        // Note that not everything has a MIME type. An NDR does not have one, so MIME conversion will fail.
                        // Save an attached email by using the EWS Managed API
                        //      https://docs.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-get-attachments-by-using-ews-in-exchange
                        string sMIME = string.Empty;

                        //System.Diagnostics.Debug.WriteLine("ItemClass of Mesage: " + currentParentItem.ItemClass);

                        try
                        {
                            itemAttachment.Load(ItemSchema.MimeContent);



                            //UTF8Encoding oUTF8Encoding = new UTF8Encoding();                            // For debugging
                            //sMIME = oUTF8Encoding.GetString(itemAttachment.Item.MimeContent.Content);   // For debugging

                            System.IO.File.WriteAllBytes(fileName, itemAttachment.Item.MimeContent.Content);
                        }
                        catch (Exception ex)
                        {
                        }


                        //string sFolderPath = System.IO.Path.GetPathRoot(fileName);
                        //string sFilePath = System.IO.Path.GetFileName(fileName);

                        //EWSEditor.Common.DumpHelper.DumpXMLbyFileName(
                        //    itemAttachment.Item,
                        //    sFolderPath,
                        //    sFilePath);
                    }
                    finally
                    {
                        this.Cursor = Cursors.Default;
                    }

                    this.Cursor = Cursors.WaitCursor;

                    // An Item Attachment may have attachemnets also - so, save them off also.  Things like NDR messages contain the origional message.
                    try
                    {
                        this.Cursor = Cursors.WaitCursor;

                        // Save an attached email by using the EWS Managed API
                        // https://docs.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-get-attachments-by-using-ews-in-exchange

                        // Code to save message attachment sub-items.  This will work for journaled messages.
                        int iSub1AttachCount = 0;
                        if (itemAttachment.Item.Attachments.Count > 0)
                        {
                            foreach (Attachment Sub1Attachment in itemAttachment.Item.Attachments)
                            {
                                ItemAttachment Sub1ItemAttachment = Sub1Attachment as ItemAttachment;
                                if (Sub1ItemAttachment != null)
                                {
                                    iSub1AttachCount++;

                                    try
                                    {
                                        Sub1ItemAttachment.Load(ItemSchema.MimeContent);  // if MIME can be pulled then save it.  not all types have a MIME equivilent.

                                        System.IO.File.WriteAllBytes(fileName + " - " + iSub1AttachCount.ToString(), Sub1ItemAttachment.Item.MimeContent.Content);
                                    }
                                    finally
                                    {
                                    }
                                }
                            }


                            //int iSub2AttachCount = 0;
                            //foreach (ItemAttachment o in itemAttachment.Item.Attachments)
                            //{

                            //    ItemAttachment itemSubAttachment = o as ItemAttachment;
                            //    if (itemAttachment != null)
                            //    {
                            //        iSub2AttachCount++;

                            //        try
                            //        {
                            //            //o.Load(ItemSchema.MimeContent);  // if MIME can be pulled then save it.  not all types have a MIME equivilent.

                            //            //System.IO.File.WriteAllBytes(fileName + " - ItemAttachment " + iSubAttachCount.ToString(), itemAttachment.Item.MimeContent.Content);

                            //            //int iSub2AttachCount = 0;

                            //            //foreach (ItemAttachment o2 in o.Item.Attachments)
                            //            //{

                            //            //    ItemAttachment itemSub2Attachment = o2 as ItemAttachment;
                            //            //    if (itemAttachment != null)
                            //            //    {
                            //            //        iSub2AttachCount++;

                            //            //        try
                            //            //        {
                            //            //            itemAttachment.Load(ItemSchema.MimeContent);  // if MIME can be pulled then save it.  not all types have a MIME equivilent.

                            //            //            System.IO.File.WriteAllBytes(fileName + " - ItemAttachment " + iSub2AttachCount.ToString(), itemAttachment.Item.MimeContent.Content);
                            //            //        }
                            //            //        finally
                            //            //        {
                            //            //        }
                            //            //    }
                            //            //}
                            //        }
                            //        finally
                            //        {
                            //        }
                            //    }
                            //}
                        }

                        this.Cursor = Cursors.Default;

                        string sFolderPath = System.IO.Path.GetPathRoot(fileName);
                        string sFilePath   = System.IO.Path.GetFileName(fileName);

                        //EWSEditor.Common.DumpHelper.DumpXMLbyFileName(
                        //    itemAttachment.Item,
                        //    sFolderPath,
                        //    sFilePath);
                    }
                    finally
                    {
                        this.Cursor = Cursors.Default;
                    }
                }
            }
        }
Exemplo n.º 9
0
        } // End Sub SendMailWithAttachment

        public static void FindUnreadEmail(ExchangeService service)
        {
            try
            {
                Folder inbox = Folder.Bind(service, WellKnownFolderName.Inbox);
            }
            catch (System.Exception e)
            {
                System.Console.WriteLine(e);
            }

            // The search filter to get unread email.
            SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And
                                                                      , new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
            ItemView view = new ItemView(1);

            // https://stackoverflow.com/questions/20662855/fetching-all-mails-in-inbox-from-exchange-web-services-managed-api-and-storing-t
            FindItemsResults <Item> findResults = null;

            do
            {
                // Fire the query for the unread items.
                // This method call results in a FindItem call to EWS.
                findResults = service.FindItems(WellKnownFolderName.Inbox, sf, view);

                System.Console.WriteLine(findResults.TotalCount);

                foreach (Item item in findResults)
                {
                    if (item is EmailMessage)
                    {
                        EmailMessage em = item as EmailMessage;
                        System.Console.WriteLine("Subject: \"{0}\"", em.Subject);

                        // https://msdn.microsoft.com/en-us/library/office/dn726695(v=exchg.150).aspx
                        if (em.HasAttachments)
                        {
                            EmailMessage message = EmailMessage.Bind(service, item.Id
                                                                     , new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments));

                            foreach (Attachment attachment in message.Attachments)
                            {
                                System.Console.WriteLine(attachment.Name);

                                if (attachment is FileAttachment)
                                {
                                    FileAttachment fa = attachment as FileAttachment;
                                    fa.Load();
                                    // System.Console.WriteLine(fa.Content);
                                    // System.IO.File.WriteAllBytes(@"d:\" + attachment.Name, fa.Content);
                                    // System.Console.WriteLine(fa.ContentType);
                                    // System.Console.WriteLine(fa.Content.Length);
                                } // End if (attachment is FileAttachment)
                                else if (attachment is ItemAttachment)
                                {
                                    ItemAttachment itemAttachment = attachment as ItemAttachment;
                                    itemAttachment.Load(ItemSchema.MimeContent);
                                    string fileName = @"C:\Temp\" + itemAttachment.Item.Subject + @".eml";

                                    // Write the bytes of the attachment into a file.
                                    // System.IO.File.WriteAllBytes(fileName, itemAttachment.Item.MimeContent.Content);
                                    System.Console.WriteLine("Email attachment name: " + itemAttachment.Item.Subject + ".eml");
                                } // End else if (attachment is ItemAttachment)
                            }     // Next attachment
                        }         // End if (em.HasAttachments)
                    }             // End if (item is EmailMessage)
                    else if (item is MeetingRequest)
                    {
                        MeetingRequest mr = item as MeetingRequest;
                        System.Console.WriteLine("Subject: \"{0}\"", mr.Subject);
                    }
                    else
                    {
                        // we can handle other item types
                    }
                } // Next item

                //any more batches?
                if (findResults.NextPageOffset.HasValue)
                {
                    view.Offset = findResults.NextPageOffset.Value;
                } // End if (findResults.NextPageOffset.HasValue)
            } while (findResults.MoreAvailable);
        }         // End Sub FindUnreadEmail
Exemplo n.º 10
0
            public string DownloadAttachments(EmailMessage message, string AttachmentSavePath, string[] EmailAttachment, string RetainOriginalAttName, string emailAttachmentLocation, int emailID = 0)
            {
                try
                {
                    string emailAttachments = "";
                    int    fileID           = 0;

                    foreach (Attachment attachment in message.Attachments)
                    {
                        if (attachment.IsInline == false)
                        {
                            string emailAttachmentSaveLocation = "";


                            if ((EmailAttachment.Any(attachment.Name.Contains) == false) && EmailAttachment[0] != "")
                            {
                                continue;
                            }
                            string extension = "";
                            string filename  = "";
                            if (attachment is ItemAttachment)
                            {
                                ItemAttachment fileAttachment = attachment as ItemAttachment;
                                extension = ".eml";
                                filename  = fileAttachment.Name.ToString();
                                Regex rgx = new Regex("[^a-zA-Z0-9 ]");


                                filename = rgx.Replace(filename, "");
                                filename = filename + extension;
                            }
                            else
                            {
                                FileAttachment fileAttachment = attachment as FileAttachment;
                                filename  = fileAttachment.Name.ToString();
                                extension = Path.GetExtension(filename);
                            }


                            if (RetainOriginalAttName == "true")
                            {
                                if (emailID == 0)
                                {
                                    emailAttachmentLocation = AttachmentSavePath + filename;
                                }
                                else
                                {
                                    emailAttachmentLocation = AttachmentSavePath + emailID + @"\" + filename;
                                }

                                if (emailAttachments == "")
                                {
                                    emailAttachments = filename;
                                }
                                else
                                {
                                    emailAttachments = emailAttachments + "|" + filename;
                                }
                            }
                            else
                            {
                                fileID++;


                                if (emailID == 0)
                                {
                                    emailAttachmentLocation = AttachmentSavePath + fileID + extension;
                                }
                                else
                                {
                                    emailAttachmentLocation = AttachmentSavePath + emailID + @"\" + fileID + extension;
                                }

                                if (emailAttachments == "")
                                {
                                    emailAttachments = fileID + extension;
                                }
                                else
                                {
                                    emailAttachments = emailAttachments + "|" + fileID + extension;
                                }
                            }

                            emailAttachmentSaveLocation = emailAttachmentLocation;

                            if (attachment is ItemAttachment)
                            {
                                ItemAttachment fileAttachment = attachment as ItemAttachment;
                                fileAttachment.Load(EmailMessageSchema.MimeContent);

                                // MimeContent.Content will give you the byte[] for the ItemAttachment
                                // Now all you have to do is write the byte[] to a file
                                File.WriteAllBytes(emailAttachmentLocation, fileAttachment.Item.MimeContent.Content);
                            }
                            else
                            {
                                FileAttachment fileAttachment = attachment as FileAttachment;
                                fileAttachment.Load(emailAttachmentLocation);
                            }
                        }
                    }


                    return(emailAttachments);
                }
                catch (Exception e)
                {
                    throw;
                }
            }
Exemplo n.º 11
0
        static void Main(string[] args)
        {
            var service = new ExchangeService();

            service.Credentials = new NetworkCredential("*****@*****.**", "Kittyapu*5");

            try
            {
                service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
            }
            catch (AutodiscoverRemoteException ex)
            {
                Console.WriteLine(ex.Message);
            }

            FolderId inboxId     = new FolderId(WellKnownFolderName.Inbox, "*****@*****.**");
            var      findResults = service.FindItems(inboxId, new ItemView(150));

            try
            {
                foreach (var message in findResults.Items)
                {
                    var msg = EmailMessage.Bind(service, message.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments));

                    foreach (Microsoft.Exchange.WebServices.Data.Attachment attachment in msg.Attachments)
                    {
                        if (attachment is FileAttachment)
                        {
                            FileAttachment fileAttachment = attachment as FileAttachment;

                            // Load the file attachment into memory and print out its file name.
                            fileAttachment.Load();
                            var  filename = fileAttachment.Name;
                            bool b;
                            b = filename.Contains(".xlsx");

                            if (b == true)
                            {
                                bool a;
                                bool k;
                                a = filename.Contains("Fields");
                                k = filename.Contains("MaterialID");

                                if (a == true || k == true)
                                {
                                    var theStream = new FileStream("C:\\data\\kittu1\\" + fileAttachment.Name, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                                    fileAttachment.Load(theStream);
                                    theStream.Close();
                                    theStream.Dispose();
                                }
                            }
                        }
                        else // Attachment is an item attachment.
                        {
                            // Load attachment into memory and write out the subject.
                            ItemAttachment itemAttachment = attachment as ItemAttachment;
                            itemAttachment.Load();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error Occured" + e.Message);
            }
            Console.WriteLine("Success");
            Console.ReadLine();
        }
Exemplo n.º 12
0
        public void getEmailsAndSave(string uri, string username, string password, List <string> exchangeMailList, string savePath)
        {
            //Uri V = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");

            ExchangeService exchange = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
            Uri             V        = new Uri(uri);

            exchange.Url         = V;
            exchange.Credentials = new WebCredentials(username, password);
            bool hit = false;
            int  i   = 0;

            if (exchange != null)
            {
                Console.WriteLine("Connected to mailbox\n");
                FindItemsResults <Item> result = exchange.FindItems(WellKnownFolderName.Inbox, new ItemView(100));
                Console.WriteLine("Looping through emails");
                foreach (Item item in result)
                {
                    EmailMessage message = EmailMessage.Bind(exchange, item.Id);
                    try
                    {
                        if (exchangeMailList.Contains(message.Sender.Address.ToString()) && message.IsRead == false)
                        {
                            Console.WriteLine("hit!");
                            i++;
                            Directory.CreateDirectory(savePath + "\\" + i);

                            File.WriteAllText(savePath + "\\" + i + @"\Subject.txt", message.Subject.ToString());
                            File.WriteAllText(savePath + "\\" + i + @"\Body.txt", message.Body.Text.ToString());
                            File.WriteAllText(savePath + "\\" + i + @"\Id.txt", message.Id.ToString());

                            foreach (Attachment attachment in message.Attachments)
                            {
                                if (attachment is FileAttachment)
                                {
                                    FileAttachment fileAttachment = attachment as FileAttachment;
                                    // Load the attachment into a file.
                                    // This call results in a GetAttachment call to EWS.
                                    fileAttachment.Load(savePath + "\\" + i + "\\" + fileAttachment.Name);

                                    Console.WriteLine("File attachment name: " + fileAttachment.Name);
                                }
                                else // Attachment is an item attachment.
                                {
                                    ItemAttachment itemAttachment = attachment as ItemAttachment;
                                    // Load attachment into memory and write out the subject.
                                    // This does not save the file like it does with a file attachment.
                                    // This call results in a GetAttachment call to EWS.
                                    itemAttachment.Load();
                                    Console.WriteLine("Item attachment name: " + itemAttachment.Name);
                                }
                            }
                            mailHit = true;
                        }
                    }
                    catch (System.NullReferenceException)
                    {
                        Console.WriteLine("This message does not containt a subject");
                    }
                }
            }
        }
Exemplo n.º 13
0
        public static void GetMails()
        {
            try
            {
                //TimeSpan ts = new TimeSpan(0, -1, 0, 0);
                TimeSpan ts   = new TimeSpan(0, 0, -5, 0);
                DateTime date = DateTime.Now.Add(ts);
                //ExchangeService exchange = new ExchangeService(ExchangeVersion.Exchange2010);
                ExchangeService exchange = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
                //exchange.Credentials = new WebCredentials("Domain\\Username", @"Password");
                exchange.Credentials = new WebCredentials("Domain\\myusername", @"mypassword");
                //Uri - https://mail.comanyname.com/EWS/Exchange.asmx
                exchange.Url          = new Uri("https://mail.uhc.com/EWS/Exchange.asmx");
                exchange.TraceEnabled = true;
                exchange.TraceFlags   = TraceFlags.All;
                exchange.AutodiscoverUrl("*****@*****.**", RedirectionCallback);
                SearchFilter.IsGreaterThanOrEqualTo filter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, date);
                Service1.Log("calling service");
                FindItemsResults <Item> findResults = exchange.FindItems(WellKnownFolderName.Inbox, filter, new ItemView(50));

                bool RedirectionCallback(string url)
                {
                    return(url.ToLower().StartsWith("https://"));
                }
                foreach (Item item in findResults.Items)
                {
                    GetAttachmentsFromEmail(exchange, item.Id, item.Subject);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
                Service1.Log(ex.Message);
            }
            void GetAttachmentsFromEmail(ExchangeService service, ItemId itemId, String subject)
            {
                // Bind to an existing message item and retrieve the attachments collection.
                // This method results in an GetItem call to EWS.
                EmailMessage message = EmailMessage.Bind(service, itemId, new PropertySet(ItemSchema.Attachments));

                // Iterate through the attachments collection and load each attachment.

                Service1.Log("Downloading attachments");
                foreach (Attachment attachment in message.Attachments)
                {
                    if (attachment is FileAttachment)
                    {
                        FileAttachment fileAttachment = attachment as FileAttachment;
                        // fileAttachment.Load("Put mails attachments" + fileAttachment.Name);
                        fileAttachment.Load("C:\\MailAttachments\\" + fileAttachment.Name);
                        //System.IO.FileInfo fi = new System.IO.FileInfo("C:\\Mails\\" + fileAttachment.Name);
                        //if (fi.Exists)
                        //{
                        //    // Move file with a new name. Hence renamed.
                        //    fi.MoveTo(@"C:\\Mails\\" + subject);
                        //    Console.WriteLine("File Renamed.");
                        //}
                        Console.WriteLine("File attachment name: " + fileAttachment.Name);
                    }
                    else // Attachment is an item attachment.
                    {
                        ItemAttachment itemAttachment = attachment as ItemAttachment;
                        // Load attachment into memory and write out the subject.
                        // This does not save the file like it does with a file attachment.
                        // This call results in a GetAttachment call to EWS.
                        itemAttachment.Load();
                        Console.WriteLine("Item attachment name: " + itemAttachment.Name);
                        Service1.Log("Item attachment name: " + itemAttachment.Name);
                    }
                }
            }
        }