private void _bRetrieveMessages_Click(object sender, EventArgs e) { // We create Imap client imap = new Imap4Client(); try { // We connect to the imap4 server imap.Connect(_tbImap4Server.Text); this.AddLogEntry(string.Format("Connection to {0} successfully", _tbImap4Server.Text)); // Login to mail box imap.Login(_tbUserName.Text, _tbPassword.Text); this.AddLogEntry(string.Format("Login to {0} successfully", _tbImap4Server.Text)); inbox = imap.SelectMailbox("inbox"); if (inbox.MessageCount > 0) { for (int i = 1; i < inbox.MessageCount + 1; i++) { ActiveUp.Net.Mail.Message message = inbox.Fetch.MessageObject(i); ListViewItem lvi = new ListViewItem(); lvi.Text = i.ToString("0000"); lvi.SubItems.AddRange(new string[] { message.Subject}); lvi.Tag = message; _lvMessages.Items.Add(lvi); this.AddLogEntry(string.Format("{3} Subject: {0} From :{1} Message Body {2}" , message.Subject, message.From.Email, message.BodyText, i.ToString("0000"))); } } else { this.AddLogEntry("There is no unanswered messages in the imap4 account"); } } catch (Imap4Exception iex) { this.AddLogEntry(string.Format("Imap4 Error: {0}", iex.Message)); } catch (Exception ex) { this.AddLogEntry(string.Format("Failed: {0}", ex.Message)); } }
//private void ConnectPop() //{ // Pop3Client pop3Client; // pop3Client = new ActiveUp.Net.Mail.Pop3Client(); // pop3Client.Connect("pop3.smartcloudpt.pt", 995 ,true); // pop3Client.Authenticate(textBox1.Text, textBox2.Text); // bs = new BindingSource(); // int count = pop3Client.GetMessageCount(); // DataTable dtMessages = new DataTable(); // dtMessages.Columns.Add("MessageNumber"); // dtMessages.Columns.Add("From"); // dtMessages.Columns.Add("Subject"); // dtMessages.Columns.Add("DateSent"); // int counter = 0; // for (int i = count; i >= 1; i--) // { // OpenPop.Mime.Message message = pop3Client.GetMessage(i); // dtMessages.Rows.Add(); // dtMessages.Rows[dtMessages.Rows.Count - 1]["MessageNumber"] = i; // dtMessages.Rows[dtMessages.Rows.Count - 1]["From"] = message.Headers.From; // dtMessages.Rows[dtMessages.Rows.Count - 1]["Subject"] = message.Headers.Subject; // dtMessages.Rows[dtMessages.Rows.Count - 1]["DateSent"] = message.Headers.DateSent; // counter++; // if (counter > 5) // { // // break; // } // } // bs.DataSource = dtMessages; //} private void connectImap() { Imap4Client imap = new Imap4Client(); imap.ConnectSsl(servertxt.Text, 993); imap.Login(textBox1.Text, textBox2.Text); ActiveUp.Net.Mail.Mailbox mbox = imap.SelectMailbox("Inbox"); MessageCollection messages; // List<long> uids; if (todayRB.Checked) { //uids = imap.Search(Expression.Since(DateTime.Now)); messages = mbox.SearchParse("SINCE " + DateTime.Now.ToString("dd-MMM-yyyy hh:mm:ss")); } else if (specRb.Checked) { //uids = imap.Search(Expression.And(Expression.Since(specDate.Value),Expression.Before(specDate.Value))); messages = mbox.SearchParse("SINCE " + specDate.Value.ToString("dd-MMM-yyyy hh:mm:ss") + " NOT BEFORE " + specDate.Value.AddDays(-1).ToString("dd-MM-yyyy hh:mm:ss")); } else { //uids = imap.Search(Expression.And(Expression.Since(deDP.Value), Expression.Before(ateDP.Value))); messages = mbox.SearchParse("SINCE " + deDP.Value.ToString("dd-MMM-yyyy hh:mm:ss") + " NOT BEFORE " + ateDP.Value.AddDays(-1).ToString("dd-MM-yyyy hh:mm:ss")); } foreach (ActiveUp.Net.Mail.Message mail in messages) { foreach (MimePart item in mail.Attachments) { item.StoreToFile(pathUploadTxt.Text); } Console.WriteLine(mail.Date + " - " + mail.Subject); } // foreach (long uid in uids) // { // byte[] eml = imap.GetMessageByUID(uid); // IMail message = new MailBuilder().CreateFromEml(eml); // foreach (MimeData mime in message.Attachments) // { // mime.Save( pathUploadTxt.Text+"\\" + mime.SafeFileName); // } // Console.WriteLine(message.Subject); // Console.WriteLine(message.Text); // } //// MessageBox.Show("Leu emails"); // imap.Close(true); }
/// <summary> /// Same as SelectMailbox() except that the mailbox is opened with read-only permission. /// </summary> /// <param name="mailboxName">The mailbox to be examined.</param> /// <returns>The examined mailbox.</returns> /// <example> /// <code> /// C# /// /// Imap4Client imap = new Imap4Client(); /// imap.Connect("mail.myhost.com"); /// imap.Login("user","pass"); /// Mailbox mbox = imap.ExamineMailbox("inbox.Staff"); /// //The inbox.Staff mailbox is now selected (read-only). /// int recentMessageCount = mbox.Recent; /// //There are recentMessageCount messages that haven't been read in inbox.Staff. /// imap.Disconnect(); /// /// VB.NET /// /// Dim imap As New Imap4Client /// imap.Connect("mail.myhost.com") /// imap.Login("user","pass") /// Dim mbox As Mailbox = imap.ExamineMailbox("inbox.Staff") /// 'The inbox.Staff mailbox is now selected (read-only). /// Dim recentMessageCount As Integer = mbox.Recent /// 'There are recentMessageCount messages that haven't been read in inbox.Staff. /// imap.Disconnect() /// /// JScript.NET /// /// var imap:Imap4Client = new Imap4Client(); /// imap.Connect("mail.myhost.com"); /// imap.Login("user","pass"); /// var mbox:Mailbox = imap.ExamineMailbox("inbox.Staff"); /// //The inbox.Staff mailbox is now selected (read-only). /// int recentMessageCount = mbox.Recent; /// //There are recentMessageCount messages that haven't been read in inbox.Staff. /// imap.Disconnect(); /// </code> /// </example> public Mailbox ExamineMailbox(string mailboxName) { ActiveUp.Net.Mail.Mailbox mailbox = new ActiveUp.Net.Mail.Mailbox(); string response = this.Command("examine \"" + mailboxName + "\""); string[] lines = System.Text.RegularExpressions.Regex.Split(response, "\r\n"); mailbox.MessageCount = System.Convert.ToInt32(ActiveUp.Net.Mail.Imap4Client.FindLine(lines, "EXISTS").Split(' ')[1]); mailbox.Recent = System.Convert.ToInt32(ActiveUp.Net.Mail.Imap4Client.FindLine(lines, "RECENT").Split(' ')[1]); mailbox.FirstUnseen = (response.ToLower().IndexOf("[unseen") != -1) ? System.Convert.ToInt32( ActiveUp.Net.Mail.Imap4Client.FindLine(lines, "[UNSEEN ").Split(' ')[3] .TrimEnd(']')) : 0; mailbox.UidValidity = System.Convert.ToInt64( ActiveUp.Net.Mail.Imap4Client.FindLine(lines, "[UIDVALIDITY ").Split(' ')[3].TrimEnd(']')); foreach (string str in ActiveUp.Net.Mail.Imap4Client.FindLine(lines, " FLAGS").Split(' ')) if (str.StartsWith("(\\") || str.StartsWith("\\")) mailbox.ApplicableFlags.Add(str.Trim(new char[] {' ', '\\', ')', '('})); if (response.ToLower().IndexOf("[permanentflags") != -1) foreach (string str in ActiveUp.Net.Mail.Imap4Client.FindLine(lines, "[PERMANENTFLAGS").Split(' ')) if (str.StartsWith("(\\") || str.StartsWith("\\")) mailbox.PermanentFlags.Add(str.Trim(new char[] {' ', '\\', ')', '('})); mailbox.Permission = ActiveUp.Net.Mail.MailboxPermission.ReadOnly; mailbox.Name = mailboxName; mailbox.SourceClient = this; return mailbox; }
/// <summary> /// Selects a mailbox on the server. /// </summary> /// <param name="mailboxName">The mailbox to be selected.</param> /// <returns>The selected mailbox.</returns> /// <example> /// <code> /// C# /// /// Imap4Client imap = new Imap4Client(); /// imap.Connect("mail.myhost.com"); /// imap.Login("user","pass"); /// Mailbox mbox = imap.SelectMailbox("inbox.Staff"); /// //The inbox.Staff mailbox is now selected. /// mbox.Empty(true); /// //Mailbox inbox.Staff is now empty. /// imap.Disconnect(); /// /// VB.NET /// /// Dim imap As New Imap4Client /// imap.Connect("mail.myhost.com") /// imap.Login("user","pass") /// Dim mbox As Mailbox = imap.SelectMailbox("inbox.Staff") /// 'The inbox.Staff mailbox is now selected. /// mbox.Empty(true) /// 'Mailbox inbox.Staff is now empty. /// imap.Disconnect() /// /// JScript.NET /// /// var imap:Imap4Client = new Imap4Client(); /// imap.Connect("mail.myhost.com"); /// imap.Login("user","pass"); /// var mbox:Mailbox = imap.SelectMailbox("inbox.Staff"); /// //The inbox.Staff mailbox is now selected. /// mbox.Empty(true); /// //Mailbox inbox.Staff is now empty. /// imap.Disconnect(); /// </code> /// </example> public Mailbox SelectMailbox(string mailboxName) { var mailbox_name = renderSafeParam(mailboxName); ActiveUp.Net.Mail.Mailbox mailbox = new ActiveUp.Net.Mail.Mailbox(); string response = this.Command("select \"" + mailbox_name + "\""); string[] lines = System.Text.RegularExpressions.Regex.Split(response, "\r\n"); // message count. int messageCount = 0; try { messageCount = System.Convert.ToInt32(ActiveUp.Net.Mail.Imap4Client.FindLine(lines, "EXISTS").Split(' ')[1]); } catch (Exception) { } mailbox.MessageCount = messageCount; // recent. int recent = 0; try { recent = System.Convert.ToInt32(ActiveUp.Net.Mail.Imap4Client.FindLine(lines, "RECENT").Split(' ')[1]); } catch (Exception) { } mailbox.Recent = recent; // unseen. int unseen = 0; try { unseen = System.Convert.ToInt32( ActiveUp.Net.Mail.Imap4Client.FindLine(lines, "[UNSEEN ").Split(' ')[3].TrimEnd(']')); } catch (Exception) { } mailbox.FirstUnseen = (response.ToLower().IndexOf("[unseen") != -1) ? unseen : 0; // uid validity. int uidValidity = 0; try { uidValidity = System.Convert.ToInt32( ActiveUp.Net.Mail.Imap4Client.FindLine(lines, "[UIDVALIDITY ").Split(' ')[3].TrimEnd(']')); } catch (Exception) { } mailbox.UidValidity = uidValidity; // flags. foreach (string str in ActiveUp.Net.Mail.Imap4Client.FindLine(lines, " FLAGS").Split(' ')) { if (str.StartsWith("(\\") || str.StartsWith("\\")) { mailbox.ApplicableFlags.Add(str.Trim(new char[] {' ', '\\', ')', '('})); } } // permanent flags. if (response.ToLower().IndexOf("[permanentflags") != -1) { foreach (string str in ActiveUp.Net.Mail.Imap4Client.FindLine(lines, "[PERMANENTFLAGS").Split(' ')) { if (str.StartsWith("(\\") || str.StartsWith("\\")) { mailbox.PermanentFlags.Add(str.Trim(new char[] {' ', '\\', ')', '('})); } } } // read-write and read-only. if (response.ToLower().IndexOf("[read-write]") != -1) { mailbox.Permission = ActiveUp.Net.Mail.MailboxPermission.ReadWrite; } else if (response.ToLower().IndexOf("[read-only]") != -1) { mailbox.Permission = ActiveUp.Net.Mail.MailboxPermission.ReadOnly; } mailbox.Name = mailboxName; mailbox.SourceClient = this; return mailbox; }
// Returns: maxMessagesPerSession minus count of downloaded messages or zero if limit excided private int ProcessMessages( Mailbox mb, int folder_id, int last_uid, int max_messages_per_session, WaitHandle stop_event, string[] tags_names) { UpdateTimeCheckedIfNeeded(); int[] uids_collection; try { uids_collection = mb.UidSearch("UID " + (0 != last_uid ? last_uid : 1) + ":*") .Where(uid => uid != last_uid) .ToArray(); if (!uids_collection.Any()) throw new Exception("Empty folder"); } catch (Exception) { _log.Info("New messages not found."); return max_messages_per_session; } var stored_uid_list = new Dictionary<int, string>(); var stored_md5_list = new Dictionary<int, string>(); InvokeGetStoredMessagesUIDL_MD5(stored_uid_list, stored_md5_list); var tags_hash = tags_names.Aggregate(string.Empty, (current, name) => current + name).GetMD5Hash(); var new_messages = uids_collection .Select( item_uid => new { uid = item_uid, uidl = tags_names.Any() ? string.Format("{0}-{1}-{2}-{3}", item_uid, folder_id, mb.UidValidity, tags_hash) : string.Format("{0}-{1}-{2}", item_uid, folder_id, mb.UidValidity) }) .Where(msg => !stored_uid_list.Values.Contains(msg.uidl)) .OrderByDescending(msg => msg.uid) .ToDictionary(msg => msg.uid, id => id.uidl); var quota_error_flag = false; var update_folder_uid_flag = new_messages.Any(); int[] tags_ids = null; var message_ids_for_tag_update = new List<int>(); var tags_retrieved = false; foreach (var new_message in new_messages) { int last_founded_message_id = -1; try { if (stop_event.WaitOne(0)) { _log.Debug("Stop event occure."); break; } if (max_messages_per_session == 0) { _log.Debug("Limit of max messages per session is exceeded!"); update_folder_uid_flag = false; break; } // flags should be retrieved before message fetch - because mail server // could add seen flag right after message was retrieved by us var flags = mb.Fetch.UidFlags(new_message.Key); //Peek method didn't set \Seen flag on mail var message = mb.Fetch.UidMessageObjectPeek(new_message.Key); UpdateTimeCheckedIfNeeded(); if (message.Date < Account.BeginDate) { _log.Debug("Skip message (Date = {0}) on BeginDate = {1}", message.Date, Account.BeginDate); break; } var unique_identifier = string.Format("{0}|{1}|{2}|{3}", message.From.Email, message.Subject, message.DateString, message.MessageId); var header_md5 = unique_identifier.GetMD5(); //Get tags ids for folder before message proccessing only once if (!tags_retrieved) { tags_ids = tags_names.Any() ? InvokeOnGetOrCreateTags(tags_names) : null; tags_retrieved = true; } if (folder_id == MailFolder.Ids.inbox || !message.To.Exists(email => email.Email.ToLowerInvariant() .Equals(message.From.Email.ToLowerInvariant()) ) ) { var found_message_id = stored_md5_list .Where(el => el.Value == header_md5) .Select(el => el.Key) .FirstOrDefault(); if (found_message_id > 0) { InvokeOnUpdateUidl(found_message_id, new_message.Value); last_founded_message_id = found_message_id; message_ids_for_tag_update.Add(found_message_id); //Todo: Remove id if exception happened continue; // Skip saving founded message } } var unread = null == flags["seen"]; InvokeOnRetrieve(message, folder_id, new_message.Value, header_md5, unread, tags_ids); } catch (IOException io_ex) { if (io_ex.Message.StartsWith("Unable to write data to the transport connection") || io_ex.Message.StartsWith("Unable to read data from the transport connection")) { _log.Error("ProcessMessages() Account='{0}': {1}", Account.EMail.Address, io_ex.ToString()); message_ids_for_tag_update.Remove(last_founded_message_id); update_folder_uid_flag = false; max_messages_per_session = 0; // stop checking other mailboxes break; } } catch (MailBoxOutException ex) { _log.Info("ProcessMessages() Account='{0}': {1}", Account.EMail.Address, ex.Message); message_ids_for_tag_update.Remove(last_founded_message_id); update_folder_uid_flag = false; max_messages_per_session = 0; // stop checking other mailboxes break; } catch (TenantQuotaException qex) { _log.Info("Tenant {0} quota exception: {1}", Account.TenantId, qex.Message); message_ids_for_tag_update.Remove(last_founded_message_id); quota_error_flag = true; update_folder_uid_flag = false; } catch (Exception e) { _log.Error("ProcessMessages() Account='{0}', MessageId={1} Exception:\r\n{2}\r\n", Account.EMail.Address, new_message, e.ToString()); update_folder_uid_flag = false; message_ids_for_tag_update.Remove(last_founded_message_id); } UpdateTimeCheckedIfNeeded(); max_messages_per_session--; } if (tags_ids != null && tags_ids.Length > 0 && message_ids_for_tag_update.Count > 0) { InvokeOnUpdateMessagesTags(Account.TenantId, Account.UserId, tags_ids, message_ids_for_tag_update.ToArray()); } if (update_folder_uid_flag) { var max_uid = new_messages.Keys.Max(); if(Account.ImapFolders.Keys.Contains(mb.Name)) Account.ImapFolders[mb.Name] = max_uid; else Account.ImapFolders.Add(mb.Name, max_uid); Account.ImapFolderChanged = true; } InvokeOnDone(quota_error_flag); return max_messages_per_session; }
/// <summary> /// Subscribe the client to the inbox /// </summary> private void SubscribeToInbox() { inbox = client.SelectMailbox("INBOX"); inbox.Subscribe(); }
private int LoadMailboxMessage(Mailbox mb, int folderId, int maxMessagesPerSession, string[] tagsNames, out bool quotaErrorFlag) { UpdateTimeCheckedIfNeeded(); ImapFolderUids folderUids; if (!Account.ImapIntervals.TryGetValue(mb.Name, out folderUids)) folderUids = new ImapFolderUids(); // by default - mailbox never was processed before var imapIntervals = new ImapIntervals(folderUids.UnhandledUidIntervals); var beginDateUid = folderUids.BeginDateUid; quotaErrorFlag = false; int[] tagsIds = null; var tagsRetrieved = false; var allUids = mb.UidSearch("1:*").OrderBy(i => i).SkipWhile(i => i < beginDateUid).ToList(); foreach (var uidsInterval in imapIntervals.GetUnhandledIntervalsCopy()) { cancelToken.ThrowIfCancellationRequested(); if (!mb.SourceClient.IsConnected) break; if (maxMessagesPerSession == 0) break; var interval = uidsInterval; var uidsCollection = allUids.Select(u => u) .Where(u => u <= interval.To && u >= interval.From) .OrderByDescending(x => x) .ToList(); if (!uidsCollection.Any()) { if (!uidsInterval.IsToUidMax()) imapIntervals.AddHandledInterval(uidsInterval); continue; } var toUid = uidsInterval.IsToUidMax() ? uidsCollection.First() : Math.Max(uidsInterval.To, uidsCollection.First()); #region Loading messages foreach (var uid in uidsCollection) { var hasParseError = false; cancelToken.ThrowIfCancellationRequested(); try { if (!mb.SourceClient.IsConnected) { log.Warn("Imap4-server is disconnected. Skip another messages."); break; } log.Debug("Processing new message\tUID: {0}", uid); // flags should be retrieved before message fetch - because mail server // could add seen flag right after message was retrieved by us var flags = mb.Fetch.UidFlags(uid); //Peek method didn't set \Seen flag on mail var message = mb.Fetch.UidMessageObjectPeek(uid); if (message.HasParseError) { log.Error("ActiveUp: message parsed with some errors. MailboxId = {0} Message UID = {1}", Account.MailBoxId, uid); hasParseError = true; } UpdateTimeCheckedIfNeeded(); 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 uniqueIdentifier = string.Format("{0}|{1}|{2}|{3}", message.From.Email, message.Subject, message.DateString, message.MessageId); var headerMd5 = uniqueIdentifier.GetMd5(); //Get tags ids for folder before message proccessing only once if (!tagsRetrieved) { tagsIds = tagsNames.Any() ? InvokeOnGetOrCreateTags(tagsNames) : null; tagsRetrieved = true; } var unread = null == flags["seen"]; var uidl = string.Format("{0}-{1}", uid, folderId); RetrieveMessage(message, folderId, uidl, headerMd5, hasParseError, unread, tagsIds); } 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 (e is IOException || e is MailBoxOutException) { maxMessagesPerSession = 0; // stop checking other mailboxes } else if (e is TenantQuotaException) { quotaErrorFlag = true; } if (uid != uidsCollection.First() && uid != toUid) { imapIntervals.AddHandledInterval(new UidInterval(uid + 1, toUid)); } toUid = uid - 1; if (maxMessagesPerSession == 0) break; continue; } // after successfully message saving - lets update imap intervals state imapIntervals.AddHandledInterval( new UidInterval( uid == uidsCollection.Last() && uidsInterval.IsFromUidMin() ? uidsInterval.From : uid, toUid)); toUid = uid - 1; UpdateTimeCheckedIfNeeded(); maxMessagesPerSession--; if (maxMessagesPerSession != 0) continue; log.Info("Limit of max messages per session is exceeded!"); break; } #endregion } var updatedImapFolderUids = new ImapFolderUids(imapIntervals.ToIndexes(), beginDateUid); if (!Account.ImapIntervals.Keys.Contains(mb.Name)) { Account.ImapFolderChanged = true; Account.ImapIntervals.Add(mb.Name, updatedImapFolderUids); } else if (Account.ImapIntervals[mb.Name] != updatedImapFolderUids) { Account.ImapFolderChanged = true; Account.ImapIntervals[mb.Name] = updatedImapFolderUids; } return maxMessagesPerSession; }
private Header GetImapHeader(Mailbox mb, int uid) { var header_bytes = mb.Fetch.UidHeader(uid); var header = new Header {OriginalData = header_bytes}; var hdr = Encoding.GetEncoding("iso-8859-1") .GetString(header.OriginalData, 0, header.OriginalData.Length); hdr = RegxHeader.Match(hdr).Value; hdr = RegxUnfold.Replace(hdr, ""); var m = RegxHeaderLines.Match(hdr); while (m.Success) { try { var name = FormatFieldName(m.Value.Substring(0, m.Value.IndexOf(':'))); var value = Codec.RFC2047Decode(m.Value.Substring(m.Value.IndexOf(":", StringComparison.Ordinal) + 1)) .Trim('\r', '\n') .TrimStart(' '); if (name.Equals("received")) header.Trace.Add(Parser.ParseTrace(m.Value.Trim(' '))); else if (name.Equals("to")) header.To = Parser.ParseAddresses(value); else if (name.Equals("cc")) header.Cc = Parser.ParseAddresses(value); else if (name.Equals("bcc")) header.Bcc = Parser.ParseAddresses(value); else if (name.Equals("reply-to")) header.ReplyTo = Parser.ParseAddress(value); else if (name.Equals("from")) header.From = Parser.ParseAddress(value); else if (name.Equals("sender")) header.Sender = Parser.ParseAddress(value); else if (name.Equals("content-type")) header.ContentType = Parser.GetContentType(m.Value); else if (name.Equals("content-disposition")) header.ContentDisposition = Parser.GetContentDisposition(m.Value); header.HeaderFields.Add(name, value); header.HeaderFieldNames.Add(name, m.Value.Substring(0, m.Value.IndexOf(':'))); } catch (Exception parser_header_line_ex) { _log.Debug("Parser header field error: {0} ", parser_header_line_ex.ToString()); } m = m.NextMatch(); } return header; }
private Message GetImapMessageAfterParseError(Mailbox mb, int uid) { var header = GetImapHeader(mb, uid); var message = new Message(header); var eml_message_string = mb.Fetch.UidMessageString(uid); message.AddAttachmentFromString("original_message.eml", eml_message_string); return message; }