Exemplo n.º 1
0
        public async Task DeleteMail(string mailId)
        {
            mailId = HttpUtility.UrlDecode(mailId);
            mailId = mailId.Replace(' ', '+');
            EmailMessage mail = await EmailMessage.Bind(this._exchangeService, new ItemId(mailId), PropertySet.IdOnly);

            await mail.Delete(DeleteMode.MoveToDeletedItems);
        }
        /// <summary>
        /// Deletes a single item in a call to EWS.
        /// </summary>
        /// <param name="service">An ExchangeService object with credentials and the EWS URL.</param>
        private static void DeleteAnItem(ExchangeService service)
        {
            // Create an item to be deleted. You can delete any item type in your Exchange mailbox.
            // You will need to save these items to your Exchange mailbox before they can be deleted.
            EmailMessage email1 = new EmailMessage(service);

            email1.Subject = "Draft email one";
            email1.Body    = new MessageBody(BodyType.Text, "Draft body of the mail.");

            EmailMessage email2 = new EmailMessage(service);

            email2.Subject = "Draft email two";
            email1.Body    = new MessageBody(BodyType.Text, "Draft body of the mail.");

            Collection <EmailMessage> messages = new Collection <EmailMessage>();

            messages.Add(email1);
            messages.Add(email2);

            try
            {
                // This results in a CreateItem call to EWS. The items are created on the server.
                // The response contains the item identifiers of the newly created items. The items on the client
                // now have item identifiers. You need the identifiers to delete the item.
                ServiceResponseCollection <ServiceResponse> responses = service.CreateItems(messages, WellKnownFolderName.Drafts, MessageDisposition.SaveOnly, null);

                if (responses.OverallResult == ServiceResult.Success)
                {
                    Console.WriteLine("Successfully created items to be copied.");
                }
                else
                {
                    throw new Exception("The batch creation of the email message draft items was not successful.");
                }
            }
            catch (ServiceResponseException ex)
            {
                Console.WriteLine("Error: {0}", ex.Message);
            }

            try
            {
                // You can delete a single item. Both of the following lines will result in a DeleteItem operation call to EWS.
                // The email message to delete must be saved on the server before you can delete it.
                email1.Delete(DeleteMode.HardDelete);
                email2.Delete(DeleteMode.HardDelete);
            }

            catch (ServiceResponseException ex)
            {
                Console.WriteLine("Error: {0}", ex.Message);
            }
        }
 public void ExcluirEmail(EmailMessage mail)
 {
     try
     {
         DeleteMode delete = DeleteMode.MoveToDeletedItems;
         mail.Delete(delete);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex);
     }
 }
Exemplo n.º 4
0
        public void Delete(GXMailServiceSession sessionInfo, GXMailMessage gxmessage)
        {
            if (_service == null)
            {
                HandleError(2);
                return;
            }

            EmailMessage msg = GetEmailWithId(gxmessage.MessageId);
            if (msg != null)
            {
                msg.Delete(DeleteMode.MoveToDeletedItems);
            }
        }
Exemplo n.º 5
0
 /// <summary>
 /// Delete Emails choosen by the user.
 /// </summary>
 /// <param name="message">E-mail Message</param>
 /// <param name="index">Index Message Possition</param>
 /// <param name="service">EWS Service</param>
 public static void DeleteFunction(EmailMessage message, Int32 index, ExchangeService service)
 {
     try
     {
         Form1.GlobalAccess.Invoke(new Action(() =>
         {
             Form1.GlobalAccess.mailTree.Nodes.RemoveAt(index);
             mailMessages.RemoveAt(index);
             Form1.GlobalAccess.mailTree.SelectedNode = null;
             Form1.GlobalAccess.mailBrowser.DocumentText = null;
         }));
         EmailMessage msg = EmailMessage.Bind(service, message.Id);
         msg.Delete(DeleteMode.MoveToDeletedItems);
         msg.Update(ConflictResolutionMode.AlwaysOverwrite);
     }
     catch
     {
         //En ocaciones, si se borran muchos emails consecutivamente y se da refresh al inbox rapidamente, causa un crash porque el servidor encuentra el email que ordenamos borrar y mientras esta
         //Iterando es borrado, causando un crash. Lo mejor es unicamente ignorar la excepción, el programa seguira trabajando bien.
     }
 }
Exemplo n.º 6
0
        private async Task ProcessEmail(EmailMessage emailMessage)
        {
            if (false == monitorMailbox)
            {
                logger.Info("Monitoring has been stopped, exiting message processing...");
                return;
            }

            if (null != ProcessEmailEventHandler)
            {
                try
                {
                    logger.InfoFormat(
                        "Delegating email message with subject [{0}] processing to client...",
                        emailMessage.Subject);

                    var email = await ConvertEmailMessage(emailMessage);

                    var deleteEmail = ProcessEmailEventHandler(email);

                    if (deleteEmail)
                    {
                        emailMessage.Delete(DeleteMode.SoftDelete);
                        logger.DebugFormat("Processed email message [{0}] deleted.", emailMessage.Subject);
                    }
                }
                catch (Exception ex)
                {
                    logger.ErrorFormat(
                        ex,
                        "An exception occurred processing item [{0}]. Item has been left in the mail box",
                        emailMessage.Subject);
                }
            }
            else
            {
                throw new InvalidProgramException("The ProcessEmailEventHandler has been rendered null.");
            }
        }
