示例#1
0
        public void Move(string outputMessage, List <string> targetFolder)
        {
            try
            {
                // Get subfolder
                // Try to create subfolder on error
                IMailFolder currentFolder = Client.GetFolder(Client.PersonalNamespaces[0]);
                foreach (var folder in targetFolder)
                {
                    try
                    {
                        currentFolder = currentFolder.GetSubfolder(folder);
                    }
                    catch (Exception)
                    {
                        currentFolder = currentFolder.Create(folder, true);
                    }
                }

                // Move
                Inbox.MoveTo(Index, currentFolder);
                Inbox.Expunge();

                ConsoleUtils.WriteSuccess(outputMessage);
            }
            catch (Exception e)
            {
                ConsoleUtils.WriteError(e.ToString());
            }
        }
示例#2
0
        private IMailFolder GetSubFolder(IMailFolder folder)
        {
            if (folder.ParentFolder == null)
            {
                return(destinationClient.GetFolder(destinationClient.PersonalNamespaces[0]));
            }

            var p = GetSubFolder(folder.ParentFolder);

            var fs = p.GetSubfolders(false);

            var e = fs.FirstOrDefault(x => x.Name.Equals(folder.Name, StringComparison.OrdinalIgnoreCase));

            if (e != null)
            {
                return(e);
            }

            try {
                return(p.GetSubfolder(folder.Name));
            } catch {
                Console.WriteLine($"Creating {folder.FullName}");
                return(p.Create(folder.Name, true));
            }
        }
示例#3
0
        public async Task <string> RenderAsync(IMailFolder folder, UniqueId uid, BodyPart body)
        {
            var multipart = body as BodyPartMultipart;

            if (multipart != null && body.ContentType.IsMimeType("multipart", "related"))
            {
                return(await RenderMultipartRelatedAsync(folder, uid, multipart).ConfigureAwait(false));
            }

            var text = body as BodyPartText;

            if (multipart != null)
            {
                if (multipart.ContentType.IsMimeType("multipart", "alternative"))
                {
                    for (int i = multipart.BodyParts.Count; i > 0; i--)
                    {
                        if (multipart.BodyParts[i - 1] is BodyPartMultipart multi && multi.ContentType.IsMimeType("multipart", "related"))
                        {
                            if (multi.BodyParts.Count == 0)
                            {
                                continue;
                            }

                            var start = multi.ContentType.Parameters["start"];
                            var root  = multi.BodyParts[0];

                            if (!string.IsNullOrEmpty(start))
                            {
                                root = multi.BodyParts.OfType <BodyPartText>().FirstOrDefault(x => x.ContentId == start);
                            }

                            if (root != null && root.ContentType.IsMimeType("text", "html"))
                            {
                                return(await RenderAsync(folder, uid, multi).ConfigureAwait(false));
                            }

                            continue;
                        }

                        text = multipart.BodyParts[i - 1] as BodyPartText;

                        if (text != null)
                        {
                            return(await RenderTextAsync(folder, uid, text).ConfigureAwait(false));
                        }
                    }
                }
                else if (multipart.BodyParts.Count > 0)
                {
                    return(await RenderAsync(folder, uid, multipart.BodyParts[0]).ConfigureAwait(false));
                }
            }
            else if (text != null)
            {
                return(await RenderTextAsync(folder, uid, text).ConfigureAwait(false));
            }

            return("Uncknown message type.");
        }
