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> GetMessagesList(ArrayImpl ids) { var result = new List <UniqueId>(); if (ids == null) { result.AddRange(_currentFolder .Fetch(0, -1, MessageSummaryItems.UniqueId) .Select((IMessageSummary arg) => arg.UniqueId)); } else { // Получим список идентификаторов писем с учётом возможных вариантов входящих данных var Uids = new List <UniqueId>(); foreach (var data in ids) { if (data.DataType == DataType.String) { // Идентификатор сообщения Uids.Add(InternalIdToUniqueId(data.AsString())); } else if (data.DataType == DataType.Number) { // Передан порядковый номер в текущем ящике var index = (int)data.AsNumber(); var letterData = _currentFolder.Fetch(index, index, MessageSummaryItems.UniqueId); foreach (var oneData in letterData) { Uids.Add(oneData.UniqueId); } } else if (data is InternetMailMessage) { // ИнтернетПочтовоеСообщение foreach (var id in (data as InternetMailMessage).Uid) { Uids.Add(InternalIdToUniqueId(id.AsString())); } } else if (data is ArrayImpl) { // Массив идентификаторов foreach (var id in (data as ArrayImpl)) { Uids.Add(InternalIdToUniqueId(id.AsString())); } } } result.AddRange(Uids); } return(result); }
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); }
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); }
public IEnumerable <MailMessagePreviewDTO> GetMailInbox() { List <MailMessagePreviewDTO> list = new List <MailMessagePreviewDTO>(); using (ImapClient client = new ImapClient()) { // For demo-purposes, accept all SSL certificates client.ServerCertificateValidationCallback = (s, c, h, e) => true; client.Connect("imap.gmail.com", 993, true); client.Authenticate("*****@*****.**", "V3@pu166@@!!"); // The Inbox folder is always available on all IMAP servers... IMailFolder inbox = client.Inbox; inbox.Open(FolderAccess.ReadOnly); int index = Math.Max(inbox.Count - 10, 0); IList <IMessageSummary> items = inbox.Fetch(index, -1, MessageSummaryItems.UniqueId); foreach (IMessageSummary item in items) { MimeKit.MimeMessage message = inbox.GetMessage(item.UniqueId); list.Add(new MailMessagePreviewDTO { Date = message.Date.DateTime.ToUniversalTime(), Sender = message.From[0].Name, Subject = message.Subject }); } } return(list); }
private UniqueId GetUniqueId(MimeMessage mailMessage, string folder) { UniqueId id = new UniqueId(); IMailFolder mailFolder = GetFolder(folder); bool open = mailFolder.IsOpen; if (!open) { mailFolder.Open(FolderAccess.ReadOnly); } var items = mailFolder.Fetch(0, -1, MessageSummaryItems.UniqueId | MessageSummaryItems.Size | MessageSummaryItems.Flags); foreach (var item in items) { var message = mailFolder.GetMessage(item.UniqueId); if (message.MessageId == mailMessage.MessageId) { id = item.UniqueId; break; } } if (!open) { mailFolder.Close(); } return(id); }
public void reloadMessages(string folder) { IMailFolder mailFolder = GetFolder(folder); mailFolder.Open(FolderAccess.ReadWrite); _currentFolderSummary = mailFolder.Fetch(0, -1, MessageSummaryItems.UniqueId | MessageSummaryItems.Flags | MessageSummaryItems.Envelope); mailFolder.Close(); _currentFolder = folder; }
private List <IMessageSummary> ReceiveMesssages(IMailFolder folder, Arguments arguments) { var options = MessageSummaryItems.All | MessageSummaryItems.Body | MessageSummaryItems.BodyStructure | MessageSummaryItems.UniqueId; var allMessages = folder.Fetch(0, -1, options).ToList(); var onlyUnread = arguments.OnlyUnreadMessages.Value; var since = arguments.SinceDate.Value; var to = arguments.ToDate.Value; return(SelectMessages(allMessages, onlyUnread, since, to)); }
public List <MailItem> ExtractMailItems(IMailFolder folder, int pageSize, int page, List <uint> existingUids) { try { using (var client = new ImapClient()) { Connect(client); if (!folder.IsOpen) { logger.LogTrace("Open Folder"); folder.Open(FolderAccess.ReadOnly); } logger.LogInformation($"Fetch summaries [{folder.FullName}] - \tPage: {page} - Page Size: {pageSize}"); var summaries = folder.Fetch(page * pageSize, (page + 1) * pageSize - 1, MessageSummaryItems.UniqueId); logger.LogInformation($"Got summaries [{folder.FullName}] - Count: {summaries.Count}"); if (summaries.Count == 0) { return(null); } var result = new List <MailItem>(); logger.LogTrace("Extract Mail Addresses"); foreach (var summary in summaries) { if (!existingUids.Contains(summary.UniqueId.Id)) { var message = folder.GetMessage(summary.UniqueId); result.AddRange(CreateMailItems(logger, message, this, folder, summary.UniqueId)); } } if (folder.IsOpen) { logger.LogTrace("Close Folder"); folder.Close(false); } return(result); } } catch (Exception e) { logger.LogError(e, $"Error in folder: {folder.FullName} \r\n {e.Message}"); return(null); } }
void LoadMessages() { messages.Clear(); Nodes.Clear(); map.Clear(); if (folder.Count > 0) { var summaries = folder.Fetch(0, -1, MessageSummaryItems.Full | MessageSummaryItems.UniqueId); AddMessageSummaries(summaries); } folder.CountChanged += CountChanged; }
/// <summary> /// Gets the messages from the specified user. /// </summary> /// <param name="user">The <see cref="User"/> instance to retrive messages from.</param> private void GetMessages(User user) { try { using (ImapClient client = new ImapClient()) { Mail mail; Int32.TryParse(imapPortTextBox.Text, out int port); client.ServerCertificateValidationCallback = (s, c, h, e) => true; if (imapSslCheckBox.Enabled) { client.Connect(imapHostTextBox.Text, port, true); } else if (imapTlsCheckBox.Enabled) { client.Connect(imapHostTextBox.Text, port, SecureSocketOptions.StartTlsWhenAvailable); } else { client.Connect(imapHostTextBox.Text, port, SecureSocketOptions.Auto); } client.Authenticate(user.MailAddress.Address, user.Password); IMailFolder inbox = client.Inbox; inbox.Open(FolderAccess.ReadOnly); for (int i = 0; i < 10; i++) { mail = new Mail(inbox.GetMessage(i)) { Size = (uint)inbox.Fetch(0, -1, MessageSummaryItems.Size).ElementAt(i).Size }; mails.Add(mail); } client.Disconnect(true); } mailsController.LoadView(); } catch (Exception) { recievedMailsWithErrors = true; } }
private void CopyMessages(IMailFolder folder, IMailFolder dest) { try { folder.Open(FolderAccess.ReadOnly); dest.Open(FolderAccess.ReadWrite); UniqueIdRange r = new UniqueIdRange(UniqueId.MinValue, UniqueId.MaxValue); var headers = new HashSet <HeaderId>(); headers.Add(HeaderId.Received); headers.Add(HeaderId.Date); headers.Add(HeaderId.MessageId); headers.Add(HeaderId.Subject); headers.Add(HeaderId.From); headers.Add(HeaderId.To); headers.Add(HeaderId.Cc); headers.Add(HeaderId.ResentMessageId); var msgList = folder.Fetch(r, MessageSummaryItems.UniqueId | MessageSummaryItems.InternalDate | MessageSummaryItems.Flags, headers); int total = msgList.Count; int i = 1; foreach (var msg in msgList) { Console.WriteLine($"Copying {i++} of {total}"); CopyMessage(msg, folder, dest); if (i % 100 == 0) { dest.Check(); } } } finally { folder.Close(); dest.Close(); } }
public async Task Attachment(MailWindow inboxPage, User user, ConfigModel conf, string Atch, string destination) { using (ImapClient client = new ImapClient()) { await client.ConnectAsync(conf.ImapServer, conf.ImapPort); client.Authenticate(user.Mail, user.Password); IMailFolder Folder = client.GetFolder(ListMessages.fold); await Folder.OpenAsync(FolderAccess.ReadWrite); IList <IMessageSummary> atc = Folder.Fetch(new[] { LastOpenId }, MessageSummaryItems.Body); var multipart = (BodyPartMultipart)atc.First().Body; var attachment = multipart.BodyParts.OfType <BodyPartBasic>().FirstOrDefault(x => x.FileName == Atch); TransferProgress progress = new TransferProgress(); Downloads FileDownload = new Downloads(); FileDownload.Show(); var file = Folder.GetBodyPart(LastOpenId, attachment, default, progress);
public async Task OpenText(Message m, OpenMessage Page, User user, ConfigModel conf) { using (ImapClient client = new ImapClient()) { List <string> atc = new List <string>(); await client.ConnectAsync(conf.ImapServer, conf.ImapPort); client.Authenticate(user.Mail, user.Password); IMailFolder Folder = client.GetFolder(ListMessages.fold); await Folder.OpenAsync(FolderAccess.ReadWrite); IList <IMessageSummary> msg = Folder.Fetch(new[] { m.ID }, MessageSummaryItems.UniqueId | MessageSummaryItems.BodyStructure | MessageSummaryItems.Envelope); LastOpenId = msg.First().UniqueId; var bodyHTML = (TextPart)Folder.GetBodyPart(msg.First().UniqueId, msg.First().HtmlBody); Page.Dispatcher.Invoke(() => { Page.Attachments.Children.Clear(); }); Folder.SetFlags(m.ID, MessageFlags.Seen, true); m.MessageColor = new SolidColorBrush(Colors.White); foreach (BodyPartBasic attachment in msg.First().Attachments) { Button bt = new Button { Content = attachment.FileName, }; Page.Dispatcher.Invoke(() => { bt.Click += new RoutedEventHandler(new MailWindow(user, conf).OpenAttachment); Page.Attachments.Children.Add(bt); }); } if (m != null) { Page.Dispatcher.Invoke(() => { Page.Info.Text = ($"Subject: {msg.First().Envelope.Subject} \n\rFrom {msg.First().Envelope.From} at {msg.First().Envelope.Date} to {msg.First().Envelope.To}"); Page.Body.NavigateToString("<html><head><meta charset='UTF-8'></head>" + bodyHTML.Text + "</html>"); Page.MailBody.Visibility = 0; }); } client.Disconnect(true); } }
private List <IMessageSummary> GetMessagesSummaryInfo(IMailFolder folder, IList <UniqueId> uids) { var infoList = new List <IMessageSummary>(); try { infoList = folder.Fetch(uids, MessageSummaryItems.Flags | MessageSummaryItems.GMailLabels | MessageSummaryItems.InternalDate, CancelToken).ToList(); } catch (ImapCommandException ex) { Log.Warn("GetMessagesSummaryInfo() Exception: {0}", ex.ToString()); } return(infoList); }
/// <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); }
/// <summary> /// 使用唯一ID获取一封完整邮件 /// 调用前先调用配置方法CfgIMAP() /// </summary> /// <param name="folder">文件夹名,默认是收件箱</param> /// <param name="uniqueid">邮件唯一编号</param> public EmailViewM GetEmailByUniqueId(uint uniqueid, string folderName = null) { try { using (ImapClient client = ConnectIMAP()) { if (folderName == null) { folderName = client.Inbox.Name; } IMailFolder folder = client.GetFolder(folderName); folder.Open(FolderAccess.ReadWrite); UniqueId emailUniqueId = new UniqueId(uniqueid); // 获取这些邮件的摘要信息 List <UniqueId> uids = new List <UniqueId>(); uids.Add(emailUniqueId); var emaills = folder.Fetch(uids, MessageSummaryItems.UniqueId | MessageSummaryItems.Envelope); var emhead = emaills[0]; // 获取邮件含正文部分,. MimeMessage embody = folder.GetMessage(emailUniqueId); /*赋值到实体类*/ var entity = FillEntity(emhead, embody, folder); //然后设置为已读 folder.AddFlags(emailUniqueId, MessageFlags.Seen, true); // folder.Close(); client.Disconnect(true); // return(entity); } } catch (Exception e) { ErrMsg = $"获取单个完整邮件异常:{e.ToString()} [{e.Message}]"; return(null); } }
public Tuple <Mail, HttpStatusCode> GetMailFromFolder(UniqueId id, string folder) { if (!IsAuthenticated()) { return(new Tuple <Mail, HttpStatusCode>(null, HttpStatusCode.ExpectationFailed)); } IMailFolder mailFolder = GetFolder(folder); mailFolder.Open(FolderAccess.ReadWrite); var Items = mailFolder.Fetch(new List <UniqueId>() { id }, MessageSummaryItems.UniqueId | MessageSummaryItems.Size | MessageSummaryItems.Flags | MessageSummaryItems.All); if (Items == null) { Items = new List <IMessageSummary>(); } Mail mail = new Mail((MessageSummary)Items.First(), mailFolder.GetMessage(Items.First().UniqueId), folder); mailFolder.Close(); return(new Tuple <Mail, HttpStatusCode>(mail, HttpStatusCode.OK)); }
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()); }
/// <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!"); }
private void MailCheck() { DBConnect conn = new DBConnect(); SqlConnection sqlConnection = new SqlConnection(@"Data Source=" + conn.host + ";Initial Catalog=" + conn.db + ";" + "User ID=" + conn.user + ";Password="******"SELECT * FROM Mails WHERE Send_from = '{message.From.ToString().Replace("'","")}' " + $"and Subject = '{message.Subject.ToString().Replace("'", "")}' and Send_to = '{message.To.ToString().Replace("'", "")}'"; bool kostyl = false; using (DbDataReader reader = sqlCommand.ExecuteReader()) { if (!reader.HasRows) { kostyl = true; } } if (kostyl) { SqlCommand command = sqlConnection.CreateCommand(); command.CommandText = "INSERT INTO Mails (Send_from, Subject, Date_send, Send_to, Importance, isRead) " + $"VALUES ('{message.From.ToString().Replace("'","")}', '{message.Subject.ToString().Replace("'", "")}', " + $"'{message.Date.ToString().Replace("'", "")}', '{message.To.ToString().Replace("'", "")}', 'Важное', 0)"; command.ExecuteNonQuery(); inbox.AddFlags(item.UniqueId, MessageFlags.Deleted, true); inbox.Expunge(); } } inbox.Close(); } } catch (Exception ex) { Logger.Log.Error(ex.ToString()); } finally { sqlConnection.Close(); sqlConnection.Dispose(); } }
/// <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); } }
public void PopulateEmailList(IMailFolder mailFolder) { // The Inbox folder is always available on all IMAP servers... mailFolder.Open(FolderAccess.ReadOnly); var emailSummaries = mailFolder.Fetch(0, 49, MessageSummaryItems.UniqueId | MessageSummaryItems.PreviewText | MessageSummaryItems.Envelope); Console.WriteLine("Total messages: {0}", mailFolder.Count); Console.WriteLine("Recent messages: {0}", mailFolder.Recent); foreach (var emailSummary in emailSummaries) { if (AppConfig.CurrentIMap.IsConnected && AppConfig.CurrentIMap.IsAuthenticated && ThreadHelper.LogoutRequested == false) { try { Email email = null; ThreadHelper.StallLogout = true; if (emailSummary.TextBody != null) { email = new Email(emailSummary); } else if (emailSummary.HtmlBody != null) { lock (mailFolder.SyncRoot) { email = new Email(emailSummary, mailFolder.GetMessage(emailSummary.UniqueId)); } } if (email != null && email.Id != null && email.MessageSummary != null) { Application.Current.Dispatcher.Invoke(delegate { Emails.Add(email); Console.WriteLine("[Email Added] {0:D2}: {1}", email.Id, email.MessageSummary.Envelope.Subject); }); } else { var idState = "NOT NULL"; var messageState = "NOT NULL"; if (email.Id == null) { idState = "NULL"; } if (email.MessageSummary == null) { messageState = "NULL"; } Console.WriteLine("Email not added successfully.\nId {" + idState + "}\nMessage {" + messageState + "}"); } ThreadHelper.StallLogout = false; } catch (Exception exception) { if (ThreadHelper.LogoutRequested) { Console.WriteLine("Logout requested during email collection. "); ThreadHelper.StallLogout = false; } else { Console.WriteLine(exception); throw; } } } else { break; } } }
public override void RunCommand(object sender) { var engine = (IAutomationEngineInstance)sender; MimeMessage vMimeMessage = (MimeMessage)v_IMAPMimeMessage.ConvertUserVariableToObject(engine, nameof(v_IMAPMimeMessage), this); 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(); 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); var splitId = vMimeMessage.MessageId.Split('#').ToList(); UniqueId messageId = UniqueId.Parse(splitId.Last()); splitId.RemoveAt(splitId.Count - 1); string messageFolder = string.Join("", splitId); IMailFolder toplevel = client.GetFolder(client.PersonalNamespaces[0]); IMailFolder foundSourceFolder = GetIMAPEmailsCommand.FindFolder(toplevel, messageFolder); if (foundSourceFolder != null) { foundSourceFolder.Open(FolderAccess.ReadWrite, cancel.Token); } else { throw new Exception("Source Folder not found"); } var messageSummary = foundSourceFolder.Fetch(new[] { messageId }, MessageSummaryItems.Flags); if (v_IMAPDeleteReadOnly == "Yes") { if (messageSummary[0].Flags.Value.HasFlag(MessageFlags.Seen)) { foundSourceFolder.AddFlags(messageId, MessageFlags.Deleted, true, cancel.Token); } } else { foundSourceFolder.AddFlags(messageId, MessageFlags.Deleted, true, cancel.Token); } client.Disconnect(true, cancel.Token); client.ServerCertificateValidationCallback = null; } } }
private int LoadFolderMessages(IMailFolder folder, MailFolder mailFolder, int limitMessages) { var loaded = 0; ImapFolderUids folderUids; if (!Account.ImapIntervals.TryGetValue(folder.Name, out folderUids)) { folderUids = new ImapFolderUids(new List <int> { 1, int.MaxValue }, 1); // by default - mailbox never was processed before } var imapIntervals = new ImapIntervals(folderUids.UnhandledUidIntervals); var beginDateUid = folderUids.BeginDateUid; IList <UniqueId> allUids; try { allUids = folder.Fetch(0, -1, MessageSummaryItems.UniqueId, CancelToken).Select(r => r.UniqueId).ToList(); } catch (NotSupportedException) { 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(); } foreach (var uidsInterval in imapIntervals.GetUnhandledIntervalsCopy()) { var interval = uidsInterval; var uidsCollection = allUids.Select(u => u) .Where(u => u.Id <= interval.To && u.Id >= interval.From) .OrderByDescending(x => x) .ToList(); if (!uidsCollection.Any()) { if (!uidsInterval.IsToUidMax()) { imapIntervals.AddHandledInterval(uidsInterval); } continue; } var first = uidsCollection.First().Id; var toUid = (int)(uidsInterval.IsToUidMax() ? first : Math.Max(uidsInterval.To, first)); var infoList = folder.Fetch(limitMessages > 0 ? uidsCollection.Take(limitMessages * 3).ToList() : uidsCollection, MessageSummaryItems.Flags | MessageSummaryItems.GMailLabels | MessageSummaryItems.InternalDate); foreach (var uid in uidsCollection) { try { if (!Imap.IsConnected || CancelToken.IsCancellationRequested) { break; } var message = folder.GetMessage(uid, CancelToken); var uid1 = uid; var info = infoList.FirstOrDefault(t => t.UniqueId == uid1); message.FixDateIssues(info != null ? info.InternalDate : null, Log); if (message.Date < Account.BeginDate) { Log.Debug("Skip message (Date = {0}) on BeginDate = {1}", message.Date, Account.BeginDate); imapIntervals.SetBeginIndex(toUid); beginDateUid = toUid; break; } var unread = info != null && (info.UserFlags.Contains("\\Unseen") || info.Flags.HasValue && !info.Flags.Value.HasFlag(MessageFlags.Seen)); message.FixEncodingIssues(Log); OnGetMessage(message, uid.Id.ToString(), unread, mailFolder); loaded++; } catch (OperationCanceledException) { break; } catch (Exception e) { Log.Error( "ProcessMessages() Tenant={0} User='******' Account='{2}', MailboxId={3}, UID={4} Exception:\r\n{5}\r\n", Account.TenantId, Account.UserId, Account.EMail.Address, Account.MailBoxId, uid, e); if (uid != uidsCollection.First() && (int)uid.Id != toUid) { imapIntervals.AddHandledInterval(new UidInterval((int)uid.Id + 1, toUid)); } toUid = (int)uid.Id - 1; if (e is IOException) { break; // stop checking other mailboxes } continue; } // after successfully message saving - lets update imap intervals state imapIntervals.AddHandledInterval( new UidInterval( uid.Id == uidsCollection.Last().Id&& uidsInterval.IsFromUidMin() ? uidsInterval.From : (int)uid.Id, toUid)); toUid = (int)uid.Id - 1; if (limitMessages > 0 && loaded >= limitMessages) { break; } } if (CancelToken.IsCancellationRequested || limitMessages > 0 && loaded >= limitMessages) { break; } } var updatedImapFolderUids = new ImapFolderUids(imapIntervals.ToIndexes(), beginDateUid); if (!Account.ImapIntervals.Keys.Contains(folder.Name)) { Account.ImapFolderChanged = true; Account.ImapIntervals.Add(folder.Name, updatedImapFolderUids); } else if (Account.ImapIntervals[folder.Name] != updatedImapFolderUids) { Account.ImapFolderChanged = true; Account.ImapIntervals[folder.Name] = updatedImapFolderUids; } return(loaded); }
private void setMailContent(ImapClient client, int pagenumber, IMailFolder type) { int maxPage = type.Count / 20; if (type.Count % 20 != 0) { maxPage++; } else { maxPage = 0; } if (type.Count > 20) { for (int i = type.Count - ((pagenumber - 1) * 20) - 1; i >= type.Count - (pagenumber * 20); i--) { var message = type.GetMessage(i); var info = type.Fetch(new[] { i }, MessageSummaryItems.Flags | MessageSummaryItems.GMailLabels); ListViewItem item = new ListViewItem(); if (info[0].Flags.Value.HasFlag(MessageFlags.Seen)) { item.ForeColor = Color.FromArgb(0, 174, 219); } string[] getFrom = message.From.ToString().Split('"'); if (getFrom.Length == 1) { item.Text = message.From.ToString(); } else { item.Text = getFrom[1]; } if (message.Subject == "") { item.SubItems.Add("[no subject]"); } else { item.SubItems.Add(message.Subject); } item.SubItems.Add(message.Date.ToString()); content.Items.Add(item); } client.Disconnect(true); pageNumber = pagenumber; mailPages.selectedIndex = pageNumber - 1; if (pagenumber == 1) { changePageMinus.Hide(); changePagePlus.Show(); } if (pagenumber == maxPage) { changePagePlus.Hide(); changePageMinus.Show(); } if (pagenumber > 1 && pagenumber < maxPage) { changePagePlus.Show(); changePageMinus.Show(); } } if (type.Count == 0) { ListViewItem item = new ListViewItem(); item.Text = "No mail in this box."; content.Items.Add(item); changePageMinus.Hide(); changePagePlus.Hide(); } else { for (int i = type.Count - 1; i >= 0; i--) { var message = type.GetMessage(i); var info = type.Fetch(new[] { i }, MessageSummaryItems.Flags | MessageSummaryItems.GMailLabels); ListViewItem item = new ListViewItem(); if (info[0].Flags.Value.HasFlag(MessageFlags.Seen)) { item.ForeColor = Color.FromArgb(0, 174, 219); } string [] getFrom = message.From.ToString().Split('"'); if (getFrom.Length == 1) { item.Text = message.From.ToString(); } else { item.Text = getFrom[1]; } if (message.Subject == "") { item.SubItems.Add("[no subject]"); } else { item.SubItems.Add(message.Subject); } item.SubItems.Add(message.Date.ToString()); content.Items.Add(item); } client.Disconnect(true); pageNumber = pagenumber; mailPages.selectedIndex = pageNumber - 1; } if (pagenumber == maxPage) { changePagePlus.Hide(); changePageMinus.Show(); } if (pagenumber == 1) { changePageMinus.Hide(); changePagePlus.Show(); } if (maxPage == 1 || maxPage == 0) { changePageMinus.Hide(); changePagePlus.Hide(); } }