public ImapClient() { client = new ImapX.ImapClient(); client.Behavior.MessageFetchMode = ImapX.Enums.MessageFetchMode.Tiny; client.Behavior.ExamineFolders = false; client.Behavior.FolderTreeBrowseMode = ImapX.Enums.FolderTreeBrowseMode.Lazy; }
public static IList <ImapX.Message> Read(string userName, string password, string folder, string search) { var server = "imap.gmail.com"; using (var client = new IX.ImapClient(server, true, false)) { if (client.Connect()) { if (client.Login(userName, password)) { //var messages = client.Folders.Inbox.Search("UID SEARCH FROM \"[email protected]\""); try { return(client.Folders.Inbox.Search(search)); } catch (Exception exc) { throw new ApplicationException(new { userName, folder, server, search } +"", exc); } } else { throw new ApplicationException(new { userName, folder, server, Login = "******" } +""); } } else { throw new ApplicationException(new { userName, folder, server, Connect = "Error" } +""); } } }
private static void test() { var server = "imap.gmail.com"; var login = "******"; var password = "******"; var attachmentsPath = @"C:\test"; var inboxFolderName = "INBOX"; var processedFolderName = "PROCESSED"; var processedMessages = new List <Message>(); var client = new ImapX.ImapClient(server, true); var messages = client.Folders.Inbox.Search("UNSEEN"); // THIS LINE takes like 5-10 seconds to complete foreach (var item in messages) { if (item.Subject.Contains("Click link to post!")) { string s = item.Subject; } } var inboxFolder = client.Folders.FirstOrDefault(f => f.Name == inboxFolderName); if (inboxFolder == null) { return; } inboxFolder.Messages.Download(); }
//public FolderName CurrentFolder { get; set; } public ImapClient(string host, bool useSsl) { _client = new ImapX.ImapClient(host, useSsl); if (!_client.Connect()) { // connection not successful throw new ConnectionException("Connection not succeessful"); } }
public void SetSeen(List <Message> messages) { bool connected = false; string username = Email; string password = Password; int port = ImapPort; bool useSSL = ImapSSL; try { if (ImapClient == null) { ImapClient = new ImapX.ImapClient(ImapServer, ImapPort, ImapSSL); } if (!ImapClient.IsConnected) { ImapClient.Connect(); } if (ImapClient.IsConnected) { if (!ImapClient.IsAuthenticated) { ImapClient.Login(Email, Password); } if (ImapClient.IsAuthenticated) { connected = true; } } } catch (Exception e) { logger.Error("Не удалось установить соединение и авторизоваться на сервере " + (ImapServer ?? "") + ".\r\nУдаленный порт: " + ImapPort + "\r\nШифрование:" + (ImapSSL ? "Включено" : "Выключено") + "\r\nТекст ошибки:", e); connected = false; } if (connected) { try { var folder = ImapClient.Folders.Inbox; foreach (var message in messages) { message.Seen = true; message.Remove(); } } catch (Exception e) { logger.Error("Ошибка при отметке о чтении писем на почтовом ящике " + (Email ?? "") + ".\r\nАдрес сервера:" + (ImapServer ?? "") + ".\r\nУдаленный порт: " + ImapPort + "\r\nШифрование:" + (ImapSSL ? "Включено" : "Выключено") + "\r\nТекст ошибки:", e); } } ImapClient = null; }
public static ImapX.Collections.MessageCollection loadFolder(string name, ImapX.ImapClient client) { if (name == "INBOX") { client.Folders[name].Messages.Download("ALL", ImapX.Enums.MessageFetchMode.Tiny, 10); return(client.Folders[name].Messages); } else { client.Folders["[Gmail]"].SubFolders[name].Messages.Download("ALL", ImapX.Enums.MessageFetchMode.Tiny, 10); return(client.Folders["[Gmail]"].SubFolders[name].Messages); } }
public MailImapX(string server, string login, string password) { _server = server; _login = login; _password = password; _client = new ImapX.ImapClient(server, true); if (!_client.Connect()) { return; } if (!_client.Login(_login, _password)) { return; } }
public static List <Folder> GetFolders(ImapX.ImapClient client) { var folders = new List <Folder>(); folders.Add(client.Folders.Inbox); for (int i = 0; i < client.Folders["[Gmail]"].SubFolders.Count(); i++) { folders.Add(client.Folders["[Gmail]"].SubFolders[i]); } // Before returning start the idling client.Folders.Inbox.StartIdling(); // And continue to listen for more. client.Folders.Inbox.OnNewMessagesArrived += Inbox_OnNewMessagesArrived; return(folders); }
private MessageCollection FetchMessages(string host, string login, string pass, string from, DateTime startDate, DateTime endDate) { var client = new ImapX.ImapClient(host, 993, true); client.Connection(); client.LogIn(login, pass); string imapQuery = string.Format("FROM \"{0}\" BEFORE {1} SINCE {2}", from, endDate.ToString("dd-MMM-yyyy", CultureInfo.InvariantCulture), startDate.ToString("dd-MMM-yyyy", CultureInfo.InvariantCulture)); var messages = client.Folders["INBOX"].Search(imapQuery, false); foreach (var m in messages) { m.Process(); } return(messages); }
public static List <Data.Entities.Email> getGMailEmail(string inboxPath, string username, string password) { List <Data.Entities.Email> emails = new List <Data.Entities.Email>(); Data.Entities.Email email = null; bool isHtml = true; ImapX.ImapClient client = new ImapX.ImapClient("imap.gmail.com", 993, true); bool result = false; result = client.Connection(); result = client.LogIn(username, password); if (result) { ImapX.FolderCollection folders = client.Folders; ImapX.MessageCollection messages = client.Folders["export"].Search("ALL", true); // .Search("export", true); //true - means all message parts will be received from server if (messages != null && messages.Count > 0) { for (int i = 0; i < messages.Count; i++) { email = new Data.Entities.Email(); email.From = messages[i].From.DisplayName; email.Subject = messages[i].Subject; email.TextBody = messages[i].GetDecodedBody(out isHtml); //email.TextBody = messages[i].TextBody.TextData; email.ReceivedDate = messages[i].Date; emails.Add(email); } } } return(emails); }
public static List<Data.Email> getGMailEmail(string inboxPath, string username, string password) { List<Data.Email> emails = new List<Data.Email>(); Data.Email email = null; bool isHtml = true; ImapX.ImapClient client = new ImapX.ImapClient("imap.gmail.com", 993, true); bool result = false; result = client.Connection(); result = client.LogIn(username, password); if (result) { ImapX.FolderCollection folders = client.Folders; ImapX.MessageCollection messages = client.Folders["export"].Search("ALL", true); // .Search("export", true); //true - means all message parts will be received from server if (messages != null && messages.Count > 0) { for (int i = 0; i < messages.Count; i++) { email = new Data.Email(); email.From = messages[i].From.DisplayName; email.Subject = messages[i].Subject; email.TextBody = messages[i].GetDecodedBody(out isHtml); //email.TextBody = messages[i].TextBody.TextData; email.ReceivedDate = messages[i].Date; emails.Add(email); } } } return emails; }
protected override bool Do() { int MaxCount = 3; int CurrCount = 0; Action("Подключение к почте", MaxCount, CurrCount++); lines.AppendLine(DateTime.Now.ToString() + " - подключение к почте"); ImapX.ImapClient Client; if (Settings.AutoCrypto) { Client = new ImapX.ImapClient(Settings.MailImap, Settings.MailPort, Settings.AutoCrypto); } else { Client = new ImapX.ImapClient(Settings.MailImap, Settings.MailPort, Settings.MailSecure); } if (!Client.Connect()) { Action("Подключение к почте не удалось: проверьте настройки подключения либо сервер не доступен", MaxCount, CurrCount++); lines.AppendLine(DateTime.Now.ToString() + " - подключение к почте не удалось"); return(true); } if (!Client.Login(Settings.MailName, Settings.MailPass)) { Action("Подключение к почте не удалось: проверьте логин и/или пароль", MaxCount, CurrCount++); lines.AppendLine(DateTime.Now.ToString() + " - подключение к почте не удалось"); return(true); } MaxCount++; Action("Поиск обновлений", MaxCount, CurrCount++); lines.AppendLine(DateTime.Now.ToString() + " - успешное подключение к почте"); var SearchedSubject = Path.GetFileNameWithoutExtension(Settings.FileName); //var messages = Client.Folders.Inbox.Search("CHARSET UTF-8 UNSEEN SUBJECT {" + Encoding.GetEncoding("UTF-8").GetByteCount(SearchedSubject) + "}\r\n" + SearchedSubject, ImapX.Enums.MessageFetchMode.Headers).ToList(); var messages = Client.Folders.Inbox.Search("UNSEEN", ImapX.Enums.MessageFetchMode.Headers).ToList(); MaxCount += messages.Count + 3; Action("Сканирование писем", MaxCount, CurrCount++); int LastDateIndex = -1; SearchedSubject = "обновление " + SearchedSubject.ToLower(); for (int i = 0; i < messages.Count; i++) { if (messages[i].Subject.ToLower() == SearchedSubject && messages[i].Date > Date) { LastDateIndex = i; Action(MaxCount, CurrCount++); } else { Action(MaxCount, CurrCount++); } } if (LastDateIndex > -1) { MaxCount++; Action("Получение файла обновлений", MaxCount, CurrCount++); messages[LastDateIndex].Download(ImapX.Enums.MessageFetchMode.Full); //messages[i].Attachments[0].Download(); if (messages[LastDateIndex].Attachments.Length == 1) { Action("Файл обновлений обнаружен", MaxCount, CurrCount++); lines.AppendLine(DateTime.Now.ToString() + " - обновление найдено"); Date = messages[LastDateIndex].Date.Value; var str = messages[LastDateIndex].Attachments[0].GetTextData(); var Index = str.IndexOf(")IMAPX"); if (Index > -1) { str = str.Substring(0, Index); } //messages[Mn].Attachments[0].Save(TempPath, FileName); var Bytes = Convert.FromBase64String(str); FilePath = Path.GetTempPath() + messages[LastDateIndex].Attachments[0].FileName; using (var fs = new FileStream(FilePath, FileMode.Create)) { fs.Write(Bytes, 0, Bytes.Length); } } else { Action("Файл обновлений не обнаружен", MaxCount, CurrCount++); } } else { Action("Обновления не обнаружены", MaxCount, CurrCount++); } Action("Закрытие почты", MaxCount, CurrCount++); lines.AppendLine(DateTime.Now.ToString() + " - закрытие почты"); Client.Disconnect(); Action("Почта закрыта", MaxCount, CurrCount++); return(true); }
public void SetSeen(List<Message> messages) { bool connected = false; string username = Email; string password = Password; int port = ImapPort; bool useSSL = ImapSSL; try { if (ImapClient == null) ImapClient = new ImapX.ImapClient(ImapServer, ImapPort, ImapSSL); if (!ImapClient.IsConnected) ImapClient.Connect(); if (ImapClient.IsConnected) { if (!ImapClient.IsAuthenticated) ImapClient.Login(Email, Password); if (ImapClient.IsAuthenticated) { connected = true; } } } catch (Exception e) { logger.Error("Не удалось установить соединение и авторизоваться на сервере " + (ImapServer ?? "") + ".\r\nУдаленный порт: " + ImapPort + "\r\nШифрование:" + (ImapSSL ? "Включено" : "Выключено") + "\r\nТекст ошибки:", e); connected = false; } if (connected) { try { var folder = ImapClient.Folders.Inbox; foreach (var message in messages) { message.Seen = true; message.Remove(); } } catch (Exception e) { logger.Error("Ошибка при отметке о чтении писем на почтовом ящике " + (Email ?? "") + ".\r\nАдрес сервера:" + (ImapServer?? "") + ".\r\nУдаленный порт: " + ImapPort + "\r\nШифрование:" + (ImapSSL ? "Включено" : "Выключено") + "\r\nТекст ошибки:" , e); } } ImapClient = null; }
public Message[] LoadMessages() { Message[] messages = null; try { bool connected = false; string username = Email; string password = Password; int port = ImapPort; bool useSSL = ImapSSL; try { if (ImapClient == null) ImapClient = new ImapX.ImapClient(ImapServer, ImapPort, ImapSSL); if (!ImapClient.IsConnected) ImapClient.Connect(); if (ImapClient.IsConnected) { if (!ImapClient.IsAuthenticated) ImapClient.Login(Email, Password); if (ImapClient.IsAuthenticated) { connected = true; } } } catch (Exception e) { logger.Error("Не удалось установить соединение и авторизоваться на сервере " + (ImapServer ?? "") + ".\r\nУдаленный порт: " + ImapPort + "\r\nШифрование:" + (ImapSSL ? "Включено" : "Выключено") + "\r\nТекст ошибки:", e); connected = false; } if (connected) { var folder = ImapClient.Folders.Inbox; messages = folder.Search("UNSEEN", MessageFetchMode.Headers); string deamon = "MAILER-DAEMON"; foreach (var mes in messages) { if (mes.From != null && mes.From.Address != null && mes.From.Address.ToLower().Contains(deamon.ToLower())) { mes.Seen = true; mes.Remove(); } } messages = folder.Search("UNSEEN", MessageFetchMode.Basic); } } catch (Exception e) { logger.Error("Ошибка при загрузке сообщений с почтового ящика " + (Email ?? "") + ".\r\nАдрес сервера:" + (ImapServer?? "") + ".\r\nУдаленный порт: " + ImapPort + "\r\nШифрование:" + (ImapSSL ? "Включено" : "Выключено") + "\r\nТекст ошибки:" ,e); } ImapClient = null; return messages; }
internal Message(long uId, ImapClient client, Folder folder) : this(client, folder) { UId = uId; }
public Message[] LoadMessages() { Message[] messages = null; try { bool connected = false; string username = Email; string password = Password; int port = ImapPort; bool useSSL = ImapSSL; try { if (ImapClient == null) { ImapClient = new ImapX.ImapClient(ImapServer, ImapPort, ImapSSL); } if (!ImapClient.IsConnected) { ImapClient.Connect(); } if (ImapClient.IsConnected) { if (!ImapClient.IsAuthenticated) { ImapClient.Login(Email, Password); } if (ImapClient.IsAuthenticated) { connected = true; } } } catch (Exception e) { logger.Error("Не удалось установить соединение и авторизоваться на сервере " + (ImapServer ?? "") + ".\r\nУдаленный порт: " + ImapPort + "\r\nШифрование:" + (ImapSSL ? "Включено" : "Выключено") + "\r\nТекст ошибки:", e); connected = false; } if (connected) { var folder = ImapClient.Folders.Inbox; messages = folder.Search("UNSEEN", MessageFetchMode.Headers); string deamon = "MAILER-DAEMON"; foreach (var mes in messages) { if (mes.From != null && mes.From.Address != null && mes.From.Address.ToLower().Contains(deamon.ToLower())) { mes.Seen = true; mes.Remove(); } } messages = folder.Search("UNSEEN", MessageFetchMode.Basic); } } catch (Exception e) { logger.Error("Ошибка при загрузке сообщений с почтового ящика " + (Email ?? "") + ".\r\nАдрес сервера:" + (ImapServer ?? "") + ".\r\nУдаленный порт: " + ImapPort + "\r\nШифрование:" + (ImapSSL ? "Включено" : "Выключено") + "\r\nТекст ошибки:", e); } ImapClient = null; return(messages); }
public MessageContent(ImapClient client, Message message) { _client = client; _message = message; Parameters = new Dictionary <string, string>(); }
internal GMailMessageThread(ImapClient client, Folder folder, long threadId) { Id = threadId; Messages = new MessageCollection(client, folder); }
internal MessageBody(ImapClient client, MessageContent textContent, MessageContent htmlContent) { _client = client; _textContent = textContent; _htmlContent = htmlContent; }