public void DeleteMailFolderShouldThrowIfFolderDoesNotExist()
        {
            var nonExistentFolder = new MailFolder { Id = 102, Name = "nonExistentFolder" };

            Action action = () => this.GetDefaultExchangeServiceProvider().DeleteMailFolder(nonExistentFolder);

            action.ShouldThrow<InvalidOperationException>().And.Message.Should().Be("Folder nonExistentFolder does not exist.");
        }
        static void Main()
        {
            Handle.GET("/Kanban", () => {
                var page = new KanbanPage();

                var messages = Db.SQL<MailMessage>("SELECT m FROM MailMessage m");
                page.KanbanItems.Data = messages;
                foreach (var item in page.KanbanItems) {
                    item.Details = Self.GET("/Kanban/partials/item/" + item.Data.GetObjectID());
                }

                var folders = Db.SQL<MailFolder>("SELECT m FROM MailFolder m");
                foreach (var folder in folders) {
                    var col = page.KanbanColumns.Add();
                    col.StringValue = folder.Name;
                }

                page.Session = new Session(SessionOptions.PatchVersioning);

                return page;
            });

            Handle.GET("/Kanban/partials/item/{?}", (string id) => {
                var page = new KanbanItemPage();
                page.Data = Db.SQL<MailMessage>("SELECT m FROM MailMessage m WHERE ObjectID = ?", id).First;
                return page;
            });

            UriMapping.OntologyMap("/Kanban/partials/item/{?}", "simplified.ring6.chatmessage", null, null);

            if (Db.SQL("SELECT m FROM MailFolder m").First == null) {
                Db.Transact(() => {
                    var inbox = new MailFolder() {
                        Name = "Inbox"
                    };
                    new MailFolder() {
                        Name = "Work in progress"
                    };
                    new MailFolder() {
                        Name = "Done"
                    };
                });
            }
        }
        public static void InitializeProvider(TestContext testContext)
        {
            var serviceEndpoint = Environment.GetEnvironmentVariable("SupaExchangeServiceProviderServiceUrl");
            if (string.IsNullOrEmpty(serviceEndpoint))
            {
                Assert.Inconclusive("SupaExchangeServiceProviderServiceUrl is not set. Please set it to an exchange endpoint. E.g. https://outlook.office365.com/EWS/Exchange.asmx");
            }

            if (string.IsNullOrEmpty(TestUser))
            {
                Assert.Inconclusive("SupaExchangeServiceProviderTestUser is not set. Please set it to the username for exchange endpoint.");
            }

            if (string.IsNullOrEmpty(TestUserPassword))
            {
                Assert.Inconclusive("SupaExchangeServiceProviderTestPassword is not set. Please set it to the password for exchange endpoint.");
            }

            var serviceUrl = new Uri(serviceEndpoint);
            var credential = new NetworkCredential(TestUser, TestUserPassword);
            exchangeServiceProvider = new ExchangeServiceProvider(serviceUrl, credential);

            exchangeService = new ExchangeService(ExchangeVersion.Exchange2013)
                                  {
                                      Credentials = credential,
                                      TraceEnabled = false,
                                      TraceFlags = TraceFlags.All,
                                      Url = serviceUrl
                                  };

            // Create default test folders
            testFolder = exchangeServiceProvider.GetMailFolder(TestFolder, true);

            // Create a test conversation with two emails
            var testClass = new ExchangeServiceProviderTests();
            testClass.CreateMailThreadInTestFolder(
                subject: FirstConversationSubject,
                body: FirstConversationContent,
                recipients: TestUser);

            // AddMailToMailThread(
            // conversationSubject: ExchangeServiceProviderTestsBase.FirstConversationSubject,
            // messageContent: ExchangeServiceProviderTestsBase.FirstConversationSecondEmailContent);
        }