Exemplo n.º 7
0
        //gavdcodeend 09

        //gavdcodebegin 10
        static void DeleteOneEmail(ExchangeService ExService)
        {
            SearchFilter myFilter = new SearchFilter.SearchFilterCollection(
                LogicalOperator.And,
                new SearchFilter.IsEqualTo(
                    EmailMessageSchema.Subject,
                    "Email created by EWS"));
            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,
                                                    EmailMessageSchema.Subject, EmailMessageSchema.ParentFolderId);
            EmailMessage emailToDelete = EmailMessage.Bind(ExService, myEmailId, myPropSet);

            emailToDelete.Delete(DeleteMode.SoftDelete);
        }
Exemplo n.º 8
0
 public void Delete()
 {
     _message.Delete(DeleteMode.MoveToDeletedItems);
 }
Exemplo n.º 9
0
        public void Execute(IActivityRequest request, IActivityResponse response)
        {
            userName        = settings.UserName;
            password        = settings.Password;
            domain          = settings.Domain;
            serviceURL      = settings.ServiceUrl;
            exchangeVersion = settings.ExchangeVersion;

            deleteModeChoice = request.Inputs["Delete Mode"].AsString();
            emailID          = request.Inputs["Email ID"].AsString();

            string alternateMailbox = string.Empty;

            if (request.Inputs.Contains("Alternate Mailbox"))
            {
                alternateMailbox = request.Inputs["Alternate Mailbox"].AsString();
            }

            ExchangeService service = new ExchangeService();

            switch (exchangeVersion)
            {
            case "Exchange2007_SP1":
                service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
                break;

            case "Exchange2010":
                service = new ExchangeService(ExchangeVersion.Exchange2010);
                break;

            case "Exchange2010_SP1":
                service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
                break;

            default:
                service = new ExchangeService();
                break;
            }

            service.Credentials = new WebCredentials(userName, password, domain);
            String AccountUrl = userName + "@" + domain;

            if (serviceURL.Equals("Autodiscover"))
            {
                service.AutodiscoverUrl(AccountUrl, (a) => { return(true); });
            }
            else
            {
                service.Url = new Uri(serviceURL);
            }

            if (!alternateMailbox.Equals(String.Empty))
            {
                service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, alternateMailbox);
            }

            EmailMessage message = EmailMessage.Bind(service, emailID);

            switch (deleteModeChoice)
            {
            case "Soft Delete":
                message.Delete(DeleteMode.SoftDelete);
                break;

            case "Hard Delete":
                message.Delete(DeleteMode.HardDelete);
                break;

            case "Move To Deleted Items":
                message.Delete(DeleteMode.MoveToDeletedItems);
                break;

            default:
                message.Delete(DeleteMode.HardDelete);
                break;
            }

            response.Publish("Email ID", emailID);
        }
Exemplo n.º 10
0
 private void DeleteEmail(EmailMessage item)
 {
     item.Delete(DeleteMode.HardDelete);
 }