示例#4
0
        async void RenderMultipartRelated(IMailFolder folder, UniqueId uid, BodyPartMultipart bodyPart)
        {
            // download the entire multipart/related for simplicity since we'll probably end up needing all of the image attachments anyway...
            var related = await folder.GetBodyPartAsync(uid, bodyPart) as MultipartRelated;

            RenderMultipartRelated(related);
        }
        public static List <Email> GetMails(string username, string password)
        {
            _emails = new List <Email>();
            if (CheckInternet() || System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
            {
                using (var client = new ImapClient())
                {
                    client.Connect("imap.gmail.com", 993, true);
                    client.Authenticate(username, password);
                    //The Inbox folder is always available on all IMAP servers...
                    IMailFolder inbox = client.Inbox;
                    inbox.Open(FolderAccess.ReadOnly);

                    AddEmailsToList(client);

                    client.Disconnect(true);
                    NewBackup(_emails);
                }
            }
            else
            {
                _emails = LoadBackup();
            }

            _emails.Reverse();
            return(_emails);
        }
示例#6
0
        /// <summary>
        /// This method moves emails according to the parameters
        /// </summary>
        /// <param name="operation">argument for MaiMove</param>
        /// <returns>true if processed successfully, false otherwise</returns>
        private bool MailMove(MailSimOperationsMailMove operation)
        {
            // gets the Outlook destination folder
            IMailFolder destinationFolder = olMailStore.GetDefaultFolder(operation.DestinationFolder);

            if (destinationFolder == null)
            {
                Log.Out(Log.Severity.Error, operation.OperationName, "Unable to retrieve folder {0}",
                        operation.DestinationFolder);
                return(false);
            }

            var parsedOp = ParseOperation(operation, operation.SourceFolder, operation.Subject);

            return(parsedOp.Iterate((indexToMove, mails) =>
            {
                var item = mails[indexToMove];
                Log.Out(Log.Severity.Info, operation.OperationName, "Moving to {0}: {1}",
                        operation.DestinationFolder, item.Subject);

                item.Move(destinationFolder);
                mails.RemoveAt(indexToMove);
                return true;
            }));
        }
示例#7
0
        public async void OpenFolder(IMailFolder folder)
        {
            if (this.folder == folder)
            {
                return;
            }

            if (this.folder != null)
            {
                this.folder.MessageFlagsChanged -= MessageFlagsChanged_TaskThread;
                this.folder.MessageExpunged     -= MessageExpunged_TaskThread;
                this.folder.MessagesArrived     -= MessagesArrived_TaskThread;
            }

            // Note: because we are using the *Async() methods, these events will fire
            // in another thread so we'll have to proxy them back to the main thread.
            folder.MessageFlagsChanged += MessageFlagsChanged_TaskThread;
            folder.MessageExpunged     += MessageExpunged_TaskThread;

            this.folder = folder;

            if (folder.IsOpen)
            {
                LoadMessages();
                return;
            }

            await folder.OpenAsync(FolderAccess.ReadOnly);

            LoadMessages();
        }
示例#8
0
        private async void Update()
        {
            IMailFolder inbo = await Task.Run(() => EmailAsync(login, pass));

            lbMail.Content = tbLogin.Text;

            inbo.Open(FolderAccess.ReadOnly);
            progress.Maximum        = inbo.Count;
            lbMail.Content          = login;
            spLog.Visibility        = Visibility.Collapsed;
            gridMainPage.Visibility = Visibility.Visible;

            try
            {
                for (int i = inbo.Count - 1; i >= 0; i--)
                {
                    var message = await inbo.GetMessageAsync(i);

                    letters.Add(new Letter
                    {
                        Sender  = message.From.Mailboxes.First().Name,
                        Date    = message.Date.DateTime.ToString(),
                        Subject = message.Subject,
                        Text    = message.TextBody
                    }
                                );
                    progress.Value++;
                }
            }
            catch { }
            await imap.DisconnectAsync(true);
        }
示例#9
0
        private static bool CompareFolders(IMailFolder f1, IMailFolder f2)
        {
            Func <IMailFolder, bool> isInbox = (f) => f.Attributes.HasFlag(FolderAttributes.Inbox) ||
                                               f.Name.Equals("inbox", StringComparison.InvariantCultureIgnoreCase);

            Func <IMailFolder, bool> isSent = (f) => f.Attributes.HasFlag(FolderAttributes.Sent) ||
                                              f.Name.Equals("sent", StringComparison.InvariantCultureIgnoreCase) ||
                                              f.Name.Equals("sent items", StringComparison.InvariantCultureIgnoreCase);

            Func <IMailFolder, bool> isSpam = (f) => f.Attributes.HasFlag(FolderAttributes.Junk) ||
                                              f.Name.Equals("spam", StringComparison.InvariantCultureIgnoreCase) ||
                                              f.Name.Equals("junk", StringComparison.InvariantCultureIgnoreCase) ||
                                              f.Name.Equals("bulk", StringComparison.InvariantCultureIgnoreCase);

            if (isInbox(f1))
            {
                return(true);
            }

            if (isSent(f1) && !isInbox(f2))
            {
                return(true);
            }

            return(isSpam(f1) && !isInbox(f2) && !isSent(f2));
        }
示例#10
0
        public IList <Tuple <string, string> > GetBasicInfo(string folder, int page, int pageSize)
        {
            List <Tuple <string, string> > Info = new List <Tuple <string, string> >();

            if (!IsAuthenticated())
            {
                return(Info);
            }
            IMailFolder mailFolder = GetFolder(folder);

            mailFolder.Open(FolderAccess.ReadWrite);
            var Items = mailFolder.Fetch((page - 1) * pageSize, pageSize, MessageSummaryItems.UniqueId | MessageSummaryItems.Size | MessageSummaryItems.Flags | MessageSummaryItems.All);

            if (Items == null)
            {
                Items = new List <IMessageSummary>();
            }
            foreach (var mail in (Items as List <MessageSummary>))
            {
                Info.Add(new Tuple <string, string>(mail.NormalizedSubject, mail.Envelope.From[0].Name));
            }

            mailFolder.Close();
            return(Info);
        }
        public FileResult Download(uint Uid, string Name)   //retuns file from message attachments
        {
            IMailFolder folder      = (IMailFolder)Session["folder"];
            UniqueId    uid         = new UniqueId(Uid);
            var         task        = folder.GetMessageAsync(uid);
            var         attachments = task.Result.Attachments;

            foreach (MimeEntity attachment in attachments)
            {
                if (attachment.ContentDisposition.FileName == Name)
                {
                    MemoryStream stream   = new MemoryStream();
                    string       fileType = attachment.ContentType.MimeType;
                    if (attachment is MessagePart)
                    {
                        var part = (MessagePart)attachment;
                        part.Message.WriteTo(stream);
                    }
                    else
                    {
                        var part = (MimePart)attachment;
                        part.Content.DecodeTo(stream);
                    }


                    byte[] file = stream.ToArray();
                    return(File(file, fileType, Name));
                }
            }

            return(null);
        }
示例#12
0
    public static void MoveToFolderImap()
    {
        using (var client = new ImapClient())
        {
            client.Connect(fromClient, fromImapPort, false);

            client.Authenticate(fromEmail, passw);

            // The Inbox folder is always available on all IMAP servers...
            var inbox = client.Inbox;
            inbox.Open(FolderAccess.ReadWrite);

            // Bara för test -------
            //Console.WriteLine("Total messages: {0}", inbox.Count);
            //Console.WriteLine("Recent messages: {0}", inbox.Recent);
            // -------

            var uids = inbox.Search(SearchQuery.All);

            IMailFolder destination = client.GetFolder(moveTo);
            var         uidMap      = inbox.MoveTo(uids, destination);

            client.Disconnect(true);
        }
    }
示例#13
0
		public async void OpenFolder (IMailFolder folder)
		{
			if (this.folder == folder)
				return;

			if (this.folder != null) {
				this.folder.MessageFlagsChanged -= MessageFlagsChanged_TaskThread;
				this.folder.MessageExpunged -= MessageExpunged_TaskThread;
				this.folder.MessagesArrived -= MessagesArrived_TaskThread;
			}

			// Note: because we are using the *Async() methods, these events will fire
			// in another thread so we'll have to proxy them back to the main thread.
			folder.MessageFlagsChanged += MessageFlagsChanged_TaskThread;
			folder.MessageExpunged += MessageExpunged_TaskThread;

			this.folder = folder;

			if (folder.IsOpen) {
				LoadMessages ();
				return;
			}

			await folder.OpenAsync (FolderAccess.ReadOnly);
			LoadMessages ();
		}
示例#14
0
		TreeNode CreateFolderNode (IMailFolder folder)
		{
			var node = new TreeNode (folder.Name) { Tag = folder, ToolTipText = folder.FullName };

			node.NodeFont = new Font (Font, FontStyle.Regular);

			if (folder == Program.Client.Inbox)
				node.SelectedImageKey = node.ImageKey = "inbox";
			else if (folder.Attributes.HasFlag (FolderAttributes.Archive))
				node.SelectedImageKey = node.ImageKey = "archive";
			else if (folder.Attributes.HasFlag (FolderAttributes.Drafts))
				node.SelectedImageKey = node.ImageKey = "drafts";
			else if (folder.Attributes.HasFlag (FolderAttributes.Flagged))
				node.SelectedImageKey = node.ImageKey = "important";
			else if (folder.Attributes.HasFlag (FolderAttributes.Junk))
				node.SelectedImageKey = node.ImageKey = "junk";
			else if (folder.Attributes.HasFlag (FolderAttributes.Sent))
				node.SelectedImageKey = node.ImageKey = "sent";
			else if (folder.Attributes.HasFlag (FolderAttributes.Trash))
				node.SelectedImageKey = node.ImageKey = folder.Count > 0 ? "trash-full" : "trash-empty";
			else
				node.SelectedImageKey = node.ImageKey = "folder";

			if (CheckFolderForChildren (folder))
				node.Nodes.Add ("Loading...");

			return node;
		}
示例#15
0
文件: Extensions.cs 项目: trentet/JAM
 public static void DownloadEmail(this Email email, IMailFolder mailFolder)
 {
     try
     {
         Console.WriteLine("[Downloading Email] {0:D2} ", email.Id);
         var savePath = AppConfig.EmailSaveDirectory + email.Id + ".eml";
         if (!File.Exists(savePath))
         {
             lock (mailFolder.SyncRoot)
             {
                 File.WriteAllText(savePath, mailFolder.GetMessage(email.Id).ToString());
                 Console.WriteLine("[Email Downloaded] {0:D2}: {1}", email.Id, savePath);
             }
         }
         else
         {
             Console.WriteLine("[Download Cancelled] EML {0:D2} Already Exists: {1}", email.Id, savePath);
         }
     }
     catch (Exception e)
     {
         Console.WriteLine("Failed to download email of ID {" + email.Id + "}.");
         Console.WriteLine(e.StackTrace);
         throw;
         //return null;
     }
 }
示例#16
0
        private IEnumerable <IMailFolder> GetImapSubFolders(IMailFolder folder)
        {
            try
            {
                var subfolders = folder.GetSubfolders(true, CancelToken).ToList();

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

                var tempList = new List <IMailFolder>();

                foreach (var subfolder in
                         subfolders.Where(
                             f => f.Attributes.HasFlag(FolderAttributes.HasChildren)))
                {
                    tempList.AddRange(GetImapSubFolders(subfolder));
                }

                subfolders.AddRange(tempList);

                return(subfolders);
            }
            catch (Exception ex)
            {
                Log.Error("GetImapSubFolders: {0} Exception: {1}", folder.Name, ex.Message);
            }

            return(new List <IMailFolder>());
        }
示例#17
0
        /// <summary>
        /// Get the list of emails for a search
        /// </summary>
        /// <param name="args">The search condition followed by the header only and set as seen booleans</param>
        /// <returns>The list of mail message that match the search</returns>
        private List <MimeMessage> GetSearchResults(params object[] args)
        {
            List <MimeMessage> messageList = new List <MimeMessage>();
            IMailFolder        folder      = this.GetCurrentFolder();

            foreach (UniqueId uid in folder.Search((SearchQuery)args[0], default(CancellationToken)))
            {
                if ((bool)args[2])
                {
                    folder.AddFlags(uid, MessageFlags.Seen, true);
                }

                MimeMessage message = null;

                if ((bool)args[1])
                {
                    HeaderList headers = folder.GetHeaders(uid);
                    message = new MimeMessage(headers);
                }
                else
                {
                    message = folder.GetMessage(uid);
                }

                messageList.Add(message);
            }

            return(messageList);
        }
示例#18
0
        private List <UniqueId> GetFolderUids(IMailFolder folder)
        {
            List <UniqueId> allUids;

            try
            {
                allUids = folder.Fetch(0, -1, MessageSummaryItems.UniqueId, CancelToken).Select(r => r.UniqueId).ToList();
            }
            catch (ImapCommandException ex)
            {
                Log.Warn("GetFolderUids() Exception: {0}", ex.ToString());

                const int start     = 0;
                var       end       = folder.Count;
                const int increment = 1;

                allUids = Enumerable
                          .Repeat(start, (end - start) / 1 + 1)
                          .Select((tr, ti) => tr + increment * ti)
                          .Select(n => new UniqueId((uint)n))
                          .ToList();
            }

            return(allUids);
        }
示例#19
0
        /// <summary>
        /// This method retrieves all mails or subject matching mails from the folder
        /// </summary>
        /// <param name="operationName">name of the operation</param>
        /// <param name="folder">folder to retrieve</param>
        /// <param name="subject">case sensitive subject to match</param>
        /// <returns>list of mails if successful, null otherwise</returns>
        private IEnumerable <IMailItem> GetMails(string operationName, string folder, string subject)
        {
            // retrieves the Outlook folder
            IMailFolder mailFolder = olMailStore.GetDefaultFolder(folder);

            if (mailFolder == null)
            {
                Log.Out(Log.Severity.Error, operationName, "Unable to retrieve folder {0}",
                        folder);
                return(Enumerable.Empty <IMailItem>());
            }

            // retrieves the mail items from the folder
            var mails = mailFolder.MailItems;

            if (mails.Any() == false)
            {
                Log.Out(Log.Severity.Error, operationName, "No items in folder {0}", folder);
                return(mails);
            }

            // finds all mail items with matching subject if specified
            subject = subject ?? string.Empty;
            mails   = mails.Where(x => x.Subject.Contains(subject));

            if (mails.Any() == false)
            {
                Log.Out(Log.Severity.Error, operationName, "Unable to find mail with subject {0}",
                        subject);
            }

            return(mails);
        }
        public static async Task VisitChildren(ILogger logger, IMailFolder parent, Func <IMailFolder, int, int, Task <bool> >?visitor)
        {
            if (visitor == null)
            {
                return;
            }

            var subfolders            = parent.GetSubfolders().ToList();
            var subfolderCount        = subfolders.Count;
            var currentSubfolderCount = 0;

            foreach (var subfolder in subfolders)
            {
                try
                {
                    if (!await visitor(subfolder, ++currentSubfolderCount, subfolderCount))
                    {
                        return;
                    }
                } catch (Exception e) when(!(e is OperationCanceledException) && !(e is TaskCanceledException))
                {
                    logger.Error(e, "Exception while visiting child folder '{ChildName}' of parent folder '{FolderFullName}', ignoring and continuing with next child", subfolder.Name, parent.FullName);
                }
            }
        }
示例#21
0
        public static void ListInboxFolders(EmailAccount inboxOwner, ILogger logger)
        {
            using (var client = new ImapClient())
            {
                client.ServerCertificateValidationCallback = (s, c, h, e) => true; // Accept all certificates
                client.Connect(inboxOwner.EmailHost, inboxOwner.ImapPort, useSsl: false);
                client.Authenticate(inboxOwner.EmailAddress, inboxOwner.EmailPassword);

                IMailFolder personal = client.GetFolder(client.PersonalNamespaces[0]);
                foreach (IMailFolder folder in personal.GetSubfolders(false))
                {
                    logger.LogInfo($"[folder] {folder.Name}");
                }

                if ((client.Capabilities & (ImapCapabilities.SpecialUse | ImapCapabilities.XList)) != 0)
                {
                    IMailFolder drafts = client.GetFolder(SpecialFolder.Sent);
                    logger.LogInfo($"[special SENT folder] {drafts.Name}");
                }
                else
                {
                    logger.LogInfo("unable to get special SENT folder");
                }

                client.Disconnect(true);
            }
        }
示例#22
0
        private void CheckImapMail()
        {
            try
            {
                using (ImapClient imapClient = new ImapClient())
                {
                    imapClient.Connect(_configuration.ServerName, _configuration.Port, _configuration.SSL);
                    imapClient.AuthenticationMechanisms.Remove("XOAUTH2");

                    imapClient.Authenticate(_configuration.UserName, _configuration.Password);

                    IMailFolder inbox = imapClient.Inbox;
                    inbox.Open(FolderAccess.ReadWrite);
                    foreach (UniqueId msgUid in inbox.Search(SearchQuery.NotSeen))
                    {
                        MimeMessage msg = inbox.GetMessage(msgUid);
                        ProcessMail(msg);
                        inbox.SetFlags(msgUid, MessageFlags.Seen, true);
                    }
                }
            }
            catch (Exception ex)
            {
                // Sometimes an error occures, e.g. if the network was disconected or a timeout occured.
                Logger.Instance.LogException(this, ex);
            }
        }
示例#23
0
        private void StoreLocal(IMessageSummary msg, IMailFolder folder)
        {
            using (var tx = new TransferContext(conn, false))
            {
                string mid = msg.Headers[HeaderId.MessageId];
                if (mid != null)
                {
                    tx.Messages.Add(new ImapMigration.Message
                    {
                        Url       = DestinationServer.Url,
                        MessageID = mid
                    });
                    tx.SaveChanges();
                    return;
                }

                tx.Messages.Add(new ImapMigration.Message
                {
                    Folder = folder.FullName,
                    Hash   = GetHash(msg),
                    Url    = DestinationServer.Url
                });
                tx.SaveChanges();
            }
        }
        // GET api/<controller>
        public IEnumerable <long> Get(string IMAP, int Port, string Login, string Password)
        {
            List <long> list = new List <long>();

            using (ImapClient client = new ImapClient())
            {
                var context = new ELMA3Entities();
                client.Connect(IMAP, Port, SecureSocketOptions.SslOnConnect);
                client.Authenticate(Login, Password);
                IMailFolder inbox = client.Inbox;
                inbox.Open(FolderAccess.ReadOnly);
                var uids = inbox.Search(SearchQuery.NotSeen);
                foreach (var item in uids)
                {
                    var    message = inbox.GetMessage(item);
                    string a;
                    if (message.HtmlBody != null)
                    {
                        a = message.HtmlBody;
                    }
                    else
                    {
                        a = message.TextBody;
                    }
                    var b = context.CreateEmailMessageI(DateTime.Now.ToString(), DateTime.Now, message.Subject, a, message.Date.UtcDateTime, message.From.FirstOrDefault().Name);
                    list.Add(b.FirstOrDefault().Id);
                }
            }
            return(list.AsEnumerable());
        }
示例#25
0
        void LoadChildFolders(IMailFolder folder, IEnumerable <IMailFolder> children)
        {
            TreeNodeCollection nodes;
            TreeNode           node;

            if (map.TryGetValue(folder, out node))
            {
                nodes = node.Nodes;
                nodes.Clear();
            }
            else
            {
                nodes = Nodes;
            }

            foreach (var child in children)
            {
                node       = CreateFolderNode(child);
                map[child] = node;
                nodes.Add(node);

                // Note: because we are using the *Async() methods, these events will fire
                // in another thread so we'll have to proxy them back to the main thread.
                child.MessageFlagsChanged += UpdateUnreadCount_TaskThread;
                child.CountChanged        += UpdateUnreadCount_TaskThread;

                if (!child.Attributes.HasFlag(FolderAttributes.NonExistent) && !child.Attributes.HasFlag(FolderAttributes.NoSelect))
                {
                    child.StatusAsync(StatusItems.Unread).ContinueWith(task => {
                        Invoke(new UpdateFolderNodeDelegate(UpdateFolderNode), child);
                    });
                }
            }
        }
示例#26
0
        public void GetAllMails(IProgress <MailInfo> progress, [Optional] IMailFolder folder)
        {
            using (ImapClient client = new ImapClient())
            {
                client.Connect(mailServer, port, ssl);
                client.AuthenticationMechanisms.Remove("XOAUTH2");
                client.Authenticate(UserData.Email, UserData.Password);

                if (folder == null)
                {
                    folder = client.Inbox;
                }
                else
                {
                    folder = client.GetFolder(folder.FullName);
                }

                folder.Open(FolderAccess.ReadOnly);
                SearchResults results = folder.Search(SearchOptions.All, SearchQuery.DeliveredAfter(DateFrom));

                if (results.UniqueIds.Count < MaxEmails)
                {
                    MaxEmails = results.UniqueIds.Count;
                }

                for (int i = MaxEmails - 1; i >= 0; i--)
                {
                    MailInfo message = new MailInfo(folder.GetMessage(results.UniqueIds[i]), results.UniqueIds[i], folder);
                    progress.Report(message);
                }

                folder.Close();
                client.Disconnect(true);
            }
        }
示例#27
0
        public List <string> ReceivedFileImap(string SaveToDirectory)
        {
            List <string> file_names = new List <string>();

            using (ImapClient client = new ImapClient())
            {
                client.Connect(IMAPGmailServer, IMAPGmailPort, true);
                client.Authenticate(mailAddress, mailPassword);
                IMailFolder inbox = client.Inbox;
                inbox.Open(FolderAccess.ReadOnly);
                for (int i = 0; i < inbox.Count; i++)
                {
                    MimeMessage message = inbox.GetMessage(i);
                    if (message.Date.Month == DateTime.Now.Month && message.Date.Day == DateTime.Now.Day && message.Date.Year == DateTime.Now.Year)
                    {
                        IEnumerable <MimeEntity> attachments = message.Attachments;
                        foreach (MimeEntity file in attachments)
                        {
                            file_names.Add(SaveToDirectory + file.ContentType.Name);
                            GetFileImap(file, SaveToDirectory);
                        }
                    }
                }
            }
            logger.WriteLog("Get archives from email", LogLevel.Mail);
            return(file_names);
        }
示例#28
0
        public IObservable <LockResult> AcquireLockRetry(IMailFolder folder, string resourceName, int?previousCookie = null, int overallTimeoutSecs = 60, bool agressiveMode = false)
        {
            return(Observable.FromAsync((cancellationToken) => Task.Run(() =>
            {
                var watch = Stopwatch.StartNew();
                while (true)
                {
                    LockResult lockResult;
                    lock (folder.SyncRoot)
                    {
                        lockResult = AcquireLockInternal(folder, resourceName, previousCookie, cancellationToken);
                    }
                    if (lockResult.IsSuccess)
                    {
                        return lockResult;
                    }

                    if (watch.Elapsed.TotalSeconds > overallTimeoutSecs)
                    {
                        return lockResult;
                    }

                    if (!agressiveMode)
                    {
                        Thread.Sleep(lockResult.TryAgainIn);
                    }
                }
            })));
        }
示例#29
0
        /// <summary>
        /// Get text body of mail from cache or server and update cache if available
        /// </summary>
        /// <param name="summary">Mail summary</param>
        /// <param name="inbox">Mailbox that contains mail</param>
        /// <returns>Body text</returns>
        private string GetBodyText(IMessageSummary summary, IMailFolder inbox)
        {
            //Get from cache
            var cachedText = CacheService?.GetCachedMail(summary.UniqueId.Id);

            if (cachedText != null)
            {
                return(cachedText.BodyText);
            }

            //Download from server
            var bodyText = "";

            if (summary.TextBody != null)
            {
                var text = (TextPart)inbox.GetBodyPart(summary.UniqueId, summary.TextBody);
                bodyText = text.Text.Trim();
            }
            else if (summary.HtmlBody != null)
            {
                //TODO: Read html body
                bodyText = "";
            }

            //Update cache
            CacheService?.UpdateCachedMailPart(summary.UniqueId.Id, "BodyText", bodyText);

            return(bodyText);
        }
示例#30
0
        /// <summary>
        /// Reads all the messages.
        /// </summary>
        private static void ReadMessage()
        {
            using (ImapClient client = new ImapClient())
            {
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                client.Connect("imap.gmail.com", 993, true);
                client.Authenticate(from.Address, password);

                IMailFolder inbox = client.Inbox;
                inbox.Open(FolderAccess.ReadOnly);

                Console.WriteLine("Total messages: {0}", inbox.Count);
                Console.WriteLine("Recent messages: {0}", inbox.Recent);

                for (int i = 0; i < inbox.Count; i++)
                {
                    MimeMessage message = inbox.GetMessage(i);
                    Console.WriteLine("\n-------------------- messsage " + i + 1 + ", size=" + inbox.Fetch(0, -1, MessageSummaryItems.Size).ElementAt(i).Size + " --------------------");
                    Console.WriteLine("From: {0}", message.From[0]);
                    Console.WriteLine("Subject: {0}", message.Subject);
                    Console.WriteLine("Text: {0}", message.TextBody);
                    Console.WriteLine("-------------------- end of message " + i + 1 + " --------------------");
                }

                Console.WriteLine("Press a key to continue");
                Console.ReadKey();
                client.Disconnect(true);
            }
        }
        private async Task CheckMailfolder(IMailFolder mailFolder)
        {
            if (!mailFolder.IsOpen)
            {
                mailFolder.Open(FolderAccess.ReadOnly);
            }

            var folderStatus = GetFolderStatus(mailFolder.FullName);

            var ids = await SearchMail(mailFolder, folderStatus);


            var newIds = ids
                         .Where(id => id > folderStatus.LastReceived)
                         .ToList();

            foreach (var uid in newIds)
            {
                var message = await GetMessage(mailFolder, uid);

                folderStatus.LastReceived = uid;

                ReportMessage(message);
            }

            folderStatus.LastChecked = DateTime.Now;
        }
示例#32
0
 private static void MarkMessagesAsRead(IMailFolder folder, List <IMessageSummary> messages)
 {
     foreach (var message in messages)
     {
         folder.SetFlags(message.UniqueId, MessageFlags.Seen, true);
     }
 }
示例#33
0
        public MessageListViewController (IMailFolder folder) : base (UITableViewStyle.Grouped, null, true)
        {
            Folder = folder;

            Root = new RootElement (folder.FullName) {
                new Section ()
            };
        }
示例#34
0
		static bool CheckFolderForChildren (IMailFolder folder)
		{
			if (Program.Client.Capabilities.HasFlag (ImapCapabilities.Children)) {
				if (folder.Attributes.HasFlag (FolderAttributes.HasChildren))
					return true;
			} else if (!folder.Attributes.HasFlag (FolderAttributes.NoInferiors)) {
				return true;
			}

			return false;
		}
        // Recursive function to load all folders and their subfolders
        async Task LoadChildFolders (Section foldersSection, IMailFolder folder)
        {
            if (!folder.IsNamespace) {    
                foldersSection.Add (new StyledStringElement (folder.FullName, () =>
                    OpenFolder (folder)));
            }

            var subfolders = await folder.GetSubfoldersAsync ();

            foreach (var sf in subfolders)
                await LoadChildFolders (foldersSection, sf);
        }
        public static void Analyze(IMailFolder folder, LearningDataSet result) {
            var messages = folder.Search(SearchQuery.All);

            if (messages.Count > 0) {
                foreach (var messageUid in messages) {
                    var message = folder.GetMessage(messageUid);

                    AnalyzeMessage(message, result);
                }
            }

            result.LastUpdate = DateTime.Now;
        }
示例#37
0
        // Recursive function to load all folders and their subfolders
        async Task LoadChildFolders (Section foldersSection, IMailFolder folder)
        {
            if (!folder.IsNamespace) {    
                foldersSection.Add (new StyledStringElement (folder.FullName, () =>
                    OpenFolder (folder)));
            }

			if (folder.Attributes.HasFlag (FolderAttributes.HasNoChildren))
				return;

            var subfolders = await folder.GetSubfoldersAsync ();

            foreach (var sf in subfolders)
                await LoadChildFolders (foldersSection, sf);
        }
示例#38
0
		void UpdateFolderNode (IMailFolder folder)
		{
			var node = map[folder];

			if (folder.Unread > 0) {
				node.Text = string.Format ("{0} ({1})", folder.Name, folder.Unread);
				node.NodeFont = new Font (node.NodeFont, FontStyle.Bold);
			} else {
				node.NodeFont = new Font (node.NodeFont, FontStyle.Regular);
				node.Text = folder.Name;
			}

			if (folder.Attributes.HasFlag (FolderAttributes.Trash))
				node.SelectedImageKey = node.ImageKey = folder.Count > 0 ? "trash-full" : "trash-empty";
		}
        private void ProcessAnalysis(IMailFolder inbox) {
            if ((_mailBox.Spam == null) || (_mailBox.Spam.EnableSpamProtection == false)) {
                return;
            }

            _learningData = _learningStorage.Read();
            var needToUpdateData = _learningData.LastUpdate < DateTime.Now.Subtract(TimeSpan.FromMinutes(_mailBox.Spam.AnalysisInterval));
            if (needToUpdateData) {
                var targetFolder = inbox.GetSubfolder(_mailBox.Spam.Target);
                targetFolder.Open(FolderAccess.ReadOnly);

                MailBoxFolderAnalyzer.Analyze(targetFolder, _learningData);

                _learningStorage.Save(_learningData);
            }
        }
        private void ProcessRules(IMailFolder inbox) {
            inbox.Open(FolderAccess.ReadWrite);
            inbox.Status(StatusItems.Unread);

            if (inbox.Unread > 0) {
                var unreadMessageUids = inbox.Search(SearchQuery.NotSeen);
                var toMove = new Dictionary<string, List<UniqueId>>();
                var markAsRead = new List<UniqueId>();

                // process unread messages
                foreach (var unreadMessageUid in unreadMessageUids) {
                    var message = inbox.GetMessage(unreadMessageUid);

                    var matchingRule = GetMatchingRule(message);
                    if (matchingRule != null) {
                        if (!toMove.ContainsKey(matchingRule.Destination)) {
                            toMove.Add(matchingRule.Destination, new List<UniqueId>());
                        }

                        toMove[matchingRule.Destination].Add(unreadMessageUid);

                        if (matchingRule.MarkAsRead) {
                            markAsRead.Add(unreadMessageUid);
                        }
                    }
                }

                // mark as read
                if (markAsRead.Any()) {
                    inbox.AddFlags(markAsRead, MessageFlags.Seen, true);
                }

                // move to destination
                if (toMove.Any()) {
                    foreach (var destination in toMove.Keys) {
                        inbox.MoveTo(toMove[destination], inbox.GetSubfolder(destination));
                    }
                }
            }
        }
示例#41
0
		/// <summary>
		/// Asynchronously move the specified messages to the destination folder.
		/// </summary>
		/// <remarks>
		/// Asynchronously moves the specified messages to the destination folder.
		/// </remarks>
		/// <returns>An asynchronous task context.</returns>
		/// <param name="indexes">The indexes of the messages to move.</param>
		/// <param name="destination">The destination folder.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="indexes"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="destination"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <para><paramref name="indexes"/> is empty.</para>
		/// <para>-or-</para>
		/// <para>One or more of the <paramref name="indexes"/> is invalid.</para>
		/// <para>-or-</para>
		/// <para>The destination folder does not belong to the <see cref="IMailStore"/>.</para>
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="IMailStore"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="IMailStore"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="IMailStore"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The folder is not currently open in read-write mode.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="CommandException">
		/// The command failed.
		/// </exception>
		public virtual Task MoveToAsync (IList<int> indexes, IMailFolder destination, CancellationToken cancellationToken = default (CancellationToken))
		{
			if (indexes == null)
				throw new ArgumentNullException ("indexes");

			if (destination == null)
				throw new ArgumentNullException ("destination");

			return Task.Factory.StartNew (() => {
				lock (SyncRoot) {
					MoveTo (indexes, destination, cancellationToken);
				}
			}, cancellationToken, TaskCreationOptions.None, TaskScheduler.Default);
		}
示例#42
0
		/// <summary>
		/// Moves the specified messages to the destination folder.
		/// </summary>
		/// <remarks>
		/// <para>If the IMAP server supports the MOVE command, then the MOVE command will be used. Otherwise,
		/// the messages will first be copied to the destination folder and then marked as \Deleted in the
		/// originating folder. Since the server could disconnect at any point between those 2 operations, it
		/// may be advisable to implement your own logic for moving messages in this case in order to better
		/// handle spontanious server disconnects and other error conditions.</para>
		/// </remarks>
		/// <param name="indexes">The indexes of the messages to move.</param>
		/// <param name="destination">The destination folder.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="indexes"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="destination"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <para><paramref name="indexes"/> is empty.</para>
		/// <para>-or-</para>
		/// <para>One or more of the <paramref name="indexes"/> is invalid.</para>
		/// <para>-or-</para>
		/// <para>The destination folder does not belong to the <see cref="ImapClient"/>.</para>
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotFoundException">
		/// <paramref name="destination"/> does not exist.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The <see cref="ImapFolder"/> is not currently open in read-write mode.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		public override void MoveTo (IList<int> indexes, IMailFolder destination, CancellationToken cancellationToken = default (CancellationToken))
		{
			if ((Engine.Capabilities & ImapCapabilities.Move) == 0) {
				CopyTo (indexes, destination, cancellationToken);
				AddFlags (indexes, MessageFlags.Deleted, true, cancellationToken);
				return;
			}

			var set = ImapUtils.FormatIndexSet (indexes);

			if (destination == null)
				throw new ArgumentNullException ("destination");

			if (!(destination is ImapFolder) || ((ImapFolder) destination).Engine != Engine)
				throw new ArgumentException ("The destination folder does not belong to this ImapClient.", "destination");

			CheckState (true, true);

			if (indexes.Count == 0)
				return;

			var command = string.Format ("MOVE {0} %F\r\n", set);
			var ic = Engine.QueueCommand (cancellationToken, this, command, destination);

			Engine.Wait (ic);

			ProcessResponseCodes (ic, destination);

			if (ic.Response != ImapCommandResponse.Ok)
				throw ImapCommandException.Create ("MOVE", ic);
		}
示例#43
0
		/// <summary>
		/// Renames the folder to exist with a new name under a new parent folder.
		/// </summary>
		/// <remarks>
		/// Renames the folder to exist with a new name under a new parent folder.
		/// </remarks>
		/// <param name="parent">The new parent folder.</param>
		/// <param name="name">The new name of the folder.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="parent"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="name"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <para><paramref name="parent"/> does not belong to the <see cref="ImapClient"/>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="name"/> is not a legal folder name.</para>
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotFoundException">
		/// The <see cref="ImapFolder"/> does not exist.
		/// </exception>
		/// <exception cref="System.InvalidOperationException">
		/// The folder cannot be renamed (it is either a namespace or the Inbox).
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		public override void Rename (IMailFolder parent, string name, CancellationToken cancellationToken = default (CancellationToken))
		{
			if (parent == null)
				throw new ArgumentNullException ("parent");

			if (!(parent is ImapFolder) || ((ImapFolder) parent).Engine != Engine)
				throw new ArgumentException ("The parent folder does not belong to this ImapClient.", "parent");

			if (name == null)
				throw new ArgumentNullException ("name");

			if (!Engine.IsValidMailboxName (name, DirectorySeparator))
				throw new ArgumentException ("The name is not a legal folder name.", "name");

			if (IsNamespace || (Attributes & FolderAttributes.Inbox) != 0)
				throw new InvalidOperationException ("Cannot rename this folder.");

			CheckState (false, false);

			string newFullName;

			if (!string.IsNullOrEmpty (parent.FullName))
				newFullName = parent.FullName + parent.DirectorySeparator + name;
			else
				newFullName = name;

			var encodedName = Engine.EncodeMailboxName (newFullName);
			var ic = Engine.QueueCommand (cancellationToken, null, "RENAME %F %S\r\n", this, encodedName);
			var oldFullName = FullName;

			Engine.Wait (ic);

			ProcessResponseCodes (ic, this);

			if (ic.Response != ImapCommandResponse.Ok)
				throw ImapCommandException.Create ("RENAME", ic);

			Engine.FolderCache.Remove (EncodedName);
			Engine.FolderCache[encodedName] = this;

			ParentFolder = parent;

			FullName = Engine.DecodeMailboxName (encodedName);
			EncodedName = encodedName;
			Name = name;

			if (Engine.Selected == this) {
				Engine.State = ImapEngineState.Authenticated;
				Access = FolderAccess.None;
				Engine.Selected = null;
				OnClosed ();
			}

			OnRenamed (oldFullName, FullName);
		}
示例#44
0
		/// <summary>
		/// Move the specified messages to the destination folder.
		/// </summary>
		/// <remarks>
		/// <para>Moves the specified messages to the destination folder.</para>
		/// <para>If the IMAP server supports the MOVE extension (check the <see cref="ImapClient.Capabilities"/>
		/// property for the <see cref="ImapCapabilities.Move"/> flag), then this operation will be atomic.
		/// Otherwise, MailKit implements this by first copying the messages to the destination folder, then
		/// marking them for deletion in the originating folder, and finally expunging them (see
		/// <see cref="Expunge(IList&lt;UniqueId&gt;,CancellationToken)"/> for more information about how a
		/// subset of messages are expunged). Since the server could disconnect at any point between those 3
		/// (or more) commands, it is advisable for clients to implement their own logic for moving messages when
		/// the IMAP server does not support the MOVE command in order to better handle spontanious server
		/// disconnects and other error conditions.</para>
		/// </remarks>
		/// <returns>The UID mapping of the messages in the destination folder, if available; otherwise an empty mapping.</returns>
		/// <param name="uids">The UIDs of the messages to move.</param>
		/// <param name="destination">The destination folder.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="uids"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="destination"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <para><paramref name="uids"/> is empty.</para>
		/// <para>-or-</para>
		/// <para>One or more of the <paramref name="uids"/> is invalid.</para>
		/// <para>-or-</para>
		/// <para>The destination folder does not belong to the <see cref="ImapClient"/>.</para>
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotFoundException">
		/// <paramref name="destination"/> does not exist.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The <see cref="ImapFolder"/> is not currently open in read-write mode.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		public override UniqueIdMap MoveTo (IList<UniqueId> uids, IMailFolder destination, CancellationToken cancellationToken = default (CancellationToken))
		{
			if ((Engine.Capabilities & ImapCapabilities.Move) == 0) {
				var copied = CopyTo (uids, destination, cancellationToken);
				AddFlags (uids, MessageFlags.Deleted, true, cancellationToken);
				Expunge (uids, cancellationToken);
				return copied;
			}

			if ((Engine.Capabilities & ImapCapabilities.UidPlus) == 0) {
				var indexes = Fetch (uids, MessageSummaryItems.UniqueId, cancellationToken).Select (x => x.Index).ToList ();
				MoveTo (indexes, destination, cancellationToken);
				Expunge (uids, cancellationToken);
				return UniqueIdMap.Empty;
			}

			var set = ImapUtils.FormatUidSet (uids);

			if (destination == null)
				throw new ArgumentNullException ("destination");

			if (!(destination is ImapFolder) || ((ImapFolder) destination).Engine != Engine)
				throw new ArgumentException ("The destination folder does not belong to this ImapClient.", "destination");

			CheckState (true, true);

			if (uids.Count == 0)
				return UniqueIdMap.Empty;

			var command = string.Format ("UID MOVE {0} %F\r\n", set);
			var ic = Engine.QueueCommand (cancellationToken, this, command, destination);

			Engine.Wait (ic);

			ProcessResponseCodes (ic, destination);

			if (ic.Response != ImapCommandResponse.Ok)
				throw ImapCommandException.Create ("MOVE", ic);

			var copy = ic.RespCodes.OfType<CopyUidResponseCode> ().FirstOrDefault ();

			if (copy != null)
				return new UniqueIdMap (copy.SrcUidSet, copy.DestUidSet);

			return UniqueIdMap.Empty;
		}
示例#45
0
		/// <summary>
		/// Copies the specified messages to the destination folder.
		/// </summary>
		/// <remarks>
		/// Copies the specified messages to the destination folder.
		/// </remarks>
		/// <param name="indexes">The indexes of the messages to copy.</param>
		/// <param name="destination">The destination folder.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="indexes"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="destination"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <para><paramref name="indexes"/> is empty.</para>
		/// <para>-or-</para>
		/// <para>One or more of the <paramref name="indexes"/> is invalid.</para>
		/// <para>-or-</para>
		/// <para>The destination folder does not belong to the <see cref="ImapClient"/>.</para>
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="ImapClient"/> has been disposed.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The <see cref="ImapFolder"/> is not currently open.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="ImapClient"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="ImapClient"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotFoundException">
		/// <paramref name="destination"/> does not exist.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The <see cref="ImapFolder"/> is not currently open.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ImapProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="ImapCommandException">
		/// The server replied with a NO or BAD response.
		/// </exception>
		public override void CopyTo (IList<int> indexes, IMailFolder destination, CancellationToken cancellationToken = default (CancellationToken))
		{
			var set = ImapUtils.FormatIndexSet (indexes);

			if (destination == null)
				throw new ArgumentNullException ("destination");

			if (!(destination is ImapFolder) || ((ImapFolder) destination).Engine != Engine)
				throw new ArgumentException ("The destination folder does not belong to this ImapClient.", "destination");

			CheckState (true, false);

			if (indexes.Count == 0)
				return;

			var command = string.Format ("COPY {0} %F\r\n", set);
			var ic = Engine.QueueCommand (cancellationToken, this, command, destination);

			Engine.Wait (ic);

			ProcessResponseCodes (ic, destination);

			if (ic.Response != ImapCommandResponse.Ok)
				throw ImapCommandException.Create ("COPY", ic);
		}
示例#46
0
		/// <summary>
		/// Rename the folder.
		/// </summary>
		/// <remarks>
		/// Renames the folder.
		/// </remarks>
		/// <param name="parent">The new parent folder.</param>
		/// <param name="name">The new name of the folder.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="parent"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="name"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <para><paramref name="parent"/> does not belong to the <see cref="IMailStore"/>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="name"/> is not a legal folder name.</para>
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="IMailStore"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="IMailStore"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="IMailStore"/> is not authenticated.
		/// </exception>
		/// <exception cref="System.InvalidOperationException">
		/// The folder cannot be renamed (it is either a namespace or the Inbox).
		/// </exception>
		/// <exception cref="FolderNotFoundException">
		/// The <see cref="MailFolder"/> does not exist.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="CommandException">
		/// The command failed.
		/// </exception>
		public abstract void Rename (IMailFolder parent, string name, CancellationToken cancellationToken = default (CancellationToken));
示例#47
0
		/// <summary>
		/// Move the specified messages to the destination folder.
		/// </summary>
		/// <remarks>
		/// Moves the specified messages to the destination folder.
		/// </remarks>
		/// <returns>The UIDs of the messages in the destination folder, if available; otherwise an empty array.</returns>
		/// <param name="uids">The UIDs of the messages to move.</param>
		/// <param name="destination">The destination folder.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="uids"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="destination"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <para><paramref name="uids"/> is empty.</para>
		/// <para>-or-</para>
		/// <para>One or more of the <paramref name="uids"/> is invalid.</para>
		/// <para>-or-</para>
		/// <para>The destination folder does not belong to the <see cref="IMailStore"/>.</para>
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="IMailStore"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="IMailStore"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="IMailStore"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The folder is not currently open in read-write mode.
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// The mail store does not support the UIDPLUS extension.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="CommandException">
		/// The command failed.
		/// </exception>
		public abstract IList<UniqueId> MoveTo (IList<UniqueId> uids, IMailFolder destination, CancellationToken cancellationToken = default (CancellationToken));
示例#48
0
		public MessageSelectedEventArgs (IMailFolder folder, UniqueId uid, BodyPart body)
		{
			Folder = folder;
			UniqueId = uid;
			Body = body;
		}
        // TODO: Should this method return a IMailItem?
        public void Move(IMailFolder newFolder)
        {
            var folderProvider = newFolder as MailFolderProviderHTTP;

            var folderId = folderProvider.Handle;

            dynamic destination = new ExpandoObject();
            destination.DestinationId = folderId;

            HttpUtil.PostDynamicAsync<Message>(Uri + "/Move", destination).Wait();
        }
 public void Move(IMailFolder newFolder)
 {
     var provider = newFolder as MailFolderProviderOM;
     _mailItem = _mailItem.Move(provider.Handle);
 }
示例#51
0
		/// <summary>
		/// Asynchronously rename the folder.
		/// </summary>
		/// <remarks>
		/// Asynchronously renames the folder.
		/// </remarks>
		/// <returns>An asynchronous task context.</returns>
		/// <param name="parent">The new parent folder.</param>
		/// <param name="name">The new name of the folder.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="parent"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="name"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <para><paramref name="parent"/> does not belong to the <see cref="IMailStore"/>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="name"/> is not a legal folder name.</para>
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="IMailStore"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="IMailStore"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="IMailStore"/> is not authenticated.
		/// </exception>
		/// <exception cref="System.InvalidOperationException">
		/// The folder cannot be renamed (it is either a namespace or the Inbox).
		/// </exception>
		/// <exception cref="FolderNotFoundException">
		/// The <see cref="MailFolder"/> does not exist.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="CommandException">
		/// The command failed.
		/// </exception>
		public virtual Task RenameAsync (IMailFolder parent, string name, CancellationToken cancellationToken = default (CancellationToken))
		{
			if (parent == null)
				throw new ArgumentNullException ("parent");

			if (name == null)
				throw new ArgumentNullException ("name");

			if (name.Length == 0 || name.IndexOf (parent.DirectorySeparator) != -1)
				throw new ArgumentException ("The name is not a legal folder name.", "name");

			if (IsNamespace)
				throw new InvalidOperationException ("Cannot rename this folder.");

			return Task.Factory.StartNew (() => {
				lock (SyncRoot) {
					Rename (parent, name, cancellationToken);
				}
			}, cancellationToken, TaskCreationOptions.None, TaskScheduler.Default);
		}
示例#52
0
		/// <summary>
		/// Asynchronously move the specified message to the destination folder.
		/// </summary>
		/// <remarks>
		/// Asynchronously moves the specified message to the destination folder.
		/// </remarks>
		/// <returns>The UID of the message in the destination folder, if available; otherwise, <c>null</c>.</returns>
		/// <param name="uid">The UID of the message to move.</param>
		/// <param name="destination">The destination folder.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="destination"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <para><paramref name="uid"/> is invalid.</para>
		/// <para>-or-</para>
		/// <para>The destination folder does not belong to the <see cref="IMailStore"/>.</para>
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="IMailStore"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="IMailStore"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="IMailStore"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The folder is not currently open in read-write mode.
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// The mail store does not support the UIDPLUS extension.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="CommandException">
		/// The command failed.
		/// </exception>
		public virtual Task<UniqueId?> MoveToAsync (UniqueId uid, IMailFolder destination, CancellationToken cancellationToken = default (CancellationToken))
		{
			if (destination == null)
				throw new ArgumentNullException ("destination");

			return Task.Factory.StartNew (() => {
				lock (SyncRoot) {
					return MoveTo (uid, destination, cancellationToken);
				}
			}, cancellationToken, TaskCreationOptions.None, TaskScheduler.Default);
		}
示例#53
0
 void OpenFolder (IMailFolder folder)
 {
     messageListViewController = new MessageListViewController (folder);
     NavigationController.PushViewController (messageListViewController, true);
 }
示例#54
0
		/// <summary>
		/// Move the specified messages to the destination folder.
		/// </summary>
		/// <remarks>
		/// Moves the specified messages to the destination folder.
		/// </remarks>
		/// <param name="indexes">The indexes of the messages to move.</param>
		/// <param name="destination">The destination folder.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="indexes"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="destination"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <para><paramref name="indexes"/> is empty.</para>
		/// <para>-or-</para>
		/// <para>One or more of the <paramref name="indexes"/> is invalid.</para>
		/// <para>-or-</para>
		/// <para>The destination folder does not belong to the <see cref="IMailStore"/>.</para>
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="IMailStore"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="IMailStore"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="IMailStore"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The folder is not currently open in read-write mode.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="CommandException">
		/// The command failed.
		/// </exception>
		public abstract void MoveTo (IList<int> indexes, IMailFolder destination, CancellationToken cancellationToken = default (CancellationToken));
示例#55
0
		/// <summary>
		/// Initializes a new instance of the <see cref="MailKit.FolderQuota"/> class.
		/// </summary>
		/// <remarks>
		/// Creates a new <see cref="FolderQuota"/> with the specified root.
		/// </remarks>
		/// <param name="quotaRoot">The quota root.</param>
		public FolderQuota (IMailFolder quotaRoot)
		{
			QuotaRoot = quotaRoot;
		}
示例#56
0
		/// <summary>
		/// Asynchronously move the specified messages to the destination folder.
		/// </summary>
		/// <remarks>
		/// Asynchronously moves the specified messages to the destination folder.
		/// </remarks>
		/// <returns>The UIDs of the messages in the destination folder, if available; otherwise an empty array.</returns>
		/// <param name="uids">The UIDs of the messages to move.</param>
		/// <param name="destination">The destination folder.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="uids"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="destination"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <para><paramref name="uids"/> is empty.</para>
		/// <para>-or-</para>
		/// <para>One or more of the <paramref name="uids"/> is invalid.</para>
		/// <para>-or-</para>
		/// <para>The destination folder does not belong to the <see cref="IMailStore"/>.</para>
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="IMailStore"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="IMailStore"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="IMailStore"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The folder is not currently open in read-write mode.
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// The mail store does not support the UIDPLUS extension.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="CommandException">
		/// The command failed.
		/// </exception>
		public virtual Task<IList<UniqueId>> MoveToAsync (IList<UniqueId> uids, IMailFolder destination, CancellationToken cancellationToken = default (CancellationToken))
		{
			if (uids == null)
				throw new ArgumentNullException ("uids");

			if (uids.Count == 0)
				throw new ArgumentException ("No uids were specified.", "uids");

			if (destination == null)
				throw new ArgumentNullException ("destination");

			return Task.Factory.StartNew (() => {
				lock (SyncRoot) {
					return MoveTo (uids, destination, cancellationToken);
				}
			}, cancellationToken, TaskCreationOptions.None, TaskScheduler.Default);
		}
示例#57
0
		static void AssertFolder (IMailFolder folder, string fullName, FolderAttributes attributes, bool subscribed, ulong highestmodseq, int count, int recent, uint uidnext, uint validity, int unread)
		{
			if (subscribed)
				attributes |= FolderAttributes.Subscribed;

			Assert.AreEqual (fullName, folder.FullName, "FullName");
			Assert.AreEqual (attributes, folder.Attributes, "Attributes");
			Assert.AreEqual (subscribed, folder.IsSubscribed, "IsSubscribed");
			Assert.AreEqual (highestmodseq, folder.HighestModSeq, "HighestModSeq");
			Assert.AreEqual (count, folder.Count, "Count");
			Assert.AreEqual (recent, folder.Recent, "Recent");
			Assert.AreEqual (unread, folder.Unread, "Unread");
			Assert.AreEqual (uidnext, folder.UidNext.HasValue ? folder.UidNext.Value.Id : (uint) 0, "UidNext");
			Assert.AreEqual (validity, folder.UidValidity, "UidValidity");
		}
示例#58
0
		void ProcessResponseCodes (ImapCommand ic, IMailFolder folder)
		{
			bool tryCreate = false;

			foreach (var code in ic.RespCodes) {
				switch (code.Type) {
				case ImapResponseCodeType.Alert:
					Engine.OnAlert (code.Message);
					break;
				case ImapResponseCodeType.PermanentFlags:
					PermanentFlags = ((PermanentFlagsResponseCode) code).Flags;
					break;
				case ImapResponseCodeType.ReadOnly:
					Access = FolderAccess.ReadOnly;
					break;
				case ImapResponseCodeType.ReadWrite:
					Access = FolderAccess.ReadWrite;
					break;
				case ImapResponseCodeType.TryCreate:
					tryCreate = true;
					break;
				case ImapResponseCodeType.UidNext:
					UidNext = ((UidNextResponseCode) code).Uid;
					break;
				case ImapResponseCodeType.UidValidity:
					UidValidity = ((UidValidityResponseCode) code).UidValidity;
					break;
				case ImapResponseCodeType.Unseen:
					FirstUnread = ((UnseenResponseCode) code).Index;
					break;
				case ImapResponseCodeType.HighestModSeq:
					HighestModSeq = ((HighestModSeqResponseCode) code).HighestModSeq;
					SupportsModSeq = true;
					break;
				case ImapResponseCodeType.NoModSeq:
					SupportsModSeq = false;
					HighestModSeq = 0;
					break;
				}
			}

			if (tryCreate && folder != null)
				throw new FolderNotFoundException (folder.FullName);
		}
示例#59
0
		/// <summary>
		/// Move the specified message to the destination folder.
		/// </summary>
		/// <remarks>
		/// Moves the specified message to the destination folder.
		/// </remarks>
		/// <returns>The UID of the message in the destination folder, if available; otherwise, <c>null</c>.</returns>
		/// <param name="uid">The UID of the message to move.</param>
		/// <param name="destination">The destination folder.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="destination"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// <para><paramref name="uid"/> is invalid.</para>
		/// <para>-or-</para>
		/// <para>The destination folder does not belong to the <see cref="IMailStore"/>.</para>
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="IMailStore"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="IMailStore"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="IMailStore"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The folder is not currently open in read-write mode.
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// The mail store does not support the UIDPLUS extension.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="CommandException">
		/// The command failed.
		/// </exception>
		public virtual UniqueId? MoveTo (UniqueId uid, IMailFolder destination, CancellationToken cancellationToken = default (CancellationToken))
		{
			if (destination == null)
				throw new ArgumentNullException ("destination");

			var uids = MoveTo (new [] { uid }, destination, cancellationToken);

			if (uids != null && uids.Count > 0)
				return uids[0];

			return null;
		}
示例#60
0
		/// <summary>
		/// Asynchronously move the specified message to the destination folder.
		/// </summary>
		/// <remarks>
		/// Asynchronously moves the specified message to the destination folder.
		/// </remarks>
		/// <returns>An asynchronous task context.</returns>
		/// <param name="index">The index of the message to move.</param>
		/// <param name="destination">The destination folder.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="destination"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// <paramref name="index"/> does not refer to a valid message index.
		/// </exception>
		/// <exception cref="System.ArgumentException">
		/// The destination folder does not belong to the <see cref="IMailStore"/>.
		/// </exception>
		/// <exception cref="System.ObjectDisposedException">
		/// The <see cref="IMailStore"/> has been disposed.
		/// </exception>
		/// <exception cref="ServiceNotConnectedException">
		/// The <see cref="IMailStore"/> is not connected.
		/// </exception>
		/// <exception cref="ServiceNotAuthenticatedException">
		/// The <see cref="IMailStore"/> is not authenticated.
		/// </exception>
		/// <exception cref="FolderNotOpenException">
		/// The folder is not currently open in read-write mode.
		/// </exception>
		/// <exception cref="System.OperationCanceledException">
		/// The operation was canceled via the cancellation token.
		/// </exception>
		/// <exception cref="System.IO.IOException">
		/// An I/O error occurred.
		/// </exception>
		/// <exception cref="ProtocolException">
		/// The server's response contained unexpected tokens.
		/// </exception>
		/// <exception cref="CommandException">
		/// The command failed.
		/// </exception>
		public virtual Task MoveToAsync (int index, IMailFolder destination, CancellationToken cancellationToken = default (CancellationToken))
		{
			if (index < 0 || index >= Count)
				throw new ArgumentOutOfRangeException ("index");

			if (destination == null)
				throw new ArgumentNullException ("destination");

			return MoveToAsync (new [] { index }, destination, cancellationToken);
		}