Beispiel #4
0
        private async Task <bool> GetMessageItems(string TargetFolderID)
        {
            // Return false if TotalItemCount is not 0 and we could not get items.
            bool succeed = false;

            try
            {
                var results = await client.Me.MailFolders[TargetFolderID].Messages
                              .OrderByDescending(m => m.ReceivedDateTime)
                              .Take(50)
                              .Select(m => new { m.Id, m.Subject, m.Sender, m.ToRecipients, m.ReceivedDateTime, m.CreatedDateTime, m.SentDateTime })
                              .ExecuteAsync();

                if (results.CurrentPage.Count == 0)
                {
                    // No items in this folder.

                    // Check whether TotalItemCount is 0.

                    IMailFolder mailFolderResults = new MailFolder();

                    try
                    {
                        mailFolderResults = await client.Me.MailFolders[TargetFolderID].ExecuteAsync();
                    }
                    catch (Microsoft.OData.Core.ODataErrorException ex)
                    {
                        // We know that we can't get RSS Feeds folder.
                        // But we can get the folder using DisplayName Filter.

                        if (ex.Error.ErrorCode == "ErrorItemNotFound")
                        {
                            var tempResults = await client.Me.MailFolders
                                              .Where(m => m.DisplayName == targetFolderDisplayName)
                                              .Take(2)
                                              .ExecuteAsync();

                            if (tempResults.CurrentPage.Count != 1)
                            {
                                // We have to get a unique folder.
                                MessageBox.Show(ex.Message, "Office365APIEditor");
                                return(true);
                            }

                            mailFolderResults = tempResults.CurrentPage[0];
                        }
                        else
                        {
                            MessageBox.Show(ex.Error.ErrorCode);
                            return(true);
                        }
                    }

                    if (mailFolderResults.TotalItemCount == 0)
                    {
                        return(true);
                    }
                    else
                    {
                        // TotalItemCount is not 0 but we could not get items.
                        return(false);
                    }
                }

                bool morePages = false;

                do
                {
                    foreach (var item in results.CurrentPage)
                    {
                        // Add new row.
                        string receivedDateTime = (item.ReceivedDateTime != null) ? item.ReceivedDateTime.Value.ToString("yyyy/MM/dd HH:mm:ss") : "";
                        string createdDateTime  = (item.CreatedDateTime != null) ? item.CreatedDateTime.Value.ToString("yyyy/MM/dd HH:mm/ss") : "";
                        string sentDateTime     = (item.SentDateTime != null) ? item.SentDateTime.Value.ToString("yyyy/MM/dd HH:mm:ss") : "";
                        string subject          = (item.Subject != null) ? item.Subject : "";
                        string sender           = (item.Sender != null && item.Sender.EmailAddress != null && item.Sender.EmailAddress.Address != null) ? item.Sender.EmailAddress.Address : "";
                        string recipients       = (item.ToRecipients != null) ? ConvertRecipientsListToString(item.ToRecipients) : "";

                        DataGridViewRow itemRow = new DataGridViewRow();
                        itemRow.Tag = item.Id;
                        itemRow.CreateCells(dataGridView_ItemList, new object[] { subject, sender, recipients, receivedDateTime, createdDateTime, sentDateTime });

                        if (dataGridView_ItemList.InvokeRequired)
                        {
                            dataGridView_ItemList.Invoke(new MethodInvoker(delegate { dataGridView_ItemList.Rows.Add(itemRow); }));
                        }
                        else
                        {
                            dataGridView_ItemList.Rows.Add(itemRow);
                        }
                    }

                    if (results.MorePagesAvailable)
                    {
                        morePages = true;
                        results   = await results.GetNextPageAsync();
                    }
                    else
                    {
                        morePages = false;
                    }
                } while (morePages);

                succeed = true;
            }
            catch (DataServiceClientException ex)
            {
                MessageBox.Show(ex.Message, "Office365APIEditor");
                succeed = true;
            }
            catch (InvalidOperationException ex)
            {
                if (ex.Message == "No row can be added to a DataGridView control that does not have columns. Columns must be added first.")
                {
                    // Because we added columns first, it seems that this window was closed.
                    // Do nothing.
                }
                else
                {
                    MessageBox.Show(ex.Message, "Office365APIEditor");
                }

                succeed = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.GetType().FullName + "\r\n" + ex.Message, "Office365APIEditor");
                succeed = true;

                // TODO: 途中で画面を閉じて Row を追加できない場合。
            }

            return(succeed);
        }
Beispiel #5
0
 public static async Task <IMailFolderChildFoldersCollectionPage> GetChildFolders(MailFolder mailFolder)
 {
     try
     {
         return(await graphClient.Me.MailFolders[mailFolder.Id].ChildFolders.Request().GetAsync());
     }
     catch (ServiceException ex)
     {
         Console.WriteLine($"Error getting child folders: {ex.Message}");
         return(null);
     }
 }
 private async void GetDraftsFolderAsync()
 {
     draftsFolder = await viewerRequestHelper.GetDraftsFolderAsync();
 }
Beispiel #7
0
        public async Task <MailFolder> GetMsgFolderRootAsync()
        {
            // Get the folder ID of the parent folder of parent folder of Inbox.
            // It's MsgFolderRoot.

            if (Util.UseMicrosoftGraphInMailboxViewer)
            {
                try
                {
                    // Top of information store
                    Uri    URL     = new Uri($"https://graph.microsoft.com/v1.0/me/mailfolders/msgfolderroot");
                    string rawJson = await SendGetRequestAsync(URL);

                    var topOfInformationStore = new MailFolder(rawJson);

                    // MsgFolderRoot
                    URL     = new Uri($"https://graph.microsoft.com/v1.0/me/mailfolders/{topOfInformationStore.ParentFolderId}/?$select=id,parentFolderId");
                    rawJson = await SendGetRequestAsync(URL);

                    var msgFolderRoot = new MailFolder(rawJson);

                    return(msgFolderRoot);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            else
            {
                // We can't get the Top of Information Store folder directly.
                // Following operation is available with v1.0 only.
                // https://outlook.office.com/api/v1.0/me/RootFolder

                try
                {
                    // Inbox
                    Uri    URL     = new Uri("https://outlook.office.com/api/v2.0/me/mailfolders/inbox/?$select=id,parentFolderId");
                    string rawJson = await SendGetRequestAsync(URL);

                    var inbox = new MailFolder(rawJson);

                    // Top of information store
                    URL     = new Uri($"https://outlook.office.com/api/v2.0/me/mailfolders/{inbox.ParentFolderId}/?$select=id,parentFolderId");
                    rawJson = await SendGetRequestAsync(URL);

                    var topOfInformationStore = new MailFolder(rawJson);

                    // MsgFolderRoot
                    URL     = new Uri($"https://outlook.office.com/api/v2.0/me/mailfolders/{topOfInformationStore.ParentFolderId}/?$select=id,parentFolderId");
                    rawJson = await SendGetRequestAsync(URL);

                    var msgFolderRoot = new MailFolder(rawJson);

                    return(msgFolderRoot);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
Beispiel #8
0
        /// <summary>
        /// Send message from mailbox a to mailbox b
        /// </summary>
        public static async Task SendMessageFromMailboxAToMailboxB(ExchangeService exchangeServiceA, ExchangeService exchangeServiceB)
        {
            string  messageSubject = Guid.NewGuid().ToString();
            Message message        = new Message(exchangeServiceA)
            {
                Subject = messageSubject,
                Body    = new ItemBody()
                {
                    Content     = "Test message",
                    ContentType = BodyType.Html
                }
            };

            message.ToRecipients = new List <Recipient>
            {
                new Recipient()
                {
                    EmailAddress = new EmailAddress()
                    {
                        Address = AppConfig.MailboxB
                    }
                }
            };

            MailFolder draftFolder = await exchangeServiceA.GetAsync <MailFolder>(
                new EntityPath(WellKnownFolderName.Drafts.ToString(),
                               typeof(MailFolder)));

            await message.SaveAsync(draftFolder);

            await message.Send();

            Thread.Sleep(6000); // allow some time for email to be delivered
            MessageView  messageView   = new MessageView(10);
            SearchFilter subjectFilter = new SearchFilter.IsEqualTo(
                MessageObjectSchema.Subject,
                messageSubject);

            FindItemResults <Message> mailboxBMessages = await exchangeServiceB.FindItems(
                "Inbox",
                messageView,
                subjectFilter);

            Assert.AreEqual(1, mailboxBMessages.TotalCount);
            Message msg = mailboxBMessages.Items[0];
            await msg.Reply("this is my reply");

            Thread.Sleep(8000); // allow some time for email to be delivered

            subjectFilter = new SearchFilter.IsEqualTo(
                MessageObjectSchema.Subject,
                $"Re: {messageSubject}");

            FindItemResults <Message> mailboxAMessages = await exchangeServiceA.FindItems(
                "Inbox",
                messageView,
                subjectFilter);

            Assert.IsTrue(mailboxAMessages.TotalCount == 1);

            await mailboxAMessages.Items[0].DeleteAsync();
        }
Beispiel #9
0
        /// <summary>
        /// Sync messages
        /// </summary>
        public static async Task SyncMessages(ExchangeService exchangeService)
        {
            string folderName = "TempSyncFolder";

            await FunctionalTestHelpers.DeleteFolderIfExist(
                folderName,
                exchangeService,
                WellKnownFolderName.MsgFolderRoot);

            MailFolder folder = await FunctionalTestHelpers.CreateFolder(
                folderName,
                exchangeService,
                WellKnownFolderName.MsgFolderRoot);

            for (int i = 0; i < 10; i++)
            {
                await FunctionalTestHelpers.CreateMessage(
                    i,
                    folder,
                    exchangeService);
            }

            string             syncState   = null;
            MessagePropertySet propertySet = new MessagePropertySet();

            propertySet.Add(MessageObjectSchema.ToRecipients);
            ChangeCollection <MessageChange> syncCollection;
            int counter          = 0;
            int numberOfMessages = 0;

            do
            {
                syncCollection = await exchangeService.SyncFolderItems(
                    folder.Id,
                    propertySet,
                    syncState);

                syncState         = syncCollection.SyncState;
                numberOfMessages += syncCollection.TotalCount;
                counter++;

                foreach (MessageChange itemChange in syncCollection.Items)
                {
                    Assert.IsTrue(
                        itemChange.ChangeType == ChangeType.Created);
                }
            } while (syncCollection.MoreAvailable || counter == 4);

            Assert.IsFalse(syncCollection.MoreAvailable);
            Assert.AreEqual(10, numberOfMessages);

            FindItemResults <Message> items = await exchangeService.FindItems(folder.Id, new MessageView(4));

            for (int i = 0; i < items.TotalCount; i++)
            {
                Message msg = items.Items[i];
                if (i < 2)
                {
                    msg.IsRead = false;
                    await msg.UpdateAsync();
                }
                else
                {
                    await msg.DeleteAsync();
                }
            }

            syncCollection = await exchangeService.SyncFolderItems(
                folder.Id,
                propertySet,
                syncState);

            Assert.IsFalse(syncCollection.MoreAvailable);
            Assert.IsTrue(
                syncCollection.TotalCount == 4);

            int changes = syncCollection.Items.Count(i => i.ChangeType == ChangeType.Deleted);

            Assert.AreEqual(
                2,
                changes);

            changes = syncCollection.Items.Count(i => i.ChangeType == ChangeType.Updated);
            Assert.IsTrue(changes == 2);

            await folder.DeleteAsync();
        }
Beispiel #10
0
        public void ApplyFilters(MailMessageData message, MailBoxData mailbox, MailFolder folder,
                                 List <MailSieveFilterData> filters)
        {
            var listAppliedFilters = new List <MailSieveFilterData>();

            if (!filters.Any())
            {
                return;
            }

            foreach (var filter in filters)
            {
                if (!filter.Enabled)
                {
                    continue;
                }

                if (filter.Options.ApplyTo.Folders.Any() &&
                    !filter.Options.ApplyTo.Folders.Contains((int)folder.Folder))
                {
                    continue;
                }

                if (filter.Options.ApplyTo.Mailboxes.Any() &&
                    !filter.Options.ApplyTo.Mailboxes.Contains(mailbox.MailBoxId))
                {
                    continue;
                }

                var appliedCount = filter.Conditions.Count(c =>
                {
                    var success = IsConditionSucceed(c, message);
                    if (success)
                    {
                        Log.InfoFormat("Filter condition succeed -> {0} {1} '{2}'",
                                       Enum.GetName(typeof(ConditionKeyType), c.Key),
                                       Enum.GetName(typeof(ConditionOperationType), c.Operation), c.Value);
                    }
                    return(success);
                });

                switch (filter.Options.MatchMultiConditions)
                {
                case MatchMultiConditionsType.MatchAll:
                case MatchMultiConditionsType.None:
                    if (filter.Conditions.Count == appliedCount)
                    {
                        listAppliedFilters.Add(filter);
                    }
                    else if (appliedCount > 0)
                    {
                        Log.InfoFormat("Skip filter by not match all conditions");
                    }
                    break;

                case MatchMultiConditionsType.MatchAtLeastOne:
                    if (appliedCount > 0)
                    {
                        listAppliedFilters.Add(filter);
                    }
                    break;

                default:
                    Log.Error("Unknown MatchMultiConditionsType");
                    break;
                }

                if (appliedCount > 0 && filter.Options.IgnoreOther)
                {
                    break;
                }
            }

            foreach (var filter in listAppliedFilters)
            {
                foreach (var action in filter.Actions)
                {
                    try
                    {
                        Log.InfoFormat("Apply filter (id={0}) action: '{1}'{2}", filter.Id,
                                       Enum.GetName(typeof(ActionType), action.Action),
                                       action.Action == ActionType.MarkTag || action.Action == ActionType.MoveTo
                                ? " id=" + action.Data
                                : "");

                        ApplyAction(new List <int> {
                            message.Id
                        }, action);
                    }
                    catch (NotFoundFilterDataException ex)
                    {
                        Log.Error(ex.ToString());

                        Log.DebugFormat("Disable filter with id={0}", filter.Id);

                        filter.Enabled = false;
                        Factory.FilterEngine.Update(filter);

                        break;
                    }
                    catch (Exception e)
                    {
                        Log.ErrorFormat("ApplyFilters(filterId = {0}, mailId = {1}) Exception:\r\n{2}\r\n", filter.Id,
                                        message.Id, e.ToString());
                    }
                }
            }
        }
        private static bool TrySaveMail(MailBoxManager manager, MailBox mailbox, MailMessage message, MailFolder folder, string uidl, string md5, ILogger log)
        {
            try
            {
                var folderRestoreId = folder.FolderId == MailFolder.Ids.spam ? MailFolder.Ids.inbox : folder.FolderId;

                var attempt = 1;

                while (attempt < 3)
                {
                    try
                    {
                        message.Id = manager.MailSave(mailbox, message, 0, folder.FolderId, folderRestoreId,
                                                      uidl, md5, true);

                        break;
                    }
                    catch (MySqlException exSql)
                    {
                        if (!exSql.Message.StartsWith("Deadlock found"))
                        {
                            throw;
                        }

                        if (attempt > 2)
                        {
                            throw;
                        }

                        log.Warn("[DEADLOCK] MailSave() try again (attempt {0}/2)", attempt);

                        attempt++;
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                log.Error("TrySaveMail Exception:\r\n{0}\r\n", ex.ToString());
            }

            return(false);
        }
Beispiel #12
0
        private void DoOptionalOperations(MailMessageData message, MimeMessage mimeMessage, MailBoxData mailbox, MailFolder folder, ILog log)
        {
            var factory = new EngineFactory(mailbox.TenantId, mailbox.UserId, log);

            var tagIds = new List <int>();

            if (folder.Tags.Any())
            {
                log.Debug("DoOptionalOperations->GetOrCreateTags()");

                tagIds = factory.TagEngine.GetOrCreateTags(mailbox.TenantId, mailbox.UserId, folder.Tags);
            }

            log.Debug("DoOptionalOperations->IsCrmAvailable()");

            if (IsCrmAvailable(mailbox, log))
            {
                log.Debug("DoOptionalOperations->GetCrmTags()");

                var crmTagIds = factory.TagEngine.GetCrmTags(message.FromEmail);

                if (crmTagIds.Any())
                {
                    if (tagIds == null)
                    {
                        tagIds = new List <int>();
                    }

                    tagIds.AddRange(crmTagIds.Select(t => t.Id));
                }
            }

            if (tagIds.Any())
            {
                if (message.TagIds == null || !message.TagIds.Any())
                {
                    message.TagIds = tagIds;
                }
                else
                {
                    message.TagIds.AddRange(tagIds);
                }

                message.TagIds = message.TagIds.Distinct().ToList();
            }

            log.Debug("DoOptionalOperations->AddMessageToIndex()");

            var wrapper = message.ToMailWrapper(mailbox.TenantId, new Guid(mailbox.UserId));

            factory.IndexEngine.Add(wrapper);

            foreach (var tagId in tagIds)
            {
                try
                {
                    log.DebugFormat("DoOptionalOperations->SetMessagesTag(tagId: {0})", tagId);

                    factory.TagEngine.SetMessagesTag(new List <int> {
                        message.Id
                    }, tagId);
                }
                catch (Exception e)
                {
                    log.ErrorFormat(
                        "SetMessagesTag(tenant={0}, userId='{1}', messageId={2}, tagid = {3}) Exception:\r\n{4}\r\n",
                        mailbox.TenantId, mailbox.UserId, message.Id, e.ToString(),
                        tagIds != null ? string.Join(",", tagIds) : "null");
                }
            }

            log.Debug("DoOptionalOperations->AddRelationshipEventForLinkedAccounts()");

            factory.CrmLinkEngine.AddRelationshipEventForLinkedAccounts(mailbox, message, _tasksConfig.DefaultApiSchema);

            log.Debug("DoOptionalOperations->SaveEmailInData()");

            factory.EmailInEngine.SaveEmailInData(mailbox, message, _tasksConfig.DefaultApiSchema);

            log.Debug("DoOptionalOperations->SendAutoreply()");

            factory.AutoreplyEngine.SendAutoreply(mailbox, message, _tasksConfig.DefaultApiSchema, log);

            log.Debug("DoOptionalOperations->UploadIcsToCalendar()");

            factory
            .CalendarEngine
            .UploadIcsToCalendar(mailbox, message.CalendarId, message.CalendarUid, message.CalendarEventIcs,
                                 message.CalendarEventCharset, message.CalendarEventMimeType, mailbox.EMail.Address,
                                 _tasksConfig.DefaultApiSchema);

            if (_tasksConfig.SaveOriginalMessage)
            {
                log.Debug("DoOptionalOperations->StoreMailEml()");
                StoreMailEml(mailbox.TenantId, mailbox.UserId, message.StreamId, mimeMessage, log);
            }

            log.Debug("DoOptionalOperations->ApplyFilters()");

            var filters = GetFilters(factory, log);

            factory.FilterEngine.ApplyFilters(message, mailbox, folder, filters);

            log.Debug("DoOptionalOperations->NotifySignalrIfNeed()");

            NotifySignalrIfNeed(mailbox, log);
        }
Beispiel #13
0
        /// <summary>
        /// This function will display the folder name,
        /// then loop through the child folders, adding nodes as needed
        /// </summary>
        /// <param name="folder">MailFolder object</param>
        public void AddFoldersToTree(MailFolder folder)
        {
            try
            {
                // create the parent node for the folder and set the text
                TreeNode parent = new TreeNode();
                parent.Text = folder.DisplayName;
                tvwFolders.Nodes.Add(parent);

                // check for child folders
                if (folder.ChildFolderCount > 0)
                {
                    // get the child folders collection
                    var childFolders = folder.ChildFolders;
                    TreeNode[] children = new TreeNode[childFolders.Count];

                    // loop the child folders and display 
                    foreach (MailFolder childFolder in childFolders)
                    {
                        // create the child tree node and set the text
                        TreeNode child = new TreeNode();
                        child.Text = childFolder.DisplayName;
                        
                        // since we have a child folder, need to add this id to the dictionary
                        dFolderIds.Add(childFolder.DisplayName, childFolder.Id);
                        
                        // now display the child folder in the tree view
                        parent.Nodes.Add(child);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// Sync messages
        /// </summary>
        public static void SyncMessages(ExchangeService exchangeService)
        {
            string folderName = "TempSyncFolder";

            TestHelpers.DeleteFolderIfExist(
                folderName,
                exchangeService,
                WellKnownFolderName.MsgFolderRoot);

            MailFolder folder = TestHelpers.CreateFolder(
                folderName,
                exchangeService,
                WellKnownFolderName.MsgFolderRoot);

            for (int i = 0; i < 10; i++)
            {
                TestHelpers.CreateMessage(
                    i,
                    folder.FolderId,
                    exchangeService);
            }

            string             syncState   = null;
            MessagePropertySet propertySet = new MessagePropertySet();

            propertySet.AddProperty("ToRecipients");
            SyncFolderItemsCollection <Item> syncCollection;
            int counter          = 0;
            int numberOfMessages = 0;

            do
            {
                syncCollection = exchangeService.SyncFolderItems(
                    folder.FolderId,
                    propertySet,
                    4,
                    syncState);

                syncState         = syncCollection.SyncState;
                numberOfMessages += syncCollection.TotalCount;
                counter++;

                foreach (ItemChange <Item> itemChange in syncCollection)
                {
                    Assert.IsTrue(
                        itemChange.ChangeType == SyncChangeType.Created);
                }
            } while (syncCollection.MoreAvailable || counter == 4);

            Assert.IsFalse(syncCollection.MoreAvailable);
            Assert.AreEqual(10, numberOfMessages);

            FindItemsResults <Item> items = exchangeService.FindItems(folder.FolderId, new MessageView(4));

            for (int i = 0; i < items.TotalCount; i++)
            {
                Message msg = (Message)items.Items[i];
                if (i < 2)
                {
                    msg.IsRead = false;
                    msg.Update();
                }
                else
                {
                    msg.Delete();
                }
            }

            syncCollection = exchangeService.SyncFolderItems(
                folder.FolderId,
                propertySet,
                10,
                syncState);

            Assert.IsFalse(syncCollection.MoreAvailable);
            Assert.IsTrue(
                syncCollection.TotalCount == 4);

            int changes = syncCollection.Items.Count(i => i.ChangeType == SyncChangeType.Deleted);

            Assert.AreEqual(
                2,
                changes);

            changes = syncCollection.Items.Count(i => i.ChangeType == SyncChangeType.ReadFlagChanged);
            Assert.IsTrue(changes == 2);

            folder.Delete();
        }
Beispiel #15
0
			private void Add (TreeIter parent, MailFolder folder)
			{
				TreeIter current = store.AppendValues (parent, folder);
				
				foreach (MailFolder child in folder.Children)
					Add (current, child);
			}
Beispiel #16
0
 public MailClientMessageEventArgs(MimeKit.MimeMessage message, string messageUid, bool uread, MailFolder folder,
                                   MailBox mailBox, ILogger logger)
 {
     Message    = message;
     Unread     = uread;
     Folder     = folder;
     Mailbox    = mailBox;
     MessageUid = messageUid;
     Logger     = logger;
 }
        private async void GetMessageFolderProps(string FolderId, string FolderDisplayName)
        {
            // Get the folder.
            IMailFolder mailFolderResults = new MailFolder();

            try
            {
                mailFolderResults = await client.Me.MailFolders[FolderId].ExecuteAsync();
            }
            catch (Microsoft.OData.Core.ODataErrorException ex)
            {
                // We know that we can't get RSS Feeds folder.
                // But we can get the folder using DisplayName Filter.

                if (ex.Error.ErrorCode == "ErrorItemNotFound")
                {
                    var tempResults = await client.Me.MailFolders
                                      .Where(m => m.DisplayName == FolderDisplayName)
                                      .Take(2)
                                      .ExecuteAsync();

                    if (tempResults.CurrentPage.Count != 1)
                    {
                        // We have to get a unique folder.
                        MessageBox.Show(ex.Message, "Office365APIEditor");
                        return;
                    }

                    mailFolderResults = tempResults.CurrentPage[0];
                }
                else
                {
                    MessageBox.Show(ex.Error.ErrorCode);
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Office365APIEditor");
                return;
            }

            // Add columns.
            dataGridView_FolderProps.Columns.Add("Property", "Property");
            dataGridView_FolderProps.Columns.Add("Value", "Value");
            dataGridView_FolderProps.Columns.Add("Type", "Type");

            // Add rows.

            DataGridViewRow propChildFolderCount = new DataGridViewRow();

            propChildFolderCount.CreateCells(dataGridView_FolderProps, new object[] { "ChildFolderCount", mailFolderResults.ChildFolderCount.Value, mailFolderResults.ChildFolderCount.GetType().ToString() });
            dataGridView_FolderProps.Rows.Add(propChildFolderCount);

            DataGridViewRow propDisplayName = new DataGridViewRow();

            propDisplayName.CreateCells(dataGridView_FolderProps, new object[] { "DisplayName", mailFolderResults.DisplayName, mailFolderResults.DisplayName.GetType().ToString() });
            dataGridView_FolderProps.Rows.Add(propDisplayName);

            DataGridViewRow propId = new DataGridViewRow();

            propId.CreateCells(dataGridView_FolderProps, new object[] { "Id", mailFolderResults.Id, mailFolderResults.Id.GetType().ToString() });
            dataGridView_FolderProps.Rows.Add(propId);

            DataGridViewRow propParentFolderId = new DataGridViewRow();

            propParentFolderId.CreateCells(dataGridView_FolderProps, new object[] { "ParentFolderId", mailFolderResults.ParentFolderId, mailFolderResults.ParentFolderId.GetType().ToString() });
            dataGridView_FolderProps.Rows.Add(propParentFolderId);

            DataGridViewRow propTotalItemCount = new DataGridViewRow();

            propTotalItemCount.CreateCells(dataGridView_FolderProps, new object[] { "TotalItemCount", mailFolderResults.TotalItemCount, mailFolderResults.TotalItemCount.GetType().ToString() });
            dataGridView_FolderProps.Rows.Add(propTotalItemCount);

            DataGridViewRow propUnreadItemCount = new DataGridViewRow();

            propUnreadItemCount.CreateCells(dataGridView_FolderProps, new object[] { "UnreadItemCount", mailFolderResults.UnreadItemCount, mailFolderResults.UnreadItemCount.GetType().ToString() });
            dataGridView_FolderProps.Rows.Add(propUnreadItemCount);
        }
        public static MailMessage Save(MailBox mailbox, MimeMessage mimeMessage, string uid, MailFolder folder, bool unread = true, ILogger log = null)
        {
            if (mailbox == null)
            {
                throw new ArgumentException("mailbox is null", "mailbox");
            }

            if (mimeMessage == null)
            {
                throw new ArgumentException("message is null", "mimeMessage");
            }

            if (uid == null)
            {
                throw new ArgumentException("uidl is null", "uid");
            }

            if (log == null)
            {
                log = new NullLogger();
            }

            var manager = new MailBoxManager(log);

            var fromEmail = mimeMessage.From.Mailboxes.FirstOrDefault();

            var md5 =
                string.Format("{0}|{1}|{2}|{3}",
                              mimeMessage.From.Mailboxes.Any() ? mimeMessage.From.Mailboxes.First().Address : "",
                              mimeMessage.Subject, mimeMessage.Date.UtcDateTime, mimeMessage.MessageId).GetMd5();

            var uidl = mailbox.Imap ? string.Format("{0}-{1}", uid, folder.FolderId) : uid;

            var fromThisMailBox = fromEmail != null &&
                                  fromEmail.Address.ToLowerInvariant()
                                  .Equals(mailbox.EMail.Address.ToLowerInvariant());

            var toThisMailBox =
                mimeMessage.To.Mailboxes.Select(addr => addr.Address.ToLowerInvariant())
                .Contains(mailbox.EMail.Address.ToLowerInvariant());

            List <int> tagsIds = null;

            if (folder.Tags.Any())
            {
                log.Debug("GetOrCreateTags()");

                tagsIds = manager.GetOrCreateTags(mailbox.TenantId, mailbox.UserId, folder.Tags);
            }

            log.Debug("SearchExistingMessagesAndUpdateIfNeeded()");

            var found = manager.SearchExistingMessagesAndUpdateIfNeeded(mailbox, folder.FolderId, uidl, md5,
                                                                        mimeMessage.MessageId, fromThisMailBox, toThisMailBox, tagsIds);

            var needSave = !found;

            if (!needSave)
            {
                return(null);
            }

            log.Debug("DetectChainId()");

            var chainId = manager.DetectChainId(mailbox, mimeMessage.MessageId, mimeMessage.InReplyTo,
                                                mimeMessage.Subject);

            var streamId = MailUtil.CreateStreamId();

            log.Debug("Convert MimeMessage->MailMessage");

            var message = ConvertToMailMessage(mimeMessage, folder, unread, chainId, streamId, log);

            log.Debug("TryStoreMailData()");

            if (!TryStoreMailData(message, mailbox, log))
            {
                return(null);
            }

            log.Debug("MailSave()");

            if (TrySaveMail(manager, mailbox, message, folder, uidl, md5, log))
            {
                return(message);
            }

            if (manager.TryRemoveMailDirectory(mailbox, message.StreamId))
            {
                log.Info("Problem with mail proccessing(Account:{0}). Body and attachment have been deleted", mailbox.EMail);
            }
            else
            {
                throw new Exception("Can't delete mail folder with data");
            }

            return(null);
        }
Beispiel #19
0
        /// <summary>
        /// CRUD operation against extended properties.
        /// </summary>
        /// <param name="exchangeService">Exchange service.</param>
        public static async Task CreateReadUpdateDeleteExtendedProperties(ExchangeService exchangeService)
        {
            const string extendedPropertyGuid = "4d557659-9e3f-405e-8f6d-86d2d9d5c630";
            string       subject = Guid.NewGuid().ToString();
            MailFolder   inbox   = await exchangeService.GetAsync <MailFolder>(new EntityPath("Inbox", typeof(MailFolder)));

            Message msg = new Message(exchangeService);

            msg.Subject = subject;
            msg.SingleValueExtendedProperties.Add(new SingleValueLegacyExtendedProperty()
            {
                Id    = $"String {extendedPropertyGuid} Name Blah",
                Value = "BlahValue"
            });

            msg.MultiValueExtendedProperties.Add(new MultiValueLegacyExtendedProperty()
            {
                Id    = $"StringArray {extendedPropertyGuid} Name BlahArray",
                Value = new List <string>()
                {
                    "A",
                    "B",
                    "C"
                }
            });

            await msg.SaveAsync(inbox);

            MessageView msgView = new MessageView(1);

            msgView.PropertySet.Add(new ExtendedPropertyDefinition(
                                        MapiPropertyType.String,
                                        "Blah",
                                        new Guid(extendedPropertyGuid)));

            msgView.PropertySet.Add(new ExtendedPropertyDefinition(
                                        MapiPropertyType.StringArray,
                                        "BlahArray",
                                        new Guid(extendedPropertyGuid)));

            SearchFilter filter = new SearchFilter.IsEqualTo(
                MessageObjectSchema.Subject,
                subject);

            FindItemResults <Message> findItemsResults = await exchangeService.FindItems(
                WellKnownFolderName.Inbox.ToString(),
                msgView,
                filter);

            foreach (Message item in findItemsResults)
            {
                msg = (Message)item;
                Assert.AreEqual(
                    1,
                    msg.SingleValueExtendedProperties.Count);

                Assert.AreEqual(
                    1,
                    msg.MultiValueExtendedProperties.Count);

                await msg.DeleteAsync();
            }
        }
 public static async Task <MailFolder> EnsureFolder(this IUserRequestBuilder userRequestBuilder, MailFolder parentFolder, string folderName) =>
 await EnsureFolder(userRequestBuilder, parentFolder?.Id, folderName);
Beispiel #21
0
        /// <summary>
        /// Sends the message with extended property.
        /// </summary>
        /// <param name="exchangeServiceA">The exchange service a.</param>
        /// <param name="exchangeServiceB">The exchange service b.</param>
        public static async Task SendMessageWithExtendedProperty(ExchangeService exchangeServiceA, ExchangeService exchangeServiceB)
        {
            string  messageSubject = Guid.NewGuid().ToString();
            Message message        = new Message(exchangeServiceA)
            {
                Subject = messageSubject,
                Body    = new ItemBody()
                {
                    Content     = "Test message",
                    ContentType = BodyType.Html
                }
            };

            message.ToRecipients = new List <Recipient>
            {
                new Recipient()
                {
                    EmailAddress = new EmailAddress()
                    {
                        Address = AppConfig.MailboxB
                    }
                }
            };

            ExtendedPropertyDefinition extendedPropertyDefinition = new ExtendedPropertyDefinition(
                MapiPropertyType.String,
                "MyIdProp",
                Guid.NewGuid());

            string testValue = Guid.NewGuid().ToString();
            SingleValueLegacyExtendedProperty singleValueLegacyExtendedProperty = (SingleValueLegacyExtendedProperty)extendedPropertyDefinition;

            singleValueLegacyExtendedProperty.Value = testValue;
            message.SingleValueExtendedProperties.Add(singleValueLegacyExtendedProperty);

            MailFolder draftFolder = await exchangeServiceA.GetAsync <MailFolder>(
                new EntityPath(WellKnownFolderName.Drafts.ToString(),
                               typeof(MailFolder)));

            await message.SaveAsync(draftFolder);

            await message.Send();

            Thread.Sleep(6000); // allow some time for email to be delivered
            MessageView messageView = new MessageView(10);

            messageView.PropertySet.Expand(extendedPropertyDefinition);

            SearchFilter subjectFilter = new SearchFilter.IsEqualTo(
                MessageObjectSchema.Subject,
                messageSubject);

            FindItemResults <Message> mailboxBMessages = await exchangeServiceB.FindItems(
                "Inbox",
                messageView,
                subjectFilter);

            Assert.AreEqual(
                1,
                mailboxBMessages.TotalCount);

            Assert.AreEqual(
                testValue,
                mailboxBMessages.Items[0].SingleValueExtendedProperties[0].Value);
        }
Beispiel #22
0
 public Message(DataRow row)
 {
     this.row = row;
     this.date = ((DateTime)row["Date"]).Add(DateTime.Now - DataHelper.LastMailDate);
     this.from = string.Format("{0}", row["From"]);
     this.subject = string.Format("{0}", row["Subject"]);
     this.isReply = (bool)row["IsReply"];
     this.hasAttachment = (bool)row["HasAttachment"];
     this.read = Delay > TimeSpan.FromHours(6);
     if(Delay > TimeSpan.FromHours(50) && Delay < TimeSpan.FromHours(100)) read = false;
     this.text = string.Format("{0}", row["Text"]);
     this.deleted = false;
     if(!IsReply)
         priority = 2;
     else
         if(string.IsNullOrEmpty(Folder))
             priority = 0;
     mailType = MailType.Inbox;
     mailFolder = GetFolder(row);
     DataTweaking();
 }
Beispiel #23
0
        public int CreateSampleMessage(
            int?folderId,
            int?mailboxId,
            List <string> to,
            List <string> cc,
            List <string> bcc,
            bool importance,
            bool unread,
            string subject,
            string body,
            string calendarUid   = null,
            DateTime?date        = null,
            List <int> tagIds    = null,
            string fromAddress   = null,
            bool add2Index       = false,
            string mimeMessageId = null,
            uint?userFolderId    = null)
        {
            var folder = folderId.HasValue ? (FolderType)folderId.Value : FolderType.Inbox;

            if (!MailFolder.IsIdOk(folder))
            {
                throw new ArgumentException(@"Invalid folder id", "folderId");
            }

            if (!mailboxId.HasValue)
            {
                throw new ArgumentException(@"Invalid mailbox id", "mailboxId");
            }

            var accounts = _engineFactory.AccountEngine.GetAccountInfoList().ToAccountData().ToList();

            var account = mailboxId.HasValue
                ? accounts.FirstOrDefault(a => a.MailboxId == mailboxId)
                : accounts.FirstOrDefault(a => a.IsDefault) ?? accounts.FirstOrDefault();

            if (account == null)
            {
                throw new ArgumentException("Mailbox not found");
            }

            var mbox = _engineFactory.MailboxEngine.GetMailboxData(
                new СoncreteUserMailboxExp(account.MailboxId, TenantId, Username));

            if (mbox == null)
            {
                throw new ArgumentException("no such mailbox");
            }

            var internalId = string.IsNullOrEmpty(mimeMessageId) ? MailUtil.CreateMessageId() : mimeMessageId;

            var restoreFolder = folder == FolderType.Spam || folder == FolderType.Trash
                ? FolderType.Inbox
                : folder;

            string sampleBody;
            string sampleIntro;

            if (!to.Any())
            {
                to = new List <string> {
                    mbox.EMail.Address
                };
            }

            if (!string.IsNullOrEmpty(body))
            {
                sampleBody  = body;
                sampleIntro = MailUtil.GetIntroduction(body);
            }
            else
            {
                sampleBody  = LOREM_IPSUM_BODY;
                sampleIntro = LOREM_IPSUM_INTRO;
            }

            var sampleMessage = new MailMessage
            {
                Date            = date ?? DateTime.UtcNow,
                MimeMessageId   = internalId,
                MimeReplyToId   = null,
                ChainId         = internalId,
                ReplyTo         = "",
                To              = string.Join(", ", to.ToArray()),
                Cc              = cc.Any() ? string.Join(", ", cc.ToArray()) : "",
                Bcc             = bcc.Any() ? string.Join(", ", bcc.ToArray()) : "",
                Subject         = string.IsNullOrEmpty(subject) ? LOREM_IPSUM_SUBJECT : subject,
                Important       = importance,
                TextBodyOnly    = false,
                Attachments     = new List <MailAttachmentData>(),
                Size            = sampleBody.Length,
                MailboxId       = mbox.MailBoxId,
                HtmlBody        = sampleBody,
                Introduction    = sampleIntro,
                Folder          = folder,
                RestoreFolderId = restoreFolder,
                IsNew           = unread,
                StreamId        = MailUtil.CreateStreamId(),
                CalendarUid     = calendarUid
            };

            if (!string.IsNullOrEmpty(fromAddress))
            {
                var from = Parser.ParseAddress(fromAddress);

                sampleMessage.From      = from.ToString();
                sampleMessage.FromEmail = from.Email;
            }
            else
            {
                sampleMessage.From      = MailUtil.CreateFullEmail(mbox.Name, mbox.EMail.Address);
                sampleMessage.FromEmail = mbox.EMail.Address;
            }

            if (tagIds != null && tagIds.Any())
            {
                sampleMessage.TagIds = tagIds;
            }

            MessageEngine.StoreMailBody(mbox, sampleMessage, Log);

            var id = _engineFactory.MessageEngine.MailSave(mbox, sampleMessage, 0, folder, restoreFolder, userFolderId,
                                                           SAMPLE_UIDL, "", false);

            if (!add2Index)
            {
                return(id);
            }

            var message = _engineFactory.MessageEngine.GetMessage(id, new MailMessageData.Options());

            message.IsNew = unread;

            var wrapper = message.ToMailWrapper(mbox.TenantId, new Guid(mbox.UserId));

            _engineFactory.IndexEngine.Add(wrapper);

            return(id);
        }
Beispiel #24
0
        public static MailMessageData ConvertToMailMessage(this MimeMessage mimeMessage, MailFolder folder, bool unread,
                                                           string chainId, DateTime?chainDate, string streamId, int mailboxId, bool createFailedFake = true, ILog log = null)
        {
            MailMessageData message;

            try
            {
                message = mimeMessage.CreateMailMessage(mailboxId, folder.Folder, unread, chainId, chainDate, streamId, log);
            }
            catch (Exception ex)
            {
                if (!createFailedFake)
                {
                    throw;
                }

                var logger = log ?? new NullLog();

                logger.ErrorFormat("Convert MimeMessage->MailMessage: Exception: {0}", ex.ToString());

                logger.Debug("Creating fake message with original MimeMessage in attachments");

                message = mimeMessage.CreateCorruptedMesage(folder.Folder, unread, chainId, streamId);
            }

            return(message);
        }