Exemplo n.º 11
0
        static void Main(string[] args)
        {
            if (args.Length < 14)
            {
                ShowUsage();
                Environment.Exit(0);
            }
            ExchangeService service = null;

            if ((args[0] != "-CerValidation"))
            {
                ShowUsage();
                Environment.Exit(0);
            }
            if ((args[1] == "No"))
            {
                ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => { return(true); };
            }
            Console.WriteLine("[+]CerValidation:{0}", args[1]);

            if ((args[2] != "-ExchangeVersion"))
            {
                ShowUsage();
                Environment.Exit(0);
            }
            if ((args[3] == "Exchange2007_SP1"))
            {
                service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
            }
            else if ((args[3] == "Exchange2010"))
            {
                service = new ExchangeService(ExchangeVersion.Exchange2010);
            }
            else if ((args[3] == "Exchange2010_SP1"))
            {
                service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
            }
            else if ((args[3] == "Exchange2010_SP2"))
            {
                service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
            }
            else if ((args[3] == "Exchange2013"))
            {
                service = new ExchangeService(ExchangeVersion.Exchange2013);
            }
            else if ((args[3] == "Exchange2013_SP1"))
            {
                service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
            }
            else
            {
                ShowUsage();
                Environment.Exit(0);
            }
            Console.WriteLine("[+]ExchangeVersion:{0}", args[3]);
            if (args[4] == "-u")
            {
                UserString = args[5];
                Console.WriteLine("[+]User:{0}", args[5]);
                if ((args[6] != "-p"))
                {
                    ShowUsage();
                    Environment.Exit(0);
                }
                PwdString = args[7];
                Console.WriteLine("[+]Password:{0}", args[7]);
                service.Credentials = new WebCredentials(UserString, PwdString);
            }
            else if (args[4] == "-use")
            {
                if (args[5] == "the")
                {
                    if (args[6] == "default")
                    {
                        if (args[7] == "credentials")
                        {
                            service.UseDefaultCredentials = true;
                            Console.WriteLine("[+]Use the default credentials");
                        }
                    }
                }
                else
                {
                    ShowUsage();
                    Environment.Exit(0);
                }
            }
            else
            {
                ShowUsage();
                Environment.Exit(0);
            }
            if ((args[8] == "-ewsPath"))
            {
                Console.WriteLine("[+]ewsPath:{0}", args[9]);
                ewsPathString = args[9];
                try
                {
                    service.Url = new Uri(ewsPathString);
                }
                catch (Exception e)
                {
                    Console.WriteLine("{0}", e.Message);
                    Environment.Exit(0);
                }
            }
            else if ((args[8] == "-AutodiscoverUrl"))
            {
                Console.WriteLine("[+]AutodiscoverUrl:{0}", args[9]);
                AutodiscoverUrlString = args[9];
                try
                {
                    service.AutodiscoverUrl(AutodiscoverUrlString, RedirectionUrlValidationCallback);
                }
                catch (Exception e)
                {
                    Console.WriteLine("{0}", e.Message);
                    Environment.Exit(0);
                }
            }
            else
            {
                ShowUsage();
                Environment.Exit(0);
            }
            if ((args[10] != "-Mode"))
            {
                ShowUsage();
                Environment.Exit(0);
            }

            if ((args[11] == "ListMail"))
            {
                Console.WriteLine("[+]Mode:{0}", args[11]);
                try
                {
                    ItemView    view            = new ItemView(int.MaxValue);
                    PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties);
                    itempropertyset.RequestedBodyType = BodyType.Text;
                    view.PropertySet = itempropertyset;
                    if ((args[12] != "-Folder"))
                    {
                        ShowUsage();
                        Environment.Exit(0);
                    }
                    FindItemsResults <Item> findResults = null;
                    FolderString = args[13];
                    Console.WriteLine("[+]Folder:{0}", args[13]);
                    if (args[13] == "Inbox")
                    {
                        findResults = service.FindItems(WellKnownFolderName.Inbox, view);
                    }
                    else if (args[13] == "Outbox")
                    {
                        findResults = service.FindItems(WellKnownFolderName.Outbox, view);
                    }
                    else if (args[13] == "DeletedItems")
                    {
                        findResults = service.FindItems(WellKnownFolderName.DeletedItems, view);
                    }
                    else if (args[13] == "Drafts")
                    {
                        findResults = service.FindItems(WellKnownFolderName.Drafts, view);
                    }
                    else if (args[13] == "SentItems")
                    {
                        findResults = service.FindItems(WellKnownFolderName.SentItems, view);
                    }
                    else if (args[13] == "JunkEmail")
                    {
                        findResults = service.FindItems(WellKnownFolderName.JunkEmail, view);
                    }
                    else
                    {
                        ShowUsage();
                        Environment.Exit(0);
                    }
                    foreach (Item item in findResults.Items)
                    {
                        Console.WriteLine("\r\n");
                        if (item.Subject != null)
                        {
                            Console.WriteLine("[*]Subject:{0}", item.Subject);
                        }
                        else
                        {
                            Console.WriteLine("[*]Subject:<null>");
                        }
                        Console.WriteLine("[*]HasAttachments:{0}", item.HasAttachments);
                        if (item.HasAttachments)
                        {
                            EmailMessage message = EmailMessage.Bind(service, item.Id, new PropertySet(ItemSchema.Attachments));
                            foreach (Attachment attachment in message.Attachments)
                            {
                                FileAttachment fileAttachment = attachment as FileAttachment;
                                fileAttachment.Load();
                                Console.WriteLine(" - Attachments:{0}", fileAttachment.Name);
                            }
                        }
                        Console.WriteLine("[*]ItemId:{0}", item.Id);
                        Console.WriteLine("[*]DateTimeCreated:{0}", item.DateTimeCreated);
                        Console.WriteLine("[*]DateTimeReceived:{0}", item.DateTimeReceived);
                        Console.WriteLine("[*]DateTimeSent:{0}", item.DateTimeSent);
                        Console.WriteLine("[*]DisplayCc:{0}", item.DisplayCc);
                        Console.WriteLine("[*]DisplayTo:{0}", item.DisplayTo);
                        Console.WriteLine("[*]InReplyTo:{0}", item.InReplyTo);
                        Console.WriteLine("[*]Size:{0}", item.Size);
                        item.Load(itempropertyset);
                        if (item.Body.ToString().Length > 100)
                        {
                            item.Body = item.Body.ToString().Substring(0, 100);
                            Console.WriteLine("[*]MessageBody(too big,only output 100):{0}", item.Body);
                        }
                        else
                        {
                            Console.WriteLine("[*]MessageBody:{0}", item.Body);
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("[!]{0}", e.Message);
                    Environment.Exit(0);
                }
            }

            else if ((args[11] == "ListUnreadMail"))
            {
                Console.WriteLine("[+]Mode:{0}", args[11]);
                try
                {
                    SearchFilter sf              = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false);
                    ItemView     view            = new ItemView(int.MaxValue);
                    PropertySet  itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties);
                    itempropertyset.RequestedBodyType = BodyType.Text;
                    view.PropertySet = itempropertyset;
                    if ((args[12] != "-Folder"))
                    {
                        ShowUsage();
                        Environment.Exit(0);
                    }
                    FindItemsResults <Item> findResults = null;
                    FolderString = args[13];
                    Console.WriteLine("[+]Folder:{0}", args[13]);
                    if (args[13] == "Inbox")
                    {
                        findResults = service.FindItems(WellKnownFolderName.Inbox, sf, view);
                    }
                    else if (args[13] == "Outbox")
                    {
                        findResults = service.FindItems(WellKnownFolderName.Outbox, sf, view);
                    }
                    else if (args[13] == "DeletedItems")
                    {
                        findResults = service.FindItems(WellKnownFolderName.DeletedItems, sf, view);
                    }
                    else if (args[13] == "Drafts")
                    {
                        findResults = service.FindItems(WellKnownFolderName.Drafts, sf, view);
                    }
                    else if (args[13] == "SentItems")
                    {
                        findResults = service.FindItems(WellKnownFolderName.SentItems, sf, view);
                    }
                    else if (args[13] == "JunkEmail")
                    {
                        findResults = service.FindItems(WellKnownFolderName.JunkEmail, sf, view);
                    }
                    else
                    {
                        ShowUsage();
                        Environment.Exit(0);
                    }
                    foreach (Item item in findResults.Items)
                    {
                        Console.WriteLine("\r\n");
                        EmailMessage email = EmailMessage.Bind(service, item.Id);
                        if (email.Subject != null)
                        {
                            Console.WriteLine("[*]Subject:{0}", email.Subject);
                        }
                        else
                        {
                            Console.WriteLine("[*]Subject:<null>");
                        }
                        Console.WriteLine("[*]HasAttachments:{0}", email.HasAttachments);
                        if (email.HasAttachments)
                        {
                            EmailMessage message = EmailMessage.Bind(service, email.Id, new PropertySet(ItemSchema.Attachments));
                            foreach (Attachment attachment in message.Attachments)
                            {
                                FileAttachment fileAttachment = attachment as FileAttachment;
                                fileAttachment.Load();
                                Console.WriteLine(" - Attachments:{0}", fileAttachment.Name);
                            }
                        }
                        Console.WriteLine("[*]ItemId:{0}", email.Id);
                        Console.WriteLine("[*]DateTimeCreated:{0}", email.DateTimeCreated);
                        Console.WriteLine("[*]DateTimeReceived:{0}", email.DateTimeReceived);
                        Console.WriteLine("[*]DateTimeSent:{0}", email.DateTimeSent);
                        Console.WriteLine("[*]DisplayCc:{0}", email.DisplayCc);
                        Console.WriteLine("[*]DisplayTo:{0}", email.DisplayTo);
                        Console.WriteLine("[*]InReplyTo:{0}", email.InReplyTo);
                        Console.WriteLine("[*]Size:{0}", item.Size);
                        email.Load(itempropertyset);
                        if (email.Body.ToString().Length > 100)
                        {
                            email.Body = email.Body.ToString().Substring(0, 100);
                            Console.WriteLine("[*]MessageBody(too big,only output 100):{0}", email.Body);
                        }
                        else
                        {
                            Console.WriteLine("[*]MessageBody:{0}", email.Body);
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("[!]{0}", e.Message);
                    Environment.Exit(0);
                }
            }

            if ((args[11] == "ListFolder"))
            {
                Console.WriteLine("[+]Mode:{0}", args[11]);
                try
                {
                    if ((args[12] != "-Folder"))
                    {
                        ShowUsage();
                        Environment.Exit(0);
                    }
                    FolderString = args[13];
                    Console.WriteLine("[+]Folder:{0}", args[13]);

                    FindFoldersResults findResults = null;
                    FolderView         view        = new FolderView(int.MaxValue)
                    {
                        Traversal = FolderTraversal.Deep
                    };

                    if (args[13] == "Inbox")
                    {
                        findResults = service.FindFolders(WellKnownFolderName.Inbox, view);
                    }
                    else if (args[13] == "Outbox")
                    {
                        findResults = service.FindFolders(WellKnownFolderName.Outbox, view);
                    }
                    else if (args[13] == "DeletedItems")
                    {
                        findResults = service.FindFolders(WellKnownFolderName.DeletedItems, view);
                    }
                    else if (args[13] == "Drafts")
                    {
                        findResults = service.FindFolders(WellKnownFolderName.Drafts, view);
                    }
                    else if (args[13] == "SentItems")
                    {
                        findResults = service.FindFolders(WellKnownFolderName.SentItems, view);
                    }
                    else if (args[13] == "JunkEmail")
                    {
                        findResults = service.FindFolders(WellKnownFolderName.JunkEmail, view);
                    }
                    else
                    {
                        ShowUsage();
                        Environment.Exit(0);
                    }
                    foreach (Folder folder in findResults.Folders)
                    {
                        Console.WriteLine("\r\n");
                        Console.WriteLine("[*]DisplayName:{0}", folder.DisplayName);
                        Console.WriteLine("[*]Id:{0}", folder.Id);
                        Console.WriteLine("[*]TotalCount:{0}", folder.TotalCount);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("[!]{0}", e.Message);
                    Environment.Exit(0);
                }
            }

            else if ((args[11] == "ListMailofFolder"))
            {
                Console.WriteLine("[+]Mode:{0}", args[11]);
                try
                {
                    if ((args[12] != "-Id"))
                    {
                        ShowUsage();
                        Environment.Exit(0);
                    }
                    IdString = args[13];
                    Console.WriteLine("[+]Id:{0}", args[13]);

                    Folder Folders = Folder.Bind(service, IdString);
                    FindItemsResults <Item> findResults = null;
                    ItemView    view            = new ItemView(int.MaxValue);
                    PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties);
                    itempropertyset.RequestedBodyType = BodyType.Text;
                    view.PropertySet = itempropertyset;
                    findResults      = Folders.FindItems(view);
                    foreach (Item item in findResults.Items)
                    {
                        Console.WriteLine("\r\n");
                        if (item.Subject != null)
                        {
                            Console.WriteLine("[*]Subject:{0}", item.Subject);
                        }
                        else
                        {
                            Console.WriteLine("[*]Subject:<null>");
                        }

                        Console.WriteLine("[*]HasAttachments:{0}", item.HasAttachments);
                        if (item.HasAttachments)
                        {
                            EmailMessage message = EmailMessage.Bind(service, item.Id, new PropertySet(ItemSchema.Attachments));
                            foreach (Attachment attachment in message.Attachments)
                            {
                                FileAttachment fileAttachment = attachment as FileAttachment;
                                fileAttachment.Load();
                                Console.WriteLine(" - Attachments:{0}", fileAttachment.Name);
                            }
                        }
                        Console.WriteLine("[*]ItemId:{0}", item.Id);
                        Console.WriteLine("[*]DateTimeCreated:{0}", item.DateTimeCreated);
                        Console.WriteLine("[*]DateTimeReceived:{0}", item.DateTimeReceived);
                        Console.WriteLine("[*]DateTimeSent:{0}", item.DateTimeSent);
                        Console.WriteLine("[*]DisplayCc:{0}", item.DisplayCc);
                        Console.WriteLine("[*]DisplayTo:{0}", item.DisplayTo);
                        Console.WriteLine("[*]InReplyTo:{0}", item.InReplyTo);
                        Console.WriteLine("[*]Size:{0}", item.Size);
                        item.Load(itempropertyset);
                        if (item.Body.ToString().Length > 100)
                        {
                            item.Body = item.Body.ToString().Substring(0, 100);
                            Console.WriteLine("[*]MessageBody(too big,only output 100):{0}", item.Body);
                        }
                        else
                        {
                            Console.WriteLine("[*]MessageBody:{0}", item.Body);
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("[!]{0}", e.Message);
                    Environment.Exit(0);
                }
            }

            else if ((args[11] == "ListUnreadMailofFolder"))
            {
                Console.WriteLine("[+]Mode:{0}", args[11]);
                try
                {
                    if ((args[12] != "-Id"))
                    {
                        ShowUsage();
                        Environment.Exit(0);
                    }
                    IdString = args[13];
                    Console.WriteLine("[+]Id:{0}", args[13]);

                    SearchFilter            sf              = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false);
                    Folder                  Folders         = Folder.Bind(service, IdString);
                    FindItemsResults <Item> findResults     = null;
                    ItemView                view            = new ItemView(int.MaxValue);
                    PropertySet             itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties);
                    itempropertyset.RequestedBodyType = BodyType.Text;
                    view.PropertySet = itempropertyset;
                    findResults      = Folders.FindItems(sf, view);
                    foreach (Item item in findResults.Items)
                    {
                        Console.WriteLine("\r\n");
                        EmailMessage email = EmailMessage.Bind(service, item.Id);
                        if (email.Subject != null)
                        {
                            Console.WriteLine("[*]Subject:{0}", email.Subject);
                        }
                        else
                        {
                            Console.WriteLine("[*]Subject:<null>");
                        }

                        Console.WriteLine("[*]HasAttachments:{0}", email.HasAttachments);
                        if (email.HasAttachments)
                        {
                            EmailMessage message = EmailMessage.Bind(service, email.Id, new PropertySet(ItemSchema.Attachments));
                            foreach (Attachment attachment in message.Attachments)
                            {
                                FileAttachment fileAttachment = attachment as FileAttachment;
                                fileAttachment.Load();
                                Console.WriteLine(" - Attachments:{0}", fileAttachment.Name);
                            }
                        }
                        Console.WriteLine("[*]ItemId:{0}", email.Id);
                        Console.WriteLine("[*]DateTimeCreated:{0}", email.DateTimeCreated);
                        Console.WriteLine("[*]DateTimeReceived:{0}", email.DateTimeReceived);
                        Console.WriteLine("[*]DateTimeSent:{0}", email.DateTimeSent);
                        Console.WriteLine("[*]DisplayCc:{0}", email.DisplayCc);
                        Console.WriteLine("[*]DisplayTo:{0}", email.DisplayTo);
                        Console.WriteLine("[*]InReplyTo:{0}", email.InReplyTo);
                        Console.WriteLine("[*]Size:{0}", email.Size);
                        email.Load(itempropertyset);
                        if (email.Body.ToString().Length > 100)
                        {
                            email.Body = email.Body.ToString().Substring(0, 100);
                            Console.WriteLine("[*]MessageBody(too big,only output 100):{0}", email.Body);
                        }
                        else
                        {
                            Console.WriteLine("[*]MessageBody:{0}", email.Body);
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("[!]{0}", e.Message);
                    Environment.Exit(0);
                }
            }

            else if ((args[11] == "SaveAttachment"))
            {
                Console.WriteLine("[+]Mode:{0}", args[11]);
                try
                {
                    if ((args[12] != "-Id"))
                    {
                        ShowUsage();
                        Environment.Exit(0);
                    }
                    IdString = args[13];
                    Console.WriteLine("[+]Id:{0}", args[13]);
                    EmailMessage message = EmailMessage.Bind(service, IdString, new PropertySet(ItemSchema.Attachments));
                    foreach (Attachment attachment in message.Attachments)
                    {
                        FileAttachment fileAttachment = attachment as FileAttachment;
                        Console.WriteLine("[+]Attachments:{0}", fileAttachment.Name);
                        fileAttachment.Load(fileAttachment.Name);
                        Console.WriteLine("\r\n[+]SaveAttachment success");
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("[!]{0}", e.Message);
                    Environment.Exit(0);
                }
            }

            else if ((args[11] == "AddAttachment"))
            {
                Console.WriteLine("[+]Mode:{0}", args[11]);
                try
                {
                    if ((args[12] != "-Id"))
                    {
                        ShowUsage();
                        Environment.Exit(0);
                    }
                    IdString = args[13];
                    Console.WriteLine("[+]Id:{0}", args[13]);
                    if ((args[14] != "-AttachmentFile"))
                    {
                        ShowUsage();
                        Environment.Exit(0);
                    }
                    Console.WriteLine("[+]AttachmentFile:{0}", args[15]);
                    EmailMessage message = EmailMessage.Bind(service, IdString);
                    message.Attachments.AddFileAttachment(args[15]);
                    message.Update(ConflictResolutionMode.AlwaysOverwrite);
                    Console.WriteLine("\r\n[+]AddAttachment success");
                }
                catch (Exception e)
                {
                    Console.WriteLine("[!]{0}", e.Message);
                    Environment.Exit(0);
                }
            }

            else if ((args[11] == "ClearAllAttachment"))
            {
                Console.WriteLine("[+]Mode:{0}", args[11]);
                try
                {
                    if ((args[12] != "-Id"))
                    {
                        ShowUsage();
                        Environment.Exit(0);
                    }
                    IdString = args[13];
                    Console.WriteLine("[+]Id:{0}", args[13]);
                    EmailMessage message = EmailMessage.Bind(service, IdString, new PropertySet(ItemSchema.Attachments));
                    message.Attachments.Clear();
                    message.Update(ConflictResolutionMode.AlwaysOverwrite);
                    Console.WriteLine("\r\n[+]ClearAllAttachment success");
                }
                catch (Exception e)
                {
                    Console.WriteLine("[!]{0}", e.Message);
                    Environment.Exit(0);
                }
            }

            else if ((args[11] == "DeleteAttachment"))
            {
                Console.WriteLine("[+]Mode:{0}", args[11]);
                try
                {
                    if ((args[12] != "-Id"))
                    {
                        ShowUsage();
                        Environment.Exit(0);
                    }
                    IdString = args[13];
                    Console.WriteLine("[+]Id:{0}", args[13]);
                    if ((args[14] != "-AttachmentFile"))
                    {
                        ShowUsage();
                        Environment.Exit(0);
                    }
                    Console.WriteLine("[+]AttachmentFile:{0}", args[15]);
                    EmailMessage message = EmailMessage.Bind(service, IdString, new PropertySet(ItemSchema.Attachments));
                    foreach (Attachment attachment in message.Attachments)
                    {
                        if (attachment.Name == args[15])
                        {
                            message.Attachments.Remove(attachment);
                            break;
                        }
                    }
                    message.Update(ConflictResolutionMode.AlwaysOverwrite);
                    Console.WriteLine("\r\n[+]DeleteAttachment success");
                }
                catch (Exception e)
                {
                    Console.WriteLine("[!]{0}", e.Message);
                    Environment.Exit(0);
                }
            }

            else if ((args[11] == "DeleteMail"))
            {
                Console.WriteLine("[+]Mode:{0}", args[11]);
                try
                {
                    if ((args[12] != "-Id"))
                    {
                        ShowUsage();
                        Environment.Exit(0);
                    }
                    IdString = args[13];
                    Console.WriteLine("[+]Id:{0}", args[13]);
                    EmailMessage message = EmailMessage.Bind(service, IdString);
                    message.Delete(DeleteMode.SoftDelete);
                    Console.WriteLine("\r\n[+]DeleteMail success");
                }
                catch (Exception e)
                {
                    Console.WriteLine("[!]{0}", e.Message);
                    Environment.Exit(0);
                }
            }

            else if ((args[11] == "SearchMail"))
            {
                Console.WriteLine("[+]Mode:{0}", args[11]);
                try
                {
                    if ((args[12] != "-String"))
                    {
                        ShowUsage();
                        Environment.Exit(0);
                    }
                    SearchString = args[13];
                    Console.WriteLine("[+]SearchString:{0}", args[13]);
                    SearchMail(service, WellKnownFolderName.Inbox, SearchString);
                    SearchMail(service, WellKnownFolderName.Outbox, SearchString);
                    SearchMail(service, WellKnownFolderName.DeletedItems, SearchString);
                    SearchMail(service, WellKnownFolderName.Drafts, SearchString);
                    SearchMail(service, WellKnownFolderName.SentItems, SearchString);
                    SearchMail(service, WellKnownFolderName.JunkEmail, SearchString);
                    Console.WriteLine("\r\n[+]SearchMail done");
                }
                catch (Exception e)
                {
                    Console.WriteLine("[!]{0}", e.Message);
                    Environment.Exit(0);
                }
            }

            else if ((args[11] == "ExportMail"))
            {
                Console.WriteLine("[+]Mode:{0}", args[11]);
                try
                {
                    if ((args[12] != "-Folder"))
                    {
                        ShowUsage();
                        Environment.Exit(0);
                    }
                    IdString = args[13];
                    Console.WriteLine("[+]Folder:{0}", args[13]);
                    Console.WriteLine("[+]SavePath:{0}.eml", args[13]);
                    Folder inbox = null;
                    if (args[13] == "Inbox")
                    {
                        inbox = Folder.Bind(service, WellKnownFolderName.Inbox);
                    }
                    else if (args[13] == "Outbox")
                    {
                        inbox = Folder.Bind(service, WellKnownFolderName.Outbox);
                    }
                    else if (args[13] == "DeletedItems")
                    {
                        inbox = Folder.Bind(service, WellKnownFolderName.DeletedItems);
                    }
                    else if (args[13] == "Drafts")
                    {
                        inbox = Folder.Bind(service, WellKnownFolderName.Drafts);
                    }
                    else if (args[13] == "SentItems")
                    {
                        inbox = Folder.Bind(service, WellKnownFolderName.SentItems);
                    }
                    else if (args[13] == "JunkEmail")
                    {
                        inbox = Folder.Bind(service, WellKnownFolderName.JunkEmail);
                    }
                    else
                    {
                        Console.WriteLine("[!]Don't support this folder");
                        Environment.Exit(0);
                    }
                    ItemView view = new ItemView(int.MaxValue);
                    view.PropertySet = new PropertySet(BasePropertySet.IdOnly);
                    FindItemsResults <Item> results = inbox.FindItems(view);
                    int i = 0;
                    foreach (var item in results)
                    {
                        i++;
                        PropertySet props       = new PropertySet(EmailMessageSchema.MimeContent);
                        var         email       = EmailMessage.Bind(service, item.Id, props);
                        string      emlFileName = args[13] + ".eml";
                        using (FileStream fs = new FileStream(emlFileName, FileMode.Append, FileAccess.Write))
                        {
                            fs.Write(email.MimeContent.Content, 0, email.MimeContent.Content.Length);
                        }
                    }
                    Console.WriteLine("\r\n[+]ExportMail done,total number:{0}", i);
                }
                catch (Exception e)
                {
                    Console.WriteLine("[!]{0}", e.Message);
                    Environment.Exit(0);
                }
            }

            else if ((args[11] == "ViewMail"))
            {
                Console.WriteLine("[+]Mode:{0}", args[11]);
                try
                {
                    if ((args[12] != "-Id"))
                    {
                        ShowUsage();
                        Environment.Exit(0);
                    }
                    IdString = args[13];
                    Console.WriteLine("[+]Id:{0}", args[13]);
                    ViewMail(service, WellKnownFolderName.Inbox, IdString);
                    ViewMail(service, WellKnownFolderName.Outbox, IdString);
                    ViewMail(service, WellKnownFolderName.DeletedItems, IdString);
                    ViewMail(service, WellKnownFolderName.Drafts, IdString);
                    ViewMail(service, WellKnownFolderName.SentItems, IdString);
                    ViewMail(service, WellKnownFolderName.JunkEmail, IdString);
                    Console.WriteLine("\r\n[+]ViewMail done");
                }
                catch (Exception e)
                {
                    Console.WriteLine("[!]{0}", e.Message);
                    Environment.Exit(0);
                }
            }

            else if ((args[11] == "ReadXML"))
            {
                Console.WriteLine("[+]Mode:{0}", args[11]);
                if ((args[12] != "-Path"))
                {
                    ShowUsage();
                    Environment.Exit(0);
                }
                Console.WriteLine("[+]XML path:{0}", args[13]);
                Console.WriteLine("[+]Out path:out.xml");
                StreamReader sendData     = new StreamReader(args[13], Encoding.Default);
                byte[]       sendDataByte = Encoding.UTF8.GetBytes(sendData.ReadToEnd());
                sendData.Close();
                try
                {
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(service.Url);
                    request.Method            = "POST";
                    request.ContentType       = "text/xml";
                    request.ContentLength     = sendDataByte.Length;
                    request.AllowAutoRedirect = false;
                    if (args[4] == "-use")
                    {
                        request.Credentials = CredentialCache.DefaultCredentials;
                    }
                    else
                    {
                        request.Credentials = new NetworkCredential(UserString, PwdString);
                    }

                    Stream requestStream = request.GetRequestStream();
                    requestStream.Write(sendDataByte, 0, sendDataByte.Length);
                    requestStream.Close();

                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        throw new WebException(response.StatusDescription);
                    }
                    Stream       receiveStream = response.GetResponseStream();
                    StreamReader readStream    = new StreamReader(receiveStream, Encoding.UTF8);
                    String       receiveString = readStream.ReadToEnd();
                    response.Close();
                    readStream.Close();
                    StreamWriter receiveData = new StreamWriter("out.xml");
                    receiveData.Write(receiveString);
                    receiveData.Close();
                }

                catch (WebException e)
                {
                    Console.WriteLine("[!]{0}", e.Message);
                    Environment.Exit(0);
                }
                Console.WriteLine("\r\n[+]ReadXML done");
            }
        }
Exemplo n.º 12
0
        static int Main(string[] args)
        {
            string log         = string.Empty;
            string logFileName = string.Join(", ", args);

            LoggingSystem.LogMessageToFile(
                "---Запуск VPNStateConverter", ref log, false, logFileName);
            LoggingSystem.LogMessageToFile(
                "---Возможные результаты работы: 0 - ok, 1 - error, 2 - unknown, -1 parsing error", ref log, false, logFileName);

            int      retValue       = 2;  //0 - ok, 1 - error, 2 - unknown, -1 parsing error
            DateTime?mailCreateDate = null;
            string   vpnAddress     = string.Empty;

            if (args.Length != 1)
            {
                LoggingSystem.LogMessageToFile(
                    "Для запуска необходимо передать один параметр с адресом VPN сервера", ref log, false, logFileName);
                Console.WriteLine(retValue);
                return(retValue);
            }
            else
            {
                vpnAddress = args[0];
            }

            try {
                LoggingSystem.LogMessageToFile(
                    "Подключение к почтовому ящику", ref log, false, logFileName);
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013)
                {
                    Credentials = new WebCredentials(
                        Properties.Settings.Default.UserName,
                        Properties.Settings.Default.UserPassword,
                        Properties.Settings.Default.UserDomain),
                    Url = new Uri(Properties.Settings.Default.EWS)
                };

                LoggingSystem.LogMessageToFile("Проверка папки 'Входящие'", ref log, false, logFileName);
                Folder inbox = Folder.Bind(service, WellKnownFolderName.Inbox);
                if (inbox.TotalCount > 0)
                {
                    ItemView view = new ItemView(inbox.TotalCount)
                    {
                        PropertySet = PropertySet.IdOnly
                    };

                    FindItemsResults <Item> results = service.FindItems(inbox.Id, view);
                    LoggingSystem.LogMessageToFile("Количество писем в папке: " + results.TotalCount, ref log, false, logFileName);

                    foreach (Item item in results.Items)
                    {
                        try {
                            EmailMessage email = EmailMessage.Bind(service, new ItemId(item.Id.UniqueId.ToString()));

                            string topic = email.ConversationTopic;

                            if (!topic.ToLower().Contains(vpnAddress))
                            {
                                continue;
                            }

                            DateTime mailCurrentCreateDate = email.DateTimeCreated;
                            LoggingSystem.LogMessageToFile("Обработка письма: '" + topic +
                                                           "', дата создания: " + mailCurrentCreateDate.ToString(), ref log, false, logFileName);

                            if (((DateTime.Now - mailCurrentCreateDate).TotalHours >= 1) ||
                                (mailCreateDate.HasValue && (mailCreateDate.Value > mailCurrentCreateDate)))
                            {
                                LoggingSystem.LogMessageToFile("Пропуск обработки, время создания устарело", ref log, false, logFileName);
                            }
                            else
                            {
                                retValue       = ParseMailTopic(topic, logFileName);
                                mailCreateDate = mailCurrentCreateDate;
                            }

                            email.Delete(DeleteMode.HardDelete);
                            email.Update(ConflictResolutionMode.AlwaysOverwrite);
                        } catch (Exception e) {
                            LoggingSystem.LogMessageToFile("Возникла ошибка: " +
                                                           e.Message + Environment.NewLine + e.StackTrace, ref log, false, logFileName);
                        }
                    }
                }
                else
                {
                    LoggingSystem.LogMessageToFile("Папка не содержит писем", ref log, false, logFileName);
                }
            } catch (Exception e) {
                LoggingSystem.LogMessageToFile("Возникла ошибка: " +
                                               e.Message + Environment.NewLine + e.StackTrace, ref log, false, logFileName);
            }

            LoggingSystem.LogMessageToFile("===Окончание обработки, возвращаемое значение: " + retValue, ref log, false, logFileName);
            Console.WriteLine(retValue);
            return(retValue);
        }