private void startReceive() { QuerysDb querysDb = new QuerysDb(); var emails = querysDb.SelectEmails(); for (int key = 0; key < emails.Rows.Count; key++) { if (!backList.Contains(emails.Rows[key][1].ToString())) { if (!string.IsNullOrWhiteSpace(emails.Rows[key][1].ToString())) { mail_grid.Rows.Add(false, emails.Rows[key][3].ToString(), emails.Rows[key][4].ToString(), emails.Rows[key][5].ToString(), emails.Rows[key][6].ToString()); backList.Add(emails.Rows[key][1].ToString()); } } } Thread thread = new Thread(() => { try { var client = new Pop3Client(); client.Connect("pop.mail.yahoo.com", 995, true); client.Authenticate(Toemail, Topass); var count = client.GetMessageCount(); OpenPop.Mime.Message message = client.GetMessage(count); // var mailbody = ASCIIEncoding.ASCII.GetString(message.RawMessage); StringBuilder builder = new StringBuilder(); OpenPop.Mime.MessagePart plainText = message.FindFirstPlainTextVersion(); if (plainText != null) { CreateDb.ExecuteSqlCommand($"INSERT INTO box_mail (dateId, mail_from, subject, body, tipo) VALUES('{message.Headers.Date.Trim()}','{message.Headers.From}','{message.Headers.Subject.Trim()}','{plainText.GetBodyAsText()}', 'text')"); } else { // Might include a part holding html instead OpenPop.Mime.MessagePart html = message.FindFirstHtmlVersion(); if (html != null) { CreateDb.ExecuteSqlCommand($"INSERT INTO box_mail (dateId, mail_from, subject, body, tipo) VALUES('{message.Headers.Date.Trim()}','{message.Headers.From}','{message.Headers.Subject.Trim()}','{html.GetBodyAsText()}', 'html')"); } } } catch (Exception ex) { MessageBox.Show(ex.Message); // corpo_email.AppendText(ex.Message + "\r\n"); } }) { IsBackground = true }; thread.Start(); }
//Used to click verification links in hotmail //Params: email - The email to search in // password - Email password // linkPattern - Regex used to find the link we need to click public string verifyHotmail(string email, string password, string linkPattern, string subject) { // The client disconnects from the server when being disposed string link = ""; using (Pop3Client client = new Pop3Client()) { // Connect to the server client.Connect("pop3.live.com", 995, true); // Authenticate ourselves towards the server client.Authenticate(email, password); // Get the number of messages in the inbox int messageCount = client.GetMessageCount(); // We want to check the headers of the message before we download // the full message OpenPop.Mime.Message message = null; //stores the message with the link in it for (int i = 1; i <= messageCount; ++i) { MessageHeader headers = client.GetMessageHeaders(i); if (headers.Subject.ToString().Contains(subject)) { message = client.GetMessage(i); break; } } //grab the link out of the email //fiverr: @"(https?):((//)|(\\\\))+fiverr\.com/+[\w\d:#@%/;$()~_?\+-=\\\.&]*" if (System.Text.RegularExpressions.Regex.IsMatch(message.FindFirstHtmlVersion().GetBodyAsText(), linkPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase)) { System.Text.RegularExpressions.Match match = System.Text.RegularExpressions.Regex.Match(message.FindFirstHtmlVersion().GetBodyAsText(), linkPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase); link = match.Value.ToString(); } } return(link); }
protected void PrepararCorreo() { try { using (CobranzasDataContext db = new CobranzasDataContext()) { idOperador.Value = Request["idOperador"];//Sesion.idOperador.ToString(); int id = Convert.ToInt32(Request["idCorreo"]); int Tipo = Convert.ToInt32(Request["Tipo"]); idCorreo.Value = id.ToString(); Entidades.Correos Correo = db.Correos.Single(x => x.idCorreo == id); try { List <Entidades.Correos> CorreoAnterior; List <Entidades.Correos> CorreoSiguiente; if (Tipo == 1) { CorreoSiguiente = db.Correos.Where(x => x.idOperador == Correo.idOperador && x.FechaCreacion < Correo.FechaCreacion && x.TipoEspecial == null && !x.Correos_Personas.Any() && x.RutaEml != null).OrderByDescending(x => x.FechaCreacion).Take(1).ToList(); CorreoAnterior = db.Correos.Where(x => x.idOperador == Correo.idOperador && x.FechaCreacion > Correo.FechaCreacion && x.TipoEspecial == null && !x.Correos_Personas.Any() && x.RutaEml != null).OrderBy(x => x.FechaCreacion).Take(1).ToList(); } else if (Tipo == 2) { CorreoSiguiente = db.Correos.Where(x => x.idOperador == Correo.idOperador && x.FechaCreacion < Correo.FechaCreacion && x.Correos_Personas.Any() && x.RutaEml != null && !x.Leido).OrderByDescending(x => x.FechaCreacion).Take(1).ToList(); CorreoAnterior = db.Correos.Where(x => x.idOperador == Correo.idOperador && x.FechaCreacion > Correo.FechaCreacion && x.Correos_Personas.Any() && x.RutaEml != null && !x.Leido).OrderBy(x => x.FechaCreacion).Take(1).ToList(); } else { CorreoSiguiente = new List <Entidades.Correos>(); CorreoAnterior = new List <Entidades.Correos>(); } if (CorreoSiguiente.Count == 0) { lnkSiguiente.Visible = false; } else { lnkSiguiente.HRef = "ctrlCorreo.aspx?idCorreo=" + CorreoSiguiente.First().idCorreo + "&idOperador=" + idOperador.Value + "&Tipo=" + Tipo; } if (CorreoAnterior.Count == 0) { lnkAnterior.Visible = false; } else { lnkAnterior.HRef = "ctrlCorreo.aspx?idCorreo=" + CorreoAnterior.First().idCorreo + "&idOperador=" + idOperador.Value + "&Tipo=" + Tipo; } } catch { } Correo.Leido = true; db.SubmitChanges(); lblAsunto.Text = Correo.Asunto; lblDestinatarios.Text = Server.HtmlEncode(Correo.Destinatarios); lblDestinatariosCopia.Text = Server.HtmlEncode(Correo.DestinatariosCopia); lblDestinatariosCopiaOculta.Text = Server.HtmlEncode(Correo.DestinatariosCopiaOculta); lblFecha.Text = Correo.FechaCreacion.ToString("dd/MM/yyyy HH:mm:ss tt"); String Mensaje = ""; //Boolean isHTML = true; if (Correo.Mensaje != null) { Mensaje = Correo.Mensaje; } if (Correo.RutaEml != null) { List <String> NoAdjuntos = new List <string>(); String Ruta = db.Parametros.Single(x => x.Clave == "RutaCorreos").Valor; OpenPop.Mime.Message m = OpenPop.Mime.Message.Load(new System.IO.FileInfo(Ruta + Correo.RutaEml + ".eml")); OpenPop.Mime.MessagePart Parte = m.FindFirstHtmlVersion(); if (Parte == null) { Parte = m.FindFirstPlainTextVersion(); } Mensaje = Parte.GetBodyAsText(); //isHTML = !m.MessagePart.IsText; if (Parte.ContentType.MediaType.ToLower() == "text/plain") { Mensaje = "<pre>" + Mensaje + "</pre>"; } try { foreach (Match Match in Regex.Matches(Mensaje, "\"(cid:(\\S+))\"")) { //Debug.Print(Match.ToString()); String ID = Match.Groups[2].Value; NoAdjuntos.Add(ID); try { OpenPop.Mime.MessagePart Parte2 = BuscarParte(ID, m.MessagePart); String Ext = Parte2.FileName; try { Ext = Ext.Substring(Ext.LastIndexOf(".")); } catch { Ext = ""; } String Ruta2 = Guardar(Parte2, id.ToString()); //Parte2.Save(new FileInfo(MapPath(Ruta2))); Mensaje = Mensaje.Replace(Match.Groups[0].Value, "\"" + Ruta2 + "\""); } catch { } } foreach (OpenPop.Mime.MessagePart Adjunto in m.FindAllAttachments()) { if (NoAdjuntos.Contains(Adjunto.ContentId)) { continue; } String Ruta2 = Guardar(Adjunto, id.ToString()); lblAdjuntos.Text += String.Format(@"</span><a href=""{0}"" title=""{2}"" target=""_blank"" class=""AdjuntoSL"">{1}</a><span>", Ruta2, Adjunto.ContentDisposition.FileName ?? "Adjunto", Adjunto.ContentDescription); } } catch { } } //lblAdjuntos.Text=@"</span><a href=""http://www.google.com"" target=""_blank"" class=""Adjunto"">aquí</a><span>"; lblRemitente.Text = Correo.Remitente; try { String RutaCorreo = (@"/Temp/Correo" + id.ToString() + (true ? ".html" : ".txt")); iframe.Attributes["src"] = RutaCorreo; File.WriteAllText(MapPath(RutaCorreo), Mensaje, System.Text.Encoding.UTF8); } catch { } } } catch (Exception Ex) { Ex.Registrar(); } }
public static void FetchAllMessages(object sender, DoWorkEventArgs e) { // Add messages from pop3 server to message database try { // Makes a new POP3 session // POP3 does not allow to check for new mails // * facepalm * popClient.Disconnect(); popClient.Connect(currentUser.pop_hostname, currentUser.pop_port, currentUser.pop_ssl); popClient.Authenticate(currentUser.mailaddress, currentUser.password); } catch (SystemException err) { MessageBox.Show("Kunne ikke genoprette en forbindelse" + Environment.NewLine + err.Message); } // gets messagecount int messageCount = popClient.GetMessageCount(); // progress of process int progress = 0; // the progress value when it was sent to the progressbar int lastProgress = 0; for (int i = messageCount; i > 0; i--) { OpenPop.Mime.Message msg = popClient.GetMessage(i); // We don't like the fact about messageId is optional, // so we make our own messageID by a md5 of // - the sender's email // - the tick value (ticks since 1. January year 1) // - md5 of messageID (if it doesnt present then = md5 of "") // - subject of the mail string id = genMd5(string.Format("{0}_{1}_{2}_{3}", msg.Headers.From.MailAddress.Address, msg.Headers.DateSent.Ticks.ToString(), genMd5(msg.Headers.MessageId), msg.Headers.Subject)); string from = msg.Headers.From.MailAddress.Address; string subject = msg.Headers.Subject; string body = ""; // We prefer multipart if it's available if (msg.MessagePart.IsMultiPart) { body = msg.FindFirstHtmlVersion().GetBodyAsText(); } else { body = msg.FindFirstPlainTextVersion().GetBodyAsText(); } // Date sent to SQLite DateTime format DateTime sent_o = msg.Headers.DateSent; string sent = string.Format("{0:d4}-{1:d2}-{2:d2} {3:d2}:{4:d2}:{5:d2}", sent_o.Year, sent_o.Month, sent_o.Day, sent_o.Hour, sent_o.Minute, sent_o.Second); // Insert it (or not, if it already exists) to the SQLite database SQLiteCommand crCMD = new SQLiteCommand("INSERT OR IGNORE INTO messagetable (id,sender,subject,body,date) VALUES (@_id,@_sender,@_subject,@_body,datetime(strftime('%Y-%m-%d %H:%M:%S',@_sent)))", msgSqlCon); crCMD.Parameters.AddWithValue("@_id", id); crCMD.Parameters.AddWithValue("@_sender", from); crCMD.Parameters.AddWithValue("@_subject", subject); crCMD.Parameters.AddWithValue("@_body", MerMail.Symmetric.EncryptString(currentUser.encryption_key, body)); crCMD.Parameters.AddWithValue("@_sent", sent); crCMD.ExecuteNonQuery(); // calculate the progress percentage progress = (i * 100) / (messageCount); if (progress > lastProgress + 10) { // if the progress is 10 percent higher than lastprogress, // then report it to the progressBar, and set lastprogress // to the progress percentage right now (sender as BackgroundWorker).ReportProgress(progress); lastProgress = progress; } } }
private void listBoxMails_SelectedIndexChanged(object sender, EventArgs e) { // Check if the value should be ignored, in this case if it is below zero. if (listBoxMails.SelectedIndex < 0) return; // Retrieve the selected mail from the database. mailMessage = mailDatabase.ReadMail(textBoxMail.Text, listBoxMails.Items.Count - listBoxMails.SelectedIndex); // Check if an html format is present. if (mailMessage.FindFirstHtmlVersion() != null) // Show the html format in the webbrowser. webBrowserView.DocumentText = mailMessage.FindFirstHtmlVersion().GetBodyAsText(); // Check if an text format is present. else if (mailMessage.FindFirstPlainTextVersion() != null) // Show the text format in the webbrowser. webBrowserView.DocumentText = mailMessage.FindFirstPlainTextVersion().GetBodyAsText(); else // If nothing is found then output that something is wrong. webBrowserView.DocumentText = "Problems showing this mail, Contact Simon :-)"; }