public Message[] Receive(ConnectionObject con) { HostConfigObject pop3config = SettingsObject.ListPOP3[con.Pop3ID]; POPClient popClient = new POPClient(); // Set timeouts to 5 seconds popClient.ReceiveTimeOut = 5000; popClient.SendTimeOut = 5000; bool connected = false; // Port is set to automatic, try SSL first, then STANDARD if (pop3config.Port == 0) { Console.WriteLine("Automatic port is activated for POP3 host."); Console.WriteLine("Trying to connect with SSL."); connected = Connect(popClient,pop3config.Host, SSL); if (!connected) { Console.WriteLine("Connection denied."); Console.WriteLine("Trying to connect at standard port [" + STANDARD + "]."); connected = Connect(popClient, pop3config.Host, STANDARD); if (!connected) { Console.WriteLine("Connection denied."); } else { Console.WriteLine("Connection granted."); } } else { Console.WriteLine("Connection granted."); } } else { Console.WriteLine("Currently activated port: " + pop3config.Port); Console.WriteLine("Trying to connect at this port."); connected = Connect(popClient,pop3config.Host, pop3config.Port); if (!connected) { Console.WriteLine("Connection denied."); } else { Console.WriteLine("Connection granted."); } } bool errorOccured = false; // Contacting the server and login Message[] msgArray = null; if (connected){ try { Console.WriteLine("Starting authentication."); AuthenticationMethod auth = AuthenticationMethod.TRYBOTH; popClient.Authenticate(pop3config.Username, pop3config.Password, auth); Logger.sendMessage("Login successful.", Logger.MessageTag.INFO); Console.WriteLine("login successful."); int msgCount = popClient.GetMessageCount(); Logger.sendMessage("Account statistics loaded. [" + msgCount + "] messages on server.", Logger.MessageTag.INFO); Console.WriteLine("Account statistics loaded. [" + msgCount + "] messages on server."); List<Message> msgs = new List<Message>(); //System.Windows.Forms.MessageBox.Show("Fetching first 3 messages only (Bugfixing)"); // Mailbox entries always start with "1" for (int i = 1; i <= 3; i++) // msgCount { if (running) { // Receive UID of mail string uid = popClient.GetMessageUID(i); List<string> cache = SettingsObject.CacheUIDs[con.ConnectionID]; if (cache == null) { cache = new List<string>(); } // Receive complete email Message msgObj = popClient.GetMessage(i, false); if (msgObj != null) { msgs.Add(msgObj); } // Add UID to list of cached mail UIDs SettingsObject.CacheUIDs.Add(con.ConnectionID, cache); } } msgArray = (Message[])msgs.ToArray(); } catch (Exception) { errorOccured = true; Logger.sendMessage("Problem while receiving message/s.", Logger.MessageTag.ERROR); } finally { popClient.Disconnect(); } } if (!errorOccured) { Logger.sendMessage("Received " + (msgArray != null ? msgArray.Length.ToString() : "no") + " mails from " + pop3config.Description + ".", Logger.MessageTag.INFO); } return msgArray; }
public void ReceiveProcessMails() { //inserts.Clear(); mails.Clear(); Message m = null; byte[] bytes; String uid = ""; DateTime dt = DateTime.Now; string sdt = ""; DatabaseMailRecord mail; POPClient popClient = new POPClient(); listReport = new List<IridiumExtremeBinaryReport>(); try { log.writeToLogFile(LogType.LOG_NOTICE, "ReceiveProcessMails", "Log Iniciado"); //string TableName = config.getConfigValue("databasesection", "tablename", "tablename"); int hours = config.getConfigValue("messagesection", "purgetimehours", 30); log.writeToLogFile("purgetimehours {0}", hours); string s = config.getConfigValue("popsection", "PopServer", ""); int ins = config.getConfigValue("popsection", "PopPort", 80); popClient.Connect(s, ins); log.writeToLogFile("Conectado a {0}:{1}", s, ins); s = config.getConfigValue("popsection", "PopUsername", ""); popClient.Authenticate(s, config.getConfigValue("popsection", "PopPassword", "")); log.writeToLogFile("Autenticado {0}", s); int Count = popClient.GetMessageCount(); log.writeToLogFile(LogType.LOG_NOTICE, "ReceiveProcessMails", "Hay {0} mensajes", Count); IridiumExtremeBinaryReport.NumsWithComma = config.getConfigValue("messagesection", "numswithcomma", true); for (int i = Count; i >= 1; i -= 1) { try { uid = popClient.GetMessageUID(i); m = popClient.GetMessage(i, true); try { dt = DateTime.Parse(m.Date); sdt = dt.Ticks.ToString(); } catch (Exception) { sdt = "0"; } if (md.isMail(uid, sdt)) { if (dt.AddHours(hours) < DateTime.Now) { string strLog = string.Format("Mail muy antiguo {0}, fecha: '{1}', id {2}", i, dt.ToString("yyyy/MM/dd HH:mm:ss"), uid); try { //popClient.DeleteMessage(i); log.writeToLogFile(LogType.LOG_NOTICE, "ReceiveProcessMails", "{0}, fue borrado exitosamente", strLog); } catch (Exception ex) { log.writeToLogFile(LogType.LOG_ERR, "ReceiveProcessMails", "{0}, hubo un error al intentar borrarlo: {1}", strLog, ex.Message); } } continue; } else { md.addValue(uid, sdt); if (m != null) { if (m.HasAttachment) { m = popClient.GetMessage(i, false); if (m.Attachments.Count > 0) { foreach (OpenPOP.MIMEParser.Attachment a in m.Attachments) { string attachName = m.GetAttachmentFileName(a); string extension = Path.GetExtension(attachName); if (extension.Equals(config.getValue("AttachmentType"))) { mail = new DatabaseMailRecord(); mail.Uid = uid; string imei = "desconocido"; imei = getIdFromSubject(m.Subject); //try //{ // mail.Data = a.DecodeAsText(); //} // catch (Exception) //{ // bytes = a.DecodedAsBytes(); // mail.Data = HexAscii.ConvertToHexAscii(bytes); // log.writeToLogFile(LogType.LOG_NOTICE, "ReceiveProcessMails", "El archivo no es string, procesando como binario"); //} try { bytes = a.DecodedAsBytes(); saveToDisck(bytes, attachName, @"\MESSAGES_INBOX"); mail.Data = HexAscii.ConvertToHexAscii(bytes); log.writeToLogFile(LogType.LOG_NOTICE, "ReceiveProcessMails", "El archivo no es string, procesando como binario"); } catch (Exception) { } mail.DataTime = dt; mails.Add(mail); string strlog = string.Format("Mail {0}, fecha: '{1}', id {2}", i, dt.ToString("yyyy/MM/dd HH:mm:ss"), uid); strlog = string.Format("{0}, subject: {1}, atachment: {2}", strlog, m.Subject, attachName); strlog = string.Format("{0}, contenido: '{1}', de {2}", strlog, mail.Data.Replace('\r', ' '), m.From); log.writeToLogFile(LogType.LOG_NOTICE, "ReceiveProcessMails", strlog); IridiumExtremeBinaryReport report = new IridiumExtremeBinaryReport(); string type = "MO"; if (IridiumExtremeBinaryReport.TryParse(HexAscii.ConvertToBytes(mail.Data), imei, out report, type)) { if (report.inbox) { string TableName = config.getConfigValue("databasesection", "tableinbox", "tablename"); inserts.Add(report.ToInsertSQL(true, TableName)); } if (report.posiciones) { string TableName = config.getConfigValue("databasesection", "tableposition", "tablename"); inserts.Add(report.ToInsertSQL(true, TableName)); } //listReport.Add(report); } } else { if (extension.Equals(".htm")) { if (m.Subject.Contains("SBD Mobile Terminated Message Queued for Unit:")) { //string data = mail.Data.Replace('\r', ' '); string filename = getBetween(m.RawMessage, "Filename: ", "\r"); string imei = getBetween(m.RawMessage, "IMEI: ", "\r"); DateTime time = DateTime.Parse(m.Date); string gatewayStatus = ""; if (m.RawMessage.Contains("The following mobile-terminated message was queued for delivery")) { gatewayStatus = "The mobile-terminated message was queued for delivery"; } try { OdbcCommand comm; string sql = ""; List<string> updates = new List<string>(); if (ConnectToDatabase(out comm)) { string TableName = config.getValue("tablesent"); sql = string.Format("update {0} set GATEWAY_DATETIME = '{1}' where ATTACHMENT_FILENAME = '{2}' and EQP_ESN = '{3}'", TableName, time.ToString("yyyy/MM/dd HH:mm:ss"), filename, imei); //updates.Add(sql); inserts.Add(sql); sql = string.Format("update {0} set GATEWAY_STATUS = '{1}' where ATTACHMENT_FILENAME = '{2}' and EQP_ESN = '{3}'", TableName, gatewayStatus, filename, imei); //updates.Add(sql); inserts.Add(sql); //foreach (string query in updates) //{ // comm.CommandText = query; // comm.ExecuteNonQuery(); //} } } catch (Exception ex) { } } } } } } } else { log.writeToLogFile(LogType.LOG_ERR, "ReceiveProcessMails", "El mail {0} esta corrupto o es erroneo", i); } } } } catch (Exception ex) { if (m != null) log.writeToLogFile(LogType.LOG_ERR, "ReceiveProcessMails", "Hubo un en un mail {0}, {1}, error: {2}", m.From, m.Date, ex.Message); else log.writeToLogFile(LogType.LOG_ERR, "ReceiveProcessMails", "Hubo un en un mail {0}, error: {1}", uid, ex.Message); } } } catch (Exception ex) { log.writeToLogFile(LogType.LOG_ERR, "ReceiveProcessMails", "Hubo un error: {0} ", ex.Message); } finally { popClient.Disconnect(); log.writeToLogFile(LogType.LOG_NOTICE, "ReceiveProcessMails", "Desconectado"); log.Flush(); } }