private List <string> CheckForMessages() { var messages = new List <string>(); _client = new ImapClient(_IMAPClientUri, true); if (_client.Connect() && _client.Login(_IMAPUsername, _IMAPPassword)) { try { var keyword = _subjectKeyword; var emails = _client.Folders.Inbox.Search(string.Format("UNSEEN SUBJECT \"{0}\"", keyword), ImapX.Enums.MessageFetchMode.Full); Console.WriteLine(string.Format("{0} emails", emails.Count())); foreach (var email in emails) { messages.Add(email.Body.Text); email.Remove(); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { _client.Logout(); _client.Disconnect(); } } else { Console.WriteLine("Bad email login"); } return(messages); }
private void CheckMailBox() { var authMethod = (AuthMethod)Enum.Parse(typeof(AuthMethod), GlobalConfiguration.Configuration.ImapAuthMethod, true); m_ImapClient = new ImapClient(GlobalConfiguration.Configuration.ImapHostName, GlobalConfiguration.Configuration.ImapPort, GlobalConfiguration.Configuration.ImapUserName, GlobalConfiguration.Configuration.ImapPassword, authMethod, GlobalConfiguration.Configuration.ImapUseSSL); GlobalConfiguration.Configuration.Logger.Info("Check input emails from {0}", GlobalConfiguration.Configuration.ImapUserName); SearchCondition search = null; search = SearchCondition.SentSince(m_LastCheckDate.AddMinutes(-10)); var list = m_ImapClient.Search(search); GlobalConfiguration.Configuration.Logger.Info("Found {0} emails from {1}", list.Count(), search); foreach (var uid in list) { m_LastCheckDate = DateTime.Now; if (uid <= LastMessageId.GetValueOrDefault(0)) { continue; } LastMessageId = uid; var emailMessage = m_ImapClient.GetMessage(uid, false); var message = new EmailMessage(emailMessage); message.ImapMessageId = uid.ToString(); Bus.Send(GlobalConfiguration.Configuration.ReceiveMessageQueueName, message); } m_ImapClient.Logout(); }
private List<string> CheckForMessages() { var messages = new List<string>(); _client = new ImapClient(_IMAPClientUri, true); if (_client.Connect() && _client.Login(_IMAPUsername, _IMAPPassword)) { try { var keyword = _subjectKeyword; var emails = _client.Folders.Inbox.Search(string.Format("UNSEEN SUBJECT \"{0}\"", keyword), ImapX.Enums.MessageFetchMode.Full); Console.WriteLine(string.Format("{0} emails", emails.Count())); foreach (var email in emails) { messages.Add(email.Body.Text); email.Remove(); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { _client.Logout(); _client.Disconnect(); } } else { Console.WriteLine("Bad email login"); } return messages; }
void OnDestroy() { isCheckingForEmail = false; client.Logout(); client.Disconnect(); Debug.LogWarning("Shutting down email checking."); }
private void button2_Click(object sender, EventArgs e) { UpdateTargetServerSettings(); using (ImapClient client = new ImapClient(targetServerSettings.Hostname, targetServerSettings.Port, targetServerSettings.UseSSL)) { if (client != null) { if (!client.IsConnected) { client.Connect(); } if (client.Login(targetServerSettings.Username, targetServerSettings.Password)) { client.Logout(); client.Disconnect(); MessageBox.Show("Connection succesful."); } else { MessageBox.Show("Username or password is incorrect, could not login"); } } else { MessageBox.Show("Failed to connect to host, please check hostname, port and SSL option"); } } }
public ActionResult Logout() { using (ImapClient Client = QLogin()) Client.Logout(); Session["UserName"] = null; Session.Abandon(); return(View("Login")); }
public void getFolders(string canvasid, int windowid) { ImapClient imp = new ImapClient(ccl.InputParams[2].ToString(), 993, ccl.InputParams[0].ToString(), ccl.InputParams[1].ToString(), true); List<string> mailboxes = imp.GetAllFolders(); foreach(string mb in mailboxes){ parameters.Add(mb); } imp.Logout(); }
public void Stop() { _cts?.Cancel(); _cts?.Dispose(); if (_messageProcessingTasks.Count > 0) { Task.WaitAll(_messageProcessingTasks.ToArray()); } _imapClient.Logout(); }
public void Revoke() { _credential = null; if (_email != null) { _email.Logout(); _email.Dispose(); _email = null; } }
public void getFolders(string canvasid, int windowid) { ImapClient imp = new ImapClient(ccl.InputParams[2].ToString(), 993, ccl.InputParams[0].ToString(), ccl.InputParams[1].ToString(), true); List <string> mailboxes = imp.GetAllFolders(); foreach (string mb in mailboxes) { parameters.Add(mb); } imp.Logout(); }
private void StartMonitorigThread() { if (string.IsNullOrEmpty(Settings.Default.ImapSrv) || string.IsNullOrEmpty(Settings.Default.ImapUser) || string.IsNullOrEmpty(Settings.Default.ImapPwd)) { _notifyIcon.ShowBalloonTip(1000, "Помилка", "Перевірте налаштування.", ToolTipIcon.Error); } else { try { if (_imapClient != null) { _imapClient.Logout(); _imapClient.Disconnect(); _imapClient.Folders.Inbox.OnNewMessagesArrived -= Inbox_OnNewMessagesArrived; _imapClient.Dispose(); } _imapClient = new ImapClient(Settings.Default.ImapSrv, (int)Settings.Default.SslPort, true); if (_imapClient.Connect()) { if (_imapClient.Login(Settings.Default.ImapUser, Settings.Default.ImapPwd)) { _messageProcessor = new MessageProcessor(_appEntitiesRepo, Settings.Default.FlatNumberRegex, Settings.Default.MeterReadingRegex); _imapClient.Folders.Inbox.OnNewMessagesArrived += Inbox_OnNewMessagesArrived; if (_imapClient.Folders.Inbox.StartIdling()) { _notifyIcon.ShowBalloonTip(1000, string.Empty, "Чекаю на нові листи...", ToolTipIcon.Info); } else { _notifyIcon.ShowBalloonTip(1000, "Помилка", "Неможу почати слухати папку Inbox", ToolTipIcon.Error); } } else { _notifyIcon.ShowBalloonTip(1000, "Помилка", "Перевірте логін та пароль!", ToolTipIcon.Error); } } else { _notifyIcon.ShowBalloonTip(1000, "Помилка", "З'єднання невдале.", ToolTipIcon.Error); } } catch (Exception exception) { _notifyIcon.ShowBalloonTip(1000, "Помилка", exception.Message, ToolTipIcon.Error); } } }
/// <summary> /// Logs out of the mail account. /// </summary> /// <param name="response">The response.</param> /// <returns>The response type.</returns> protected override CommandResponseType LogoutCommand(out string response) { try { CompletionResponse logoutResponse = _client.Logout(); response = logoutResponse.Message; return(GetCommandResponseType(logoutResponse.CompletionResult)); } catch (Exception ex) { response = ex.ToString(); return(CommandResponseType.Bad); } }
public static string GetMessageStatus() { var client = new ImapClient("imap.gmail.com", true); client.Behavior.AutoPopulateFolderMessages = true; if (Connect(client)) { string result = "( " + GetCountNewMessages(client) + " ) / " + GetCountInputMessages(client); client.Logout(); return result; } return "error: unauthorized"; }
public List <EnvoyerMail.MailRecu> RecupererMails() { List <ImapX.Message> liste = new List <ImapX.Message>(); List <EnvoyerMail.MailRecu> liste_test = new List <EnvoyerMail.MailRecu>(); var client = new ImapClient("imap.gmail.com", true); if (client.Connect()) { if (client.Login(user, motDePasse)) { liste = client.Folders.Inbox.Search("ALL", ImapX.Enums.MessageFetchMode.Minimal | ImapX.Enums.MessageFetchMode.Body).ToList(); } } else { liste = null; } client.Logout(); string message = null; foreach (ImapX.Message m in liste) { if (m.Body.HasHtml) { message = m.Body.Html; } else if (m.Body.HasText) { message = m.Body.Text; } else { message = string.Empty; } liste_test.Add(new EnvoyerMail.MailRecu() { Expediteur = m.From.Address, estLu = m.Seen, Message = message, Objet = m.Subject, DateReception = m.Date.Value, Uid = m.UId }); } return(liste_test); }
internal bool Testlogin(string pHost, int pPort, string pUserName, string pPassword, bool pSsl) { ImapClient client = new ImapClient(pHost, pPort, pSsl); try { client.Login(pUserName, pPassword, AuthMethod.Login); client.Logout(); } catch (Exception ex) { throw ex; //return false; } return(true); }
private void tryLogin() { try { if (client != null) { try { client.Logout(); client.Dispose(); } catch { } } client = new ImapClient("outlook.office365.com", 993, true); client.Login("*****@*****.**", main.mailPassword, AuthMethod.Login); } catch { } }
/// <summary> /// check authorization /// </summary> /// <param name="usr">Gmail user name</param> /// <param name="psw">Gmail password</param> /// <returns></returns> public static bool Login(string usr, string psw) { if (string.IsNullOrEmpty(usr)) { throw new ArgumentNullException("usr"); } if (string.IsNullOrWhiteSpace(psw)) { throw new ArgumentNullException("psw"); } using (var client = new ImapClient(IMAPConfig.IMAP_HOST, IMAPConfig.IMAP_PORT, usr, psw, AuthMethod.Login, true, (sender, certificate, chain, errors) => true)) { client.Logout(); } return(true); }
public void getEmailHeaders(string canvasid, int windowid) { ImapClient imp = new ImapClient(ccl.InputParams[2].ToString(), 993, ccl.InputParams[0].ToString(), ccl.InputParams[1].ToString(), true); List<ImapClient.Message> headers = imp.GetAllHeaders(ccl.InputParams[3].ToString()); int count = 0; foreach (ImapClient.Message msg in headers) { List<object> arlmsg = new List<object>(); arlmsg.Add(msg.From); arlmsg.Add(msg.Subject); arlmsg.Add(""); arlmsg.Add(msg.Date.ToString()); arlmsg.Add(""); arlmsg.Add(msg.ID); parameters.Add(arlmsg); count++; } imp.Logout(); }
public override void Close() { if (!Closed) { Closed = true; if (_imapClient != null) { try { _imapClient.Logout(); } catch (Exception ex) { Logger.Error("Failed to logout : " + ex.Message, ex); } } ThreadPool.QueueUserWorkItem(state => NextReader.Close()); } }
public bool MarquerCommeLu(EnvoyerMail.MailRecu m) { bool res = false; var client = new ImapClient("imap.gmail.com", true); if (client.Connect()) { if (client.Login(user, motDePasse)) { ImapX.Message tmp = client.Folders.Inbox.Search(string.Concat("UID ", m.Uid)).First(); tmp.Seen = true; res = true; } } client.Logout(); return(res); }
public void getEmailHeaders(string canvasid, int windowid) { ImapClient imp = new ImapClient(ccl.InputParams[2].ToString(), 993, ccl.InputParams[0].ToString(), ccl.InputParams[1].ToString(), true); List <ImapClient.Message> headers = imp.GetAllHeaders(ccl.InputParams[3].ToString()); int count = 0; foreach (ImapClient.Message msg in headers) { List <object> arlmsg = new List <object>(); arlmsg.Add(msg.From); arlmsg.Add(msg.Subject); arlmsg.Add(""); arlmsg.Add(msg.Date.ToString()); arlmsg.Add(""); arlmsg.Add(msg.ID); parameters.Add(arlmsg); count++; } imp.Logout(); }
static void Main(string[] args) { ImapClient ic = new ImapClient("secure.emailsrvr.com"); //var cliente = new ImapClient("secure.emailsrvr.com",888); if (ic.Connect()) { ic.Login("*****@*****.**", "2DE&D#9UbUvN"); ic.Behavior.FolderTreeBrowseMode = ImapX.Enums.FolderTreeBrowseMode.Lazy; ic.Behavior.MessageFetchMode = ImapX.Enums.MessageFetchMode.Attachments; ImapX.Collections.CommonFolderCollection fol = ic.Folders; //ic.Folders.Inbox.SubFolders[""]; ic.Folders.Add("Demo"); ic.Folders.Add("Demo2"); // ic.Folders["Demo"].Name = "Feliz"; //ic.Folders["Index"].Messages. //ic.Folders["Demo2"].Remove(); Console.WriteLine(""); foreach (Folder f in fol) { Console.WriteLine(" Folder: " + f.Name); Console.WriteLine(" Folder: " + f.Path); Console.WriteLine(" Folder: " + f.HasChildren); } Console.WriteLine(ic.IsConnected); Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("Dentro"); ic.Logout(); } else { Console.WriteLine("NO conectaod"); } Console.Read(); }
//Get folder list private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { UpdateSourceServerSettings(); using (ImapClient client = new ImapClient(sourceServerSettings.Hostname, sourceServerSettings.Port, sourceServerSettings.UseSSL)) { if (client != null) { if (!client.IsConnected) { client.Connect(); } if (client.Login(sourceServerSettings.Username, sourceServerSettings.Password)) { checkedListBox1.Items.Clear(); foreach (Folder topFolder in client.Folders) { AddSubFolders(topFolder); } client.Logout(); client.Disconnect(); } else { MessageBox.Show("Username or password is incorrect, could not login"); } } else { MessageBox.Show("Failed to connect to host, please check hostname, port and SSL option"); } } }
public void DownloadEmailAttachment() { ImapClient imapClient = new ImapClient(host); imapClient.IsDebug = true; if (imapClient.Connect()) { Console.WriteLine("Connect to {0} OK", host); } else { Console.WriteLine("Connect to {0} FAILED", host); Console.ReadKey(); return; } if (imapClient.Login(this.EmailAccount, this.password)) { Console.WriteLine("Login OK"); } else { Console.ReadKey(); return; } Folder testFolder = imapClient.Folders["其他文件夹"].SubFolders["比利时"]; testFolder.Messages.Download("ALL", ImapX.Enums.MessageFetchMode.Full); Console.WriteLine("Messages downloaded! Messages count:{0}", testFolder.Messages.Count()); List<Message> list = new List<Message>(); foreach (var message in testFolder.Messages) { Console.WriteLine("===Message Start==="); Console.WriteLine("Message Title : {0}", message.Subject); Console.WriteLine("Message Header : {0}", string.Join(",", message.Headers.Select(x => x.Key + "->" + x.Value))); Console.WriteLine("Message Body : "); Console.WriteLine(message.Body.Text); Console.WriteLine("Message Attachments"); foreach (var file in message.Attachments) { Console.WriteLine(file.FileName); Console.WriteLine(file.FileSize); Console.WriteLine("--"); file.Save(@"T:\"); } Console.WriteLine("===Message End==="); list.Add(message); } foreach (var message in list) { if (message.MoveTo(imapClient.Folders["其他文件夹"].SubFolders["比利时完成"])) { Console.WriteLine("Message moved OK"); } else { Console.WriteLine("Message moved FAILED"); } } var keyInfo = Console.ReadKey(true); imapClient.Logout(); }
private void Logout() { client.Logout(); client.Disconnect(); Console.WriteLine("Disconnected."); }
/// <summary> /// Metodo que obtiene descarga los archivos adjuntos de /// los correos no leido y los marca como leido de la /// bandeja de entrada de Gmail /// </summary> /// <returns></returns> public void bandejaEntradaGmail() { while (!detenerHilo) { try { //Se obtiene informacion de cuenta de correo ManteUdoCorreos manteUdo = new ManteUdoCorreos(); Correo correo = manteUdo.Consultar(); string clave = correo.Clave, usuario = correo.Cuenta; ImapClient cliente = new ImapClient(); //Se conecta con el servidor if (cliente.Connect(Mensaje.cliGmail, true)) { //Se loguea con el usuario y la clave cliente.Login(usuario, clave); //Se obtiene la carpeta de bandeja de entrada ImapX.Collections.FolderCollection folder = cliente.Folders; ImapX.Folder buzonEntrada = cliente.Folders.Inbox; //Se obtiene los mensajes no leidos ImapX.Message[] mensajes = buzonEntrada.Search("UNSEEN", ImapX.Enums.MessageFetchMode.Full); //Se recorren la lista de mensajes obtenidos foreach (ImapX.Message mensaje in mensajes) { //Se obtienen los archivos adjuntos foreach (var archivo in mensaje.Attachments) { //Se comprueba que sea un archivo xml if (ValidarXmlSobre(archivo.FileName)) { mensaje.Seen = true; //Se descargan los archivos adjuntos archivo.Download(); archivo.Save(RutasCarpetas.RutaCarpetaBandejaEntrada); string desde = mensaje.From.ToString(); //Se guarda en la tabla de sobres Recibidos respuestaSobre.GenerarXML(RutasCarpetas.RutaCarpetaBandejaEntrada, archivo.FileName, desde); } //Se comprueba que sea un ACK else if (ValidarXmlACKSobre(archivo.FileName)) { archivo.Download(); archivo.Save(RutasCarpetas.RutaCarpetaBandejaEntrada); mensaje.Seen = true; //Obtiene datos del sobre de un ACK xml SobreTransito sobreTransito = ObtenerSobreTransito(archivo.FileName, mensaje.From.ToString()); //Guarda los datos en la tabla TFEST(Sobre en transito) ManteUdoSobreTransito manteSobreTransito = new ManteUdoSobreTransito(); manteSobreTransito.Almacenar(sobreTransito); } //else if (ValidarXmlACKCFE(archivo.FileName)) //{ // archivo.Save(RutasCarpetas.RutaCarpetaAcuseRecibidoCertificado); // mensaje.Seen = true; // RespuestaCertificados respuestaCFE = new RespuestaCertificados(); // respuestaCFE.ProcesarRespuesta(archivo.FileName, CFE.ESTipoReceptor.Receptor); //} //else //{ // archivo.Save(RutasCarpetas.RutaCarpetaConsultaEstado); // mensaje.Seen = true; // RespuestaConsultaCFE respuestaConsultaCfe = new RespuestaConsultaCFE(); // SobreTransito sobreTransito = respuestaConsultaCfe.ValidarContenidoConsulta(archivo.FileName); // if (sobreTransito != null) // { // respuestaConsultaCfe.ObtenerEstadoCFE(sobreTransito.Token, sobreTransito.IdReceptor, mensaje.From.ToString(), archivo.FileName); // } //} } } //Se cierra sesion cliente.Logout(); //Se desconecta del servidor cliente.Disconnect(); //Se libera el objeto cliente.Dispose(); } } catch (Exception) { //SAPbouiCOM.Framework.Application.SBO_Application.MessageBox("Mail/BandejaEntradaGmail/Error: " + ex.ToString()); } finally { Thread.Sleep(30000); } } }
public List <MailMessage> GetAllMessages(IReadOnlyCollection <string> toAddressFilters) { if (toAddressFilters == null) { throw new ArgumentNullException(nameof(toAddressFilters)); } ImapClient imapClient = null; try { imapClient = new ImapClient(Hostname, Port, UseSSL); EventLog.WriteTrace($"ImapEmailReceiver : Fetching emails from IMAP server for User Id : {UserId}, Port : {Port}, Server : {Hostname}."); var authMethod = UseIntegratedAuthentication ? AuthMethod.Login : AuthMethod.Auto; try { imapClient.Login(UserId, Password, authMethod); } catch (InvalidCredentialsException ex) { throw new Exception($"ImapEmailReceiver: Failed to connect to the IMAP server rejected the supplied credentials. User Id : {UserId}, Server : {Hostname}, Message : {ex.ToString()}"); } catch (Exception ex) { throw new Exception($"ImapEmailReceiver: An error occurred connecting to IMAP Server. User Id : {UserId}, Server : {Hostname}, Message : {ex.ToString()}"); } /* * This implementation of the email fetching is far from ideal however this is the only implementation that works reliably since the * SearchCondition.To() option does not appear to work reliably. Hence we need to fetch and examin each email indivdually to determine * if we are interested in it. */ var yesterday = DateTime.Now.AddDays(-1); var uids = imapClient.Search(SearchCondition.SentSince(yesterday).And(SearchCondition.Smaller(MaxEmailSize)), Folder); // SearchCondition.SentSince has resolution of days (not hours, minutes or seconds) var matchedUids = new List <uint>(); foreach (var uid in uids.Distinct()) { // fetch just the headers and check the To address var message = imapClient.GetMessage(uid, FetchOptions.HeadersOnly); if (!ContainsAddress(message.To, toAddressFilters)) { continue; } matchedUids.Add(uid); } if (matchedUids.Count == 0) { return(new List <MailMessage>()); } // now fetch the full email for those that we have matched. var messages = imapClient.GetMessages(matchedUids, FetchOptions.Normal).ToList(); #if !DEBUG // delete these emails imapClient.DeleteMessages(matchedUids); imapClient.Expunge(Folder); #endif EventLog.WriteTrace($"ImapEmailReceiver : Fetched {messages.Count} emails from IMAP server."); return(messages); } finally { imapClient.Logout(); imapClient.Dispose(); } }