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); } }
public void CopyFolder(IMailFolder folder, Folder sqlEntity, bool update, string password) { try { folder.Open(FolderAccess.ReadOnly); } catch (Exception) { return; } Random rng = AzusaContext.GetInstance().RandomNumberGenerator; IList <UniqueId> uuids = folder.Search(FolderService.GetSearchQuery(sqlEntity)); foreach (UniqueId uuid in uuids) { if (MessageService.TestForMessage((int)uuid.Id)) { continue; } var message = folder.GetMessage(uuid); byte[] saltBuffer = new byte[16]; rng.NextBytes(saltBuffer); Array.Copy(azusaString, 0, saltBuffer, 0, azusaString.Length); int iterations = rng.Next(1000, short.MaxValue); Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(password, saltBuffer, iterations); Aes aes = Aes.Create(); aes.Key = deriveBytes.GetBytes(32); aes.IV = deriveBytes.GetBytes(16); MemoryStream ms = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write); message.WriteTo(cryptoStream); cryptoStream.Flush(); Mail child = new Mail(); child.Uid = (int)uuid.Id; child.MessageUtime = message.Date.DateTime.ToUnixTime(); child.Folder = sqlEntity.id; child.From = message.From[0].ToString(); if (message.To.Count > 0) { child.To = message.To[0].ToString(); } else { child.To = null; } child.Subject = message.Subject; child.Salt = saltBuffer; child.Iterations = (short)iterations; child.Data = new byte[ms.Position]; Array.Copy(ms.GetBuffer(), 0, child.Data, 0, ms.Position); MessageService.StoreMessage(child); } folder.Close(false); }
public IEnumerable <IEMailMessageI> GetReadMailMessages(IMailRequestI mailRequest) { var mailMessages = new List <IEMailMessageI>(); using (ImapClient client = new ImapClient()) { client.Connect(MailReadersSettingsModule.Settings.IMAP, MailReadersSettingsModule.Settings.IMAPport, SecureSocketOptions.SslOnConnect); client.Authenticate(MailReadersSettingsModule.Settings.Login, MailReadersSettingsModule.Settings.Password); IMailFolder inbox = client.Inbox; inbox.Open(FolderAccess.ReadOnly); var uids = inbox.Search(SearchQuery.Seen); foreach (var item in uids) { var message = inbox.GetMessage(item); var mailMessage = EntityManager <IEMailMessageI> .Instance.Create(); mailMessage.Name = DateTime.Now.ToString(); mailMessage.CreationDate = DateTime.Now; mailMessage.Tema = message.Subject; mailMessage.Soobschenie = message.HtmlBody; mailMessage.DataPolucheniePisjma = message.Date.UtcDateTime; mailMessage.OtKogo = message.From.FirstOrDefault().Name; mailMessage.Save(); mailMessages.Add(mailMessage); } } return(mailMessages.AsEnumerable()); }
// 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()); }
/// <summary> /// Filters the current email inbox object to pull only the "non-error" retrospect emails /// Returns a list of indicies that contain the indices that the non-error emails /// can be found at in the original email inbox object /// </summary> /// <param name="emails">Object containing all emails</param> /// <param name="newMessageIds">List of indicies of unseen emails</param> /// <returns></returns> public IList <UniqueId> GetSuccessful(IMailFolder emails, IList <UniqueId> newMessageIds) { // First argument means only search new emails IList <UniqueId> messageIds = emails.Search(newMessageIds, this.successfulSearchTerm); return(messageIds); }
/// <summary> /// Filters the current email inbox object to pull only the "error" emails /// Returns a list of indicies that contain the indices that the error emails /// can be found at in the original email inbox object /// </summary> /// <param name="emails">Object containing all emails</param> /// <param name="newMessageIds">List of indicies of unseen emails that are not successful retrospect emails</param> /// <returns></returns> public IList <UniqueId> GetFailure(IMailFolder emails, IList <UniqueId> nonSuccessfulIds) { // First argument means only search for error/unique emails IList <UniqueId> messageIds = emails.Search(nonSuccessfulIds, this.errorSearchTerm); return(messageIds); }
/// <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); }
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); } }
private void refresh() { login(); intializeFolder(); System.Collections.Generic.IList <IMessageSummary> summaries; MessageBox.Show(mailboxName); MessageBox.Show("!!" + fol.Count.ToString()); if (!Directory.Exists(@"D:\emails\" + mailboxName)) { Directory.CreateDirectory(@"D:\emails\" + mailboxName); int i = 0; summaries = fol.Fetch(0, 1000000, MessageSummaryItems.Envelope); var summaries2 = fol.Fetch(0, 1000000, MessageSummaryItems.UniqueId); StreamWriter sw; foreach (var message in summaries) { sw = new StreamWriter("D:\\emails\\" + mailboxName + "\\" + i + ".eml", false); sw.Write(message.Envelope.ToString() + "\n" + summaries2[i].UniqueId.ToString()); sw.Close(); Dispatcher.Invoke(() => dataGrid.Items.Add(new { Col1 = i + 1, Col2 = String.Format("{0:yyyy/MM/dd HH:mm:ss}", message.Date.LocalDateTime).ToString(), Col3 = message.Envelope.From, Col4 = message.Envelope.Subject, Col5 = summaries2[i].UniqueId.ToString() }), DispatcherPriority.Send); if (i > (long)Properties.Settings.Default[lastUid]) { Properties.Settings.Default[lastUid] = (long)i; Properties.Settings.Default[lastDate] = String.Format("{0:yyyy/MM/dd HH:mm:ss}", message.Date.LocalDateTime).ToString(); Properties.Settings.Default.Save(); } i++; } } else { int i = Convert.ToInt32(Properties.Settings.Default[lastUid]) + 1; MessageBox.Show(Properties.Settings.Default[lastDate] + ""); var query = SearchQuery.DeliveredAfter(DateTime.ParseExact(Properties.Settings.Default[lastDate].ToString(), "yyyy/MM/dd HH:mm:ss", null)); StreamWriter sw; var url = fol.Search(query); if (url.Count > 0) { summaries = fol.Fetch(url, MessageSummaryItems.Envelope); var summaries2 = fol.Fetch(0, 1000000, MessageSummaryItems.UniqueId); foreach (var message in summaries) { sw = new StreamWriter("D:\\emails\\" + mailboxName + "\\" + i + ".eml", false); sw.Write(message.Envelope.ToString() + "\n" + summaries2[i].UniqueId.ToString()); sw.Close(); Dispatcher.Invoke(() => dataGrid.Items.Add(new { Col1 = i + 1, Col2 = String.Format("{0:yyyy/MM/dd HH:mm:ss}", message.Date.LocalDateTime).ToString(), Col3 = message.Envelope.From, Col4 = message.Envelope.Subject, Col5 = summaries2[i].UniqueId.ToString() }), DispatcherPriority.Send); MessageBox.Show(":"); if (i > (long)Properties.Settings.Default[lastUid]) { Properties.Settings.Default[lastUid] = (long)i; Properties.Settings.Default[lastDate] = String.Format("{0:yyyy/MM/dd HH:mm:ss}", message.Date.LocalDateTime).ToString(); Properties.Settings.Default.Save(); } i++; } } } }
private IList <UniqueId> SearchMessages(StructureImpl filter) { var imapFilter = new InternetMailImapSearchFilter(filter); var query = imapFilter.CreateSearchQuery(); return(_currentFolder.Search(query)); }
/// <summary> /// Get the list of emails for a search /// </summary> /// <param name="condition">The search condition</param> /// <param name="headersOnly">True if you only want header information</param> /// <param name="markRead">True if you want the emails marked as read</param> /// <returns>The list of mail message that match the search</returns> private List <MimeMessage> GetSearchResults(SearchQuery condition, bool headersOnly, bool markRead) { List <MimeMessage> messageList = new List <MimeMessage>(); IMailFolder folder = this.GetCurrentFolder(); foreach (UniqueId uid in folder.Search(condition, default)) { if (markRead) { folder.AddFlags(uid, MessageFlags.Seen, true); } MimeMessage message; if (headersOnly) { HeaderList headers = folder.GetHeaders(uid); var messageId = headers[HeaderId.MessageId]; message = new MimeMessage(headers) { MessageId = messageId }; } else { message = folder.GetMessage(uid); } messageList.Add(message); } return(messageList); }
public static void RemoveFolder(IMailFolder folder, Configuration config) { using var kernel = new FakeItEasyMockingKernel(); kernel.Rebind <ILogger>().ToConstant(Log.Logger); kernel.Rebind <Configuration>().ToConstant(config); kernel.Rebind <ImapStore>().ToSelf().InSingletonScope(); kernel.Rebind <ImapConnectionFactory>().ToSelf().InSingletonScope(); var imapFac = kernel.Get <ImapConnectionFactory>(); using var connection = imapFac.GetImapConnectionAsync().Result; var subFolders = folder.GetSubfolders(); foreach (var subFolder in subFolders) { RemoveFolder(subFolder, config); } folder.Open(FolderAccess.ReadWrite); var allMessages = folder.Search(SearchQuery.All); folder.SetFlags(allMessages, MessageFlags.Deleted, true); folder.Expunge(); folder.Close(); try { folder.Delete(); } catch (Exception e) { Debug.WriteLine("Exception while deleting folder: " + e.ToString()); } connection.Disconnect(true); }
internal IEnumerable <Message> GetMessages() { _imapFolder.Open(FolderAccess.ReadOnly); var messages = _imapFolder.Search(SearchQuery.All).Select(u => new Message(u, _imapFolder.GetHeaders(u))).ToArray(); _imapFolder.Close(); return(messages); }
private static void DeleteOldMessages(IMailFolder folder) { var uids = (from p in folder.Search(SearchQuery.All) orderby p.Id descending select p).Skip(50).ToList(); if (uids.Any()) { folder.AddFlags(uids, MessageFlags.Deleted, true); } }
private static void MarkAllMessagesAsSeen(IMailFolder folder) { var uids = folder.Search(SearchQuery.NotSeen); if (uids.Any()) { folder.AddFlags(uids, MessageFlags.Seen, true); } }
public List <MimeMessage> LoadMessages() { foreach (var item in Fetch(inbox)) { unSorted.Add(item); } foreach (var uid in inbox.Search(SearchQuery.NotSeen)) { var message = inbox.GetMessage(uid); notseen.Add(message); } foreach (var uid in inbox.Search(SearchQuery.Seen)) { var message = inbox.GetMessage(uid); seen.Add(message); } msg = unSorted; return(new List <MimeMessage>(msg)); }
private async Task <IList <UniqueId> > SearchMail(IMailFolder mailFolder, MailBoxFolderStatus folderStatus) { var tollerantSearch = new TolerantFunction <SearchQuery, IList <UniqueId> >(new TolerantFunctionConfig <SearchQuery, IList <UniqueId> >() { Func = searchQuery => mailFolder.Search(searchQuery) }); var query = SearchQuery.DeliveredAfter(folderStatus.LastChecked); return(await tollerantSearch.Execute(query)); }
private static string CheckMail(long postId, IMailFolder inbox, UniqueIdRange range, BinarySearchQuery query) { string result = string.Empty; foreach (UniqueId uid in inbox.Search(range, query)) { var message = inbox.GetMessage(uid); result = message.TextBody.Split('\r', '\n').FirstOrDefault(); if (!string.IsNullOrEmpty(result)) { inbox.AddFlags(uid, MessageFlags.Seen, true); } if (result != null && result.ToLower().ToLower() == "cancel") { C.WriteLine("We won't be proceeding with this post..."); DbBlackList dbBlackList = new DbBlackList(); Blacklist item = new Blacklist { Subreddit = WorkingSub, PostId = postId, CreatedDate = DateTime.Now }; dbBlackList.AddToBlacklist(item); Environment.Exit(0); } else if (result != null && result.ToLower().ToLower() == "next") { C.WriteLine("We won't be proceeding with this post..."); DbBlackList dbBlackList = new DbBlackList(); Blacklist item = new Blacklist { Subreddit = WorkingSub, PostId = postId, CreatedDate = DateTime.Now }; dbBlackList.AddToBlacklist(item); Process.Start(Assembly.GetExecutingAssembly().Location, Args.FirstOrDefault()); Environment.Exit(0); } else { C.WriteLineNoTime("We got a title!"); } break; } return(result); }
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; }
public void GetAllMailsByFolder(IProgress <MimeMessage> progress, String selectedFolder) { var messages = new List <MimeMessage>(); using (var client = new ImapClient()) { try { client.Connect(mailServer, port, ssl); client.AuthenticationMechanisms.Remove("XOAUTH2"); client.Authenticate(login, password); var mainEmailFolder = client.GetFolder(client.PersonalNamespaces[0]); emailFolders = mainEmailFolder.GetSubfolders().ToList(); IMailFolder inbox = null; foreach (var folder in emailFolders) { if (folder.FullName == selectedFolder) { inbox = folder; } } inbox.Open(FolderAccess.ReadOnly); var results = inbox.Search(SearchOptions.All, SearchQuery.All); int emailCounter = results.UniqueIds.Count; if (emailCounter > 50) { emailCount = 50; } else { emailCount = results.UniqueIds.Count; } for (int i = emailCounter - 1; i >= emailCounter - emailCount; i--) { var message = inbox.GetMessage(results.UniqueIds[i]); progress.Report(message); messages.Add(message); } client.Disconnect(true); } catch (AuthenticationException) { MessageBox.Show("Wrong username or password."); } } }
private bool MessageExists(IMessageSummary msg, IMailFolder folder, IMailFolder dest) { // check if message exists on dest... string mid = msg.Headers[HeaderId.MessageId]; // check if exists locally only.... if (MessageExistsLocally(mid, msg, folder)) { return(true); } if (!CheckIfMessageExists) { return(false); } SearchQuery query = null; if (mid != null) { query = SearchQuery.HeaderContains("Message-ID", mid); } else { mid = msg.Headers[HeaderId.ResentMessageId]; if (mid != null) { query = SearchQuery.HeaderContains("Resent-Message-ID", mid); } else { Console.WriteLine($"No message id found for {msg.Headers[HeaderId.Subject]}"); } } if (query != null) { var ids = dest.Search(query); if (ids.Count == 1) { //Console.WriteLine("Message exists at destination"); return(true); } } return(false); }
protected override void Execute(CodeActivityContext context) { string username = Email.Get(context); //发送端账号 string password = Password.Get(context); //发送端密码(这个客户端重置后的密码) string server = Server.Get(context); //邮件服务器 Int32 port = Port.Get(context); //端口号 string mailFolderTo = MailFolderTo.Get(context); //目标文件夹 string mailFolderFrom = MailFolderFrom.Get(context); //源文件夹 MimeMessage mailMoveMessage = MailMoveMessage.Get(context); ImapClient client = new ImapClient(); SearchQuery query; try { client.Connect(server, port, SecureConnection); client.Authenticate(username, password); if (EnableSSL) { client.SslProtocols = System.Security.Authentication.SslProtocols.Ssl3; } query = SearchQuery.All; List <IMailFolder> mailFolderList = client.GetFolders(client.PersonalNamespaces[0]).ToList(); IMailFolder fromFolder = client.GetFolder(mailFolderFrom); IMailFolder toFolder = client.GetFolder(mailFolderTo); fromFolder.Open(FolderAccess.ReadWrite); IList <UniqueId> uidss = fromFolder.Search(query); List <MailMessage> emails = new List <MailMessage>(); for (int i = uidss.Count - 1; i >= 0; i--) { MimeMessage message = fromFolder.GetMessage(new UniqueId(uidss[i].Id)); if (message.Date == mailMoveMessage.Date && message.MessageId == mailMoveMessage.MessageId && message.Subject == mailMoveMessage.Subject) { fromFolder.MoveTo(new UniqueId(uidss[i].Id), toFolder); break; } } client.Disconnect(true); } catch (Exception e) { client.Disconnect(true); SharedObject.Instance.Output(SharedObject.enOutputType.Error, "IMAP移动邮件失败", e.Message); } }
private void button1_Click(object sender, EventArgs e) { ImapClient client = new ImapClient(); string account = "*****@*****.**"; string passWord = "******"; client.Connect("imap.qiye.163.com", 993, true); //client.Authenticate("*****@*****.**", "TNL7EtuUVJ5mRNcw"); client.Authenticate(account, passWord); IMailFolder inbox = client.Inbox; inbox.Open(FolderAccess.ReadWrite); IList <UniqueId> mail_list = inbox.Search(SearchQuery.New); foreach (UniqueId item in mail_list) { //得到邮件的内容 MimeMessage message = inbox.GetMessage(item); foreach (MimeEntity attachment in message.Attachments) { MimePart mime = (MimePart)attachment; Console.WriteLine(mime.FileName); string fileName = mime.FileName; if (mime.FileName.Contains(".xls")) { try { using (FileStream stream = File.Create(fileName)) { mime.Content.DecodeTo(stream); } } catch { continue; } } // client.Inbox.SetFlags(item, MessageFlags.Seen,false); } } }
private IMailFolder GetOrCreateLockFolder(IMailFolder parentFolderOfLockFolder, string resourceName, CancellationToken cancellationToken = default) { var lockFolderName = parentFolderOfLockFolder.MakeSafeFolderName(resourceName); IMailFolder lockFolder = null; try { lockFolder = parentFolderOfLockFolder.GetSubfolder(lockFolderName, cancellationToken); } catch { logger.Information("Could not get lock folder '{LockFolderName}' - maybe it does not yet exist or there was an error", lockFolderName); } if (lockFolder == null) { try { logger.Information("Creating new lock folder with name '{LockFolderName}'", lockFolderName); // note: on some mail servers (Greenmail) this will throw if the folder already exists, other servers don't throw and return any existing foldre with this name (Dovecot) lockFolder = parentFolderOfLockFolder.Create(lockFolderName, true); } catch { logger.Information("Error while creating lock folder '{LockFolderName}' - maybe it already exists or ther was an error", lockFolderName); } } if (lockFolder == null) { throw new TeasmCompanionException($"Could not get or create lock folder '{lockFolderName}'"); } lockFolder.Open(FolderAccess.ReadOnly); var existingLockMessages = lockFolder.Search(SearchQuery.SubjectContains(LockMessageSubject), cancellationToken); if (existingLockMessages.Count == 0) { // note: this might create duplicates if run by multiple clients; we'll remove the duplicates later lockFolder.Append(CreateLockMimeMessage()); Thread.Sleep(1000); // give other parallel clients the chance to produce their duplicates if any; we then always choose the first one (selected by UniqueId) } return(lockFolder); }
public MailInfo GetMailById(MailInfo mailInfo) { using (ImapClient client = new ImapClient()) { client.Connect(mailServer, port, ssl); client.AuthenticationMechanisms.Remove("XOAUTH2"); client.Authenticate(UserData.Email, UserData.Password); IMailFolder folder = client.GetFolder(mailInfo.ParentFolder.FullName); folder.Open(FolderAccess.ReadOnly); var results = folder.Search(SearchQuery.Uids(new List <UniqueId> { mailInfo.Uid })); MailInfo message = new MailInfo(folder.GetMessage(results[0]), results[0], folder); client.Disconnect(true); return(message); } }
/// <summary> /// Fetch unprocessed transaction ids from email messages /// </summary> public IList <MessageInfo> ParseTransaction() { var headers = new HashSet <string>(new[] { ppEmailTypeHeader }); var ids = new List <MessageInfo>(); var q = SearchQuery.FromContains("paypal.com") .And(SearchQuery.Not(SearchQuery.HasGMailLabel(successLabel))) .And(SearchQuery.Not(SearchQuery.HasGMailLabel(failureLabel))); // Fetch messages metadata and filter out // messages without the required email type codes var msgs = _inbox.Fetch(_inbox.Search(q), MessageSummaryItems.Full, headers); var filtered = msgs.Where(m => m.Headers.Contains(ppEmailTypeHeader) && IsCorrectCode(m.Headers[ppEmailTypeHeader])).ToArray(); log.Debug("Found {0} unprocessed messages from paypal.com w/ filter codes: [ {1} ]", filtered.Length, string.Join(", ", _filterCodes)); // Download text body and parse transaction ids foreach (var msg in filtered) { TextPart textBody = _inbox.GetBodyPart(msg.UniqueId, msg.TextBody) as TextPart; var id = ParseTransactionId(textBody.Text); if (id == null) { log.Warn("Failed to find any transaction id in message <{0}> with subject <{1}>", msg.Envelope.MessageId, msg.Envelope.Subject); continue; } log.Info("Found transaction <{0}> in message <{1}>", id, msg.Envelope.MessageId); ids.Add(new MessageInfo { TransactionId = id, MessageId = msg.UniqueId.Id }); } return(ids); }
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)); } } } }
public IEnumerable <IEMailMessageI> GetUnreadMailMessages(IMailRequestI mailRequest) { var mailMessages = new List <IEMailMessageI>(); using (ImapClient client = new ImapClient()) { client.Connect(MailReadersSettingsModule.Settings.IMAP, MailReadersSettingsModule.Settings.IMAPport, SecureSocketOptions.SslOnConnect); client.Authenticate(MailReadersSettingsModule.Settings.Login, MailReadersSettingsModule.Settings.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); var mailMessage = EntityManager <IEMailMessageI> .Instance.Create(); ExecuteEmailMessage(message, mailMessage); mailMessages.Add(mailMessage); } } return(mailMessages.AsEnumerable()); }
private UniqueId GetFirstExistingLockMessage(IMailFolder folder, CancellationToken cancellationToken = default) { folder.Open(FolderAccess.ReadOnly); var lockMessages = folder.Search(SearchQuery.SubjectContains(LockMessageSubject), cancellationToken); var orderedLockMessages = lockMessages?.OrderBy(m => m.Id); if (orderedLockMessages.Count() > 1) { var idToRemove = orderedLockMessages.Last(); try { folder.Open(FolderAccess.ReadWrite); folder.SetFlags(idToRemove, MessageFlags.Deleted, true, cancellationToken); folder.Expunge(); } catch { logger.Debug("Failed to remove duplicate lock message with ID {0}; note that this might be ok if another client already removed the duplicate", idToRemove); } } return(orderedLockMessages.First()); }
private List <IMessageSummary> ReceiveMesssages(IMailFolder folder, Arguments arguments) { var options = MessageSummaryItems.All | MessageSummaryItems.Body | MessageSummaryItems.BodyStructure | MessageSummaryItems.UniqueId; var query = CreateSearchQuery(arguments); var uids = folder.Search(query).Take(arguments.Count.Value).ToList(); if (arguments.FromEmail != null) { var fromMailIndex = uids.FindIndex(u => u == arguments.FromEmail.UniqueId); uids.RemoveRange(0, fromMailIndex); } if (uids.Count > arguments.Count.Value) { uids.RemoveRange(arguments.Count.Value, uids.Count - arguments.Count.Value); } return(folder.Fetch(uids, options).ToList()); }
public override void RunCommand(object sender) { var engine = (IAutomationEngineInstance)sender; string vIMAPHost = v_IMAPHost.ConvertUserVariableToString(engine); string vIMAPPort = v_IMAPPort.ConvertUserVariableToString(engine); string vIMAPUserName = v_IMAPUserName.ConvertUserVariableToString(engine); string vIMAPPassword = ((SecureString)v_IMAPPassword.ConvertUserVariableToObject(engine, nameof(v_IMAPPassword), this)).ConvertSecureStringToString(); string vIMAPSourceFolder = v_IMAPSourceFolder.ConvertUserVariableToString(engine); string vIMAPFilter = v_IMAPFilter.ConvertUserVariableToString(engine); string vIMAPMessageDirectory = v_IMAPMessageDirectory.ConvertUserVariableToString(engine); string vIMAPAttachmentDirectory = v_IMAPAttachmentDirectory.ConvertUserVariableToString(engine); using (var client = new ImapClient()) { client.ServerCertificateValidationCallback = (sndr, certificate, chain, sslPolicyErrors) => true; client.SslProtocols = SslProtocols.None; using (var cancel = new CancellationTokenSource()) { try { client.Connect(vIMAPHost, int.Parse(vIMAPPort), true, cancel.Token); //SSL } catch (Exception) { client.Connect(vIMAPHost, int.Parse(vIMAPPort)); //TLS } client.AuthenticationMechanisms.Remove("XOAUTH2"); client.Authenticate(vIMAPUserName, vIMAPPassword, cancel.Token); IMailFolder toplevel = client.GetFolder(client.PersonalNamespaces[0]); IMailFolder foundFolder = FindFolder(toplevel, vIMAPSourceFolder); if (foundFolder != null) { foundFolder.Open(FolderAccess.ReadWrite, cancel.Token); } else { throw new Exception("Source Folder not found"); } SearchQuery query; if (vIMAPFilter.ToLower() == "none") { query = SearchQuery.All; } else if (!string.IsNullOrEmpty(vIMAPFilter.Trim())) { query = SearchQuery.MessageContains(vIMAPFilter) .Or(SearchQuery.SubjectContains(vIMAPFilter)) .Or(SearchQuery.FromContains(vIMAPFilter)) .Or(SearchQuery.BccContains(vIMAPFilter)) .Or(SearchQuery.BodyContains(vIMAPFilter)) .Or(SearchQuery.CcContains(vIMAPFilter)) .Or(SearchQuery.ToContains(vIMAPFilter)); } else { throw new NullReferenceException("Filter not specified"); } if (v_IMAPGetUnreadOnly == "Yes") { query = query.And(SearchQuery.NotSeen); } var filteredItems = foundFolder.Search(query, cancel.Token); List <MimeMessage> outMail = new List <MimeMessage>(); foreach (UniqueId uid in filteredItems) { if (v_IMAPMarkAsRead == "Yes") { foundFolder.AddFlags(uid, MessageFlags.Seen, true); } MimeMessage message = foundFolder.GetMessage(uid, cancel.Token); if (v_IMAPSaveMessagesAndAttachments == "Yes") { ProcessEmail(message, vIMAPMessageDirectory, vIMAPAttachmentDirectory); } message.MessageId = $"{vIMAPSourceFolder}#{uid}"; outMail.Add(message); } outMail.StoreInUserVariable(engine, v_OutputUserVariableName, nameof(v_OutputUserVariableName), this); client.Disconnect(true, cancel.Token); client.ServerCertificateValidationCallback = null; } } }
/// <summary> /// download file /// </summary> /// <param name="folderPath">mail folder</param> /// <param name="fileName">file save name</param> public void DownloadFile(string folderPath, string fileName, string local, ImapClient client = null, IList <IMessageSummary> all = null, IMailFolder folder = null) { if (File.Exists(local)) { Console.WriteLine($"error! file {local} already exist!"); return; } if (client == null) { client = GetImapClient(); } var invalidFileName = Path.GetInvalidFileNameChars(); fileName = invalidFileName.Aggregate(fileName, (o, r) => (o.Replace(r.ToString(), string.Empty))); if (all == null) { folder = client.GetFolder(folderPath); folder.Open(FolderAccess.ReadOnly); var uids = folder.Search(SearchQuery.SubjectContains($"[mailDisk]{fileName}")); Console.WriteLine($"find {uids.Count} matchs in this folder"); Console.WriteLine($"fatching mails"); all = folder.Fetch(uids, MessageSummaryItems.Full | MessageSummaryItems.UniqueId); } bool singleFile = true; int fileSum = 0; bool hasFile = false; foreach (var m in all) { string subject = m.Envelope.Subject.Substring("[mailDisk]".Length); if (subject.IndexOf(fileName) == 0 && (subject.Length == fileName.Length || subject.Substring(fileName.Length, 1) == "<")) { if (subject.Length == fileName.Length) { hasFile = true; break; } MatchCollection mc = Regex.Matches(subject, @"<1/(\d+?)>"); if (mc.Count > 0 && mc[0].Groups.Count == 2) { fileSum = int.Parse(mc[0].Groups[1].ToString()); singleFile = false; hasFile = true; break; } } } if (!hasFile) { Console.WriteLine($"error! file not exist!"); return; } if (singleFile) { foreach (var m in all) { if (m.Envelope.Subject.IndexOf($"[mailDisk]{fileName}") == 0) { while (true) { try { using (var output = File.Create(local)) { var r = Download(folder, m.UniqueId); r.Position = 0; r.CopyTo(output); break; } } catch (Exception e) { Console.WriteLine($"[disk Download]fail, retry, infomation:" + e.Message); } } } } } else { ArrayList mails = new ArrayList(); foreach (var m in all) { string subject = m.Envelope.Subject.Substring("[mailDisk]".Length); mails.Add(subject); } Console.WriteLine($"find file {fileName} with {fileSum} parts,checking..."); bool result = true;//check is it have all files for (int i = 1; i <= fileSum; i++) { if (!mails.Contains($"{fileName}<{i}/{fileSum}>")) { result = false; break; } } if (result) { Console.WriteLine($"file {fileName} check ok, begin download..."); using (var output = File.Create(local)) { for (int i = 1; i <= fileSum; i++) { foreach (var m in all) { if (m.Envelope.Subject.IndexOf($"[mailDisk]{fileName}<{i}/{fileSum}>") == 0) { while (true) { try { Console.WriteLine($"downloading {fileName}<{i}/{fileSum}> ..."); var r = Download(folder, m.UniqueId); r.Position = 0; r.CopyTo(output); break; } catch (Exception e) { Console.WriteLine($"[disk Download]fail, retry, infomation:" + e.Message); } } } } } } } else { Console.WriteLine($"file {fileName}'s parts are missing, download fail"); return; } } Console.WriteLine($"file {fileName} download success!"); }