protected void Recieve_Email_Click_Pop_IMAP(object sender, EventArgs e) { try { // for Gmail IEmailClient imapClient = EmailClientFactory.GetClient(EmailClientEnum.POP3); imapClient.Connect("imap.gmail.com", "*****@*****.**", "test.stanev2801", 993, true); imapClient.SetCurrentFolder("INBOX"); // I assume that 5 is the last "ID" readed by my client. // If I want to read all messages i use "ImapClient.LoadMessages();" // to take min of UI count and messages.Count int cMail = int.Parse(CountMail.Text); // int msgCount = imapClient.Messages.Count; // int minCount = Math.Min(cMail, msgCount); imapClient.LoadRecentMessages(cMail); DataTable dt = InitializeDataTable(); // To read all my messages loaded: int count = 0; //for (int i = 0; i < ImapClient.Messages.Count; i++) for (int i = 0; i < cMail; i++) { IEmail msm = (IEmail)imapClient.Messages[i]; // Load all infos include attachments msm.LoadInfos(); count++; dt.Rows.Add(new object[] { count, msm.Date.ToString(), msm.From[0], msm.Subject, "", msm.TextBody }); //Console.WriteLine(msm.Date.ToString() + " - " + msm.From[0] + " - " + // msm.Subject + " - " + msm.TextBody + msm.Attachments.Count); } dataGrid.DataSource = dt; dataGrid.DataBind(); } catch (Exception ex) { ScriptManager.RegisterClientScriptBlock( this, typeof(Page), "TScript", "alert('There is an error when reading email!')", true); } }
//загрузка писем в listbox private void button4_Click(object sender, EventArgs e) { Msms.Clear(); listBox1.Items.Clear(); ImapClient.SetCurrentFolder("INBOX"); ImapClient.LoadMessages(); { for (int i = 0; i < ImapClient.Messages.Count; i++) { if (i == numericUpDown1.Value) { break; } IEmail msm = (IEmail)ImapClient.Messages[i]; msm.LoadInfos(); Msms.Add(msm); } } foreach (var msm in Msms) { if (msm.Subject.Length > 55 && msm.From[0].Length > 20) { listBox1.Items.Add(msm.From[0].Substring(0, 20) + "\t" + msm.Subject.Substring(0, 55)); } else { if (msm.From[0].Length > 20) { listBox1.Items.Add(msm.From[0].Substring(0, 20) + "\t" + msm.Subject); } else { listBox1.Items.Add(msm.From[0] + "\t" + msm.Subject); } } } }
public bool Initialize(FeuerwehrCloud.Plugin.IHost hostApplication) { if (!System.IO.File.Exists("imap.cfg")) { IMAPConfig.Add("user", ""); IMAPConfig.Add("password", ""); IMAPConfig.Add("server", ""); IMAPConfig.Add("trash", ""); FeuerwehrCloud.Helper.AppSettings.Save(IMAPConfig, "imap.cfg"); } IMAPConfig = FeuerwehrCloud.Helper.AppSettings.Load("imap.cfg"); watcher = new FileSystemWatcher(); watcher.Path = System.Environment.CurrentDirectory; watcher.IncludeSubdirectories = false; watcher.Filter = "imap.cfg"; watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.LastAccess | NotifyFilters.DirectoryName | NotifyFilters.FileName; watcher.Changed += new FileSystemEventHandler((object sender, FileSystemEventArgs e) => IMAPConfig = FeuerwehrCloud.Helper.AppSettings.Load("imap.cfg")); watcher.EnableRaisingEvents = true; new System.Threading.Thread(() => { while (true) { try { IEmailClient ImapClient = EmailClientFactory.GetClient(EmailClientEnum.IMAP); ImapClient.Connect(IMAPConfig["server"], IMAPConfig["user"], IMAPConfig["password"], 143, false); ImapClient.SetCurrentFolder("INBOX"); ImapClient.LoadMessages(); if (!ImapClient.IsConnected) { ImapClient.Connect(IMAPConfig["server"], IMAPConfig["user"], IMAPConfig["password"], 143, false); ImapClient.SetCurrentFolder("INBOX"); } ImapClient.SetCurrentFolder("INBOX"); ImapClient.LoadMessages(); System.Diagnostics.Debug.WriteLine("MSG: " + ImapClient.Messages.Count.ToString()); for (int i = 0; i < ImapClient.Messages.Count; i++) { IEmail msm = (IEmail)ImapClient.Messages[i]; // Load all infos include attachments msm.LoadInfos(); #if _ASTERISK_ if (msm.Subject.StartsWith("Facsimile received from")) { FeuerwehrCloud.Helper.Logger.WriteLine("| < [IMAP4] *** FAX-Mail found!"); try { msm.SetDeleted(""); } catch (Exception ex2) { if (ex2.Message.Contains("Mailbox doesn't exist: INBOX.Trash")) { } } System.IO.File.WriteAllBytes("/var/spool/hylafax/recvq/" + msm.Attachments[0].Text, msm.Attachments[0].Body); //gs -dNOPAUSE -q -g300x300 -sDEVICE=tiffg4 -dBATCH -sOutputFile=output_file_name.tif input_file_name.pdf string FName = msm.Attachments[0].Text.Replace(".pdf", ".tif"); FeuerwehrCloud.Helper.Helper.exec("/usr/bin/gs", " -dNOPAUSE -q -sDEVICE=tiffg4 -dBATCH -sOutputFile=/var/spool/hylafax/recvq/" + FName + " " + "/var/spool/hylafax/recvq/" + msm.Attachments[0].Text); System.Net.Sockets.TcpClient PP = new System.Net.Sockets.TcpClient(); PP.Connect("localhost", 10112); string Telefonnummer = "08031900900"; //msm.TextBody.Substring(msm.TextBody.IndexOf("Rufnummer : ")); //Telefonnummer = Telefonnummer.Substring(Telefonnummer.IndexOf(":")+2); //Telefonnummer = Telefonnummer.Substring(0,Telefonnummer.IndexOf("\r\n")); string Fax = Telefonnummer + "|recvq/" + FName + "\r\n"; PP.GetStream().Write(System.Text.Encoding.Default.GetBytes(Fax), 0, Fax.Length); PP.Close(); } #else if (msm.Subject == "Neue Faxnachricht") { FeuerwehrCloud.Helper.Logger.WriteLine("| < [IMAP4] *** FAX-Mail found!"); try { msm.SetDeleted(IMAPConfig["trash"]); } catch (Exception ex2) { if (ex2.Message.Contains("Mailbox doesn't exist: INBOX.Trash")) { //ImapClient.m } } System.IO.File.WriteAllBytes("/var/spool/hylafax/recvq/" + msm.Attachments[0].Text, msm.Attachments[0].Body); System.Net.Sockets.TcpClient PP = new System.Net.Sockets.TcpClient(); PP.Connect("localhost", 10112); string Telefonnummer = msm.TextBody.Substring(msm.TextBody.IndexOf("Rufnummer : ")); Telefonnummer = Telefonnummer.Substring(Telefonnummer.IndexOf(":") + 2); Telefonnummer = Telefonnummer.Substring(0, Telefonnummer.IndexOf("\r\n")); string Fax = Telefonnummer + "|recvq/" + msm.Attachments[0].Text + "\r\n"; PP.GetStream().Write(System.Text.Encoding.Default.GetBytes(Fax), 0, Fax.Length); PP.Close(); //System.Threading.Thread.Sleep(10000); } #endif } try { ImapClient.Disconnect(); } catch (Exception ex) { } System.Threading.Thread.Sleep(1000 * 20); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(">>" + ex.Message); } System.Threading.Thread.Sleep(1000 * 20); } }).Start(); FeuerwehrCloud.Helper.Logger.WriteLine("| *** IMAP4 loaded for address: " + IMAPConfig["user"]); return(true); }
static void Main(string[] args) { IEmailClient ImapClient = EmailClientFactory.GetClient(EmailClientEnum.IMAP); ImapClient.Connect("imap.gmail.com", "*****@*****.**", "abeo1234", 993, true); ImapClient.SetCurrentFolder("INBOX"); // I assume that 5 is the last "ID" readed by my client. // If I want to read all messages i use "ImapClient.LoadMessages();" //ImapClient.LoadRecentMessages(5); ImapClient.LoadMessages(); // To read all my messages loaded: for (int i = 0; i < ImapClient.Messages.Count; i++) { IEmail msm = (IEmail)ImapClient.Messages[i]; // Load all infos include attachments msm.LoadInfos(); Console.WriteLine(msm.Date.ToString() + " - " + msm.From[0] + " - " + msm.Subject + " - " + msm.Attachments.Count); } // try // { // path = Environment.CurrentDirectory + "\\emailresponse.txt"; // if (System.IO.File.Exists(path)) // System.IO.File.Delete(path); // sw = new System.IO.StreamWriter(System.IO.File.Create(path)); // // there should be no gap between the imap command and the \r\n // // ssl.read() -- while ssl.readbyte!= eof does not work because there is no eof from server // // cannot check for \r\n because in case of larger response from server ex:read email message // // there are lot of lines so \r \n appears at the end of each line // //ssl.timeout sets the underlying tcp connections timeout if the read or write // //time out exceeds then the undelying connection is closed // tcpc = new System.Net.Sockets.TcpClient("imap.gmail.com", 993); // ssl = new System.Net.Security.SslStream(tcpc.GetStream()); // ssl.AuthenticateAsClient("imap.gmail.com"); // receiveResponse(""); // Console.WriteLine("username : "******"password : "******"$ LOGIN " + username + " " + password + " \r\n"); // Console.Clear(); // receiveResponse("$ LIST " + "\"\"" + " \"*\"" + "\r\n"); // receiveResponse("$ SELECT INBOX\r\n"); // receiveResponse("$ STATUS INBOX (MESSAGES)\r\n"); // Console.WriteLine("enter the email number to fetch :"); // int number = int.Parse(Console.ReadLine()); // receiveResponse("$ FETCH " + number + " body[header]\r\n"); // receiveResponse("$ FETCH " + number + " body[text]\r\n"); // receiveResponse("$ LOGOUT\r\n"); // } // catch (Exception ex) // { // Console.WriteLine("error: " + ex.Message); // } // finally // { // if (sw != null) // { // sw.Close(); // sw.Dispose(); // } // if (ssl != null) // { // ssl.Close(); // ssl.Dispose(); // } // if (tcpc != null) // { // tcpc.Close(); // } // } // Console.ReadKey(); //} //static void receiveResponse(string command) //{ // try // { // if (command != "") // { // if (tcpc.Connected) // { // dummy = Encoding.ASCII.GetBytes(command); // ssl.Write(dummy, 0, dummy.Length); // } // else // { // throw new ApplicationException("TCP CONNECTION DISCONNECTED"); // } // } // ssl.Flush(); // buffer = new byte[2048]; // bytes = ssl.Read(buffer, 0, 2048); // sb.Append(Encoding.ASCII.GetString(buffer)); // Console.WriteLine(sb.ToString()); // sw.WriteLine(sb.ToString()); // sb = new StringBuilder(); // } // catch (Exception ex) // { // throw new ApplicationException(ex.Message); // } }
static void Main(string[] args) { string sFuncName = string.Empty; clsLog oLog = new clsLog(); Logic oLogic = new Logic(); string sErrDesc = string.Empty; try { sFuncName = "Main Program"; oLog.WriteToDebugLogFile("Starting Program", sFuncName); string sTicketNumber = string.Empty; string sBodyContent = string.Empty; string sServer = ConfigurationManager.AppSettings["Server"]; int iPort = Convert.ToInt32(ConfigurationManager.AppSettings["Port"]); string sFromEmail = ConfigurationManager.AppSettings["FromEmail"]; string sFromPassword = ConfigurationManager.AppSettings["FromPassword"]; IEmailClient ImapClient = EmailClientFactory.GetClient(EmailClientEnum.IMAP); ImapClient.Connect(sServer, sFromEmail, sFromPassword, iPort, true); ImapClient.SetCurrentFolder("INBOX"); ImapClient.LoadMessages(); string sLastEmailId = oLogic.GetMailNumber(); if (sLastEmailId != "NO RECORDS") { int iMailId = Convert.ToInt32(sLastEmailId); for (int i = 440; i <= ImapClient.Messages.Count - 1; i++) { string sCC = string.Empty; oLog.WriteToDebugLogFile("Count of i : " + i, sFuncName); IEmail msm = (IEmail)ImapClient.Messages[i]; if (!msm.Subject.Contains("Delivery Status Notification")) { if (msm.SequenceNumber > iMailId) { msm.LoadInfos(); foreach (var item in msm.Cc) { if (sCC.Length == 0) { sCC = item.ToString(); } else { sCC = sCC + "," + item.ToString(); } } // Check the subject contains ticket ID or nor if (msm.Subject.Contains("[##")) { sTicketNumber = oLogic.Between(msm.Subject, "[##", "##]"); sBodyContent = msm.TextBody.ToString().Replace("\r\n", "<br/>"); //call create thread string sResult = oLogic.InsertTicketThread(sTicketNumber, sBodyContent, msm.SequenceNumber, sCC); oLog.WriteToDebugLogFile("For Ticket Number : " + sTicketNumber + " the Result is " + sResult, sFuncName); } else { string sEmail = msm.From[0]; string sUserName = oLogic.Before(sEmail, "@"); string sBodyContent1 = msm.TextBody.ToString().Replace("\r\n", "<br/>"); string sResult = oLogic.InsertTicketandUser(sUserName, sEmail, msm.Subject, sBodyContent1, msm.SequenceNumber, sCC); string[] sArray = sResult.Split('*'); if (sArray[0] == "SUCCESS") { // Send auto reply email to the person who raised the ticket oLog.WriteToDebugLogFile("Before sending email to Email id : " + sEmail + "and username : "******"[##" + sArray[1].ToString() + "##]", sBodyContent1, ref sErrDesc); oLog.WriteToDebugLogFile("AFter sending email to Email id : " + sEmail + "and username : "******"For Email id : " + sEmail + "and username : "******" : the Result is " + sResult, sFuncName); } } } } oLog.WriteToDebugLogFile("Ending Program", sFuncName); } else { oLog.WriteToDebugLogFile(sLastEmailId, sFuncName); } } catch (Exception Ex) { sErrDesc = Ex.Message.ToString(); oLog.WriteToErrorLogFile(sErrDesc, sFuncName); oLog.WriteToDebugLogFile("Completed With ERROR ", sFuncName); } }