private bool disposedValue = false; // To detect redundant calls protected async virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). if (_mailFolder != null && _mailFolder.IsOpen) { await _mailFolder.CloseAsync(); } if (_imapClient?.IsConnected == true) { await _imapClient.DisconnectAsync(true); _imapClient.Dispose(); } } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. _lastRetrievedUIds = null; _mailFolder = null; _mailFolders = null; disposedValue = true; } }
private static async Task RunAsync(MailSortConfig config) { var rules = GetRules(config.ConfigFile).ToList(); if (rules.Count == 0) { throw new Exception("No rules found. Please define rules first."); } IEnumerable <Tuple <Func <MimeMessage, bool>, string> > predicatesAndTargetFolders = rules.Where(r => !r.IsCombinationRule) .Select(r => Tuple.Create(BuildPredicate(GetCombinedRules(r, new Queue <MailSortRule>(new[] { r }), rules)), r.TargetFolder)).ToList(); using var imapClient = new ImapClient(); await imapClient.ConnectAsync(config.Host, config.UseSsl?EncryptedImapPort : ImapPort, config.UseSsl).ConfigureAwait(false); await imapClient.AuthenticateAsync(config.Username, config.Password).ConfigureAwait(false); var inbox = imapClient.Inbox; await inbox.OpenAsync(FolderAccess.ReadWrite).ConfigureAwait(false); var summaries = await inbox.FetchAsync(0, -1, MessageSummaryItems.UniqueId | MessageSummaryItems.InternalDate | MessageSummaryItems.Flags); foreach (var summary in summaries) { if (summary.Flags !.Value.HasFlag(MessageFlags.Deleted)) { continue; } var message = await inbox.GetMessageAsync(summary.UniqueId).ConfigureAwait(false); var tuple = predicatesAndTargetFolders.FirstOrDefault(t => t.Item1(message)); if (tuple == null) { continue; } IMailFolder destinationFolder = null !; try { destinationFolder = await imapClient.GetFolderAsync(tuple.Item2).ConfigureAwait(false); } catch (FolderNotFoundException) { var folders = await imapClient.GetFoldersAsync(imapClient.PersonalNamespaces[0]).ConfigureAwait(false); Console.WriteLine($"The folder '{tuple.Item2}' was not found. The following folders are available: {string.Join(", ", folders.Select(f => f.Name))}"); Environment.Exit(1); } await destinationFolder.OpenAsync(FolderAccess.ReadWrite).ConfigureAwait(false); await destinationFolder.AppendAsync(message, summary.Flags !.Value, summary.InternalDate !.Value).ConfigureAwait(false); await destinationFolder.CloseAsync().ConfigureAwait(false); await inbox.OpenAsync(FolderAccess.ReadWrite).ConfigureAwait(false); await inbox.AddFlagsAsync(summary.UniqueId, MessageFlags.Deleted, true).ConfigureAwait(false); } await inbox.CloseAsync(true).ConfigureAwait(false); }