private void btnKosz_Click(object sender, EventArgs e) { if (listBox1.SelectedItems.Count == 0) { return; } try { if ((cmbFolders.SelectedItem as Imap4FolderItem).imap4Folder.Name == "Trash") { foreach (MailItem mailItem in listBox1.SelectedItems) { mailClient.Delete(mailItem.mailInfo); } mailClient.Expunge();//było zaznaczone, teraz usunięte List <MailItem> mailItems = new List <MailItem>(); foreach (MailItem mailItem in listBox1.SelectedItems) { mailItems.Add(mailItem); } listBox1.SelectedItems.Clear(); foreach (MailItem mailItem in mailItems) { listBox1.Items.Remove(mailItem); } } else { Imap4Folder trash = null; foreach (Imap4FolderItem imap4FolderItem in cmbFolders.Items) { if (imap4FolderItem.imap4Folder.Name == "Trash") { trash = imap4FolderItem.imap4Folder; } } foreach (MailItem mailItem in listBox1.SelectedItems) { mailClient.Move(mailItem.mailInfo, trash); } foreach (MailItem mailItem in listBox1.SelectedItems) { mailClient.Delete(mailItem.mailInfo); } mailClient.Expunge(); List <MailItem> mailItems = new List <MailItem>(); foreach (MailItem mailItem in listBox1.SelectedItems) { mailItems.Add(mailItem); } listBox1.SelectedItems.Clear(); foreach (MailItem mailItem in mailItems) { listBox1.Items.Remove(mailItem); } } } catch (Exception ex) { Text = "rozłączono"; } }
private void Form1_Load(object sender, EventArgs e) { string curpath = Directory.GetCurrentDirectory(); string mailbox = String.Format("{0}\\inbox", curpath); // If the folder is not existed, create it. if (!Directory.Exists(mailbox)) { Directory.CreateDirectory(mailbox); } MailServer oServer = new MailServer("pop.gmail.com", "*****@*****.**", "jarvis99", ServerProtocol.Pop3); MailClient oClient = new MailClient("TryIt"); // If your POP3 server requires SSL connection, // Please add the following codes: oServer.SSLConnection = true; oServer.Port = 995; MessageBox.Show("Connection opened"); try { oClient.Connect(oServer); MailInfo[] infos = oClient.GetMailInfos(); MessageBox.Show("Mail information received"); MessageBox.Show(infos.ToString()); for (int i = 0; i < infos.Length; i++) { MailInfo info = infos[i]; //Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}", // info.Index, info.Size, info.UIDL); // Receive email from POP3 server Mail oMail = oClient.GetMail(info); MessageBox.Show("From: " + oMail.From.ToString()); MessageBox.Show("Subject: \r\n" + oMail.Subject); MessageBox.Show("inside1"); // Generate an email file name based on date time. System.DateTime d = System.DateTime.Now; System.Globalization.CultureInfo cur = new System.Globalization.CultureInfo("en-US"); string sdate = d.ToString("yyyyMMddHHmmss", cur); string fileName = String.Format("{0}\\{1}{2}{3}.eml", mailbox, sdate, d.Millisecond.ToString("d3"), i); MessageBox.Show("inside4"); // Save email to local disk oMail.SaveAs(fileName, true); // Mark email as deleted from POP3 server. oClient.Delete(info); } // Quit and pure emails marked as deleted from POP3 server. oClient.Quit(); } catch (Exception ep) { MessageBox.Show("error" + ep.Message); } }
static void Main(string[] args) { // Create a folder named "inbox" under current directory // to save the email retrie enter code here ved. string curpath = Directory.GetCurrentDirectory(); string mailbox = String.Format("{0}\\inbox", curpath); // If the folder is not existed, create it. if (!Directory.Exists(mailbox)) { Directory.CreateDirectory(mailbox); } // Gmail IMAP4 server is "imap.gmail.com" MailServer oServer = new MailServer("imap.gmail.com", "*****@*****.**", "yourpassword", ServerProtocol.Imap4); MailClient oClient = new MailClient("TryIt"); // Set SSL connection, oServer.SSLConnection = true; // Set 993 IMAP4 port oServer.Port = 993; try { oClient.Connect(oServer); MailInfo[] infos = oClient.GetMailInfos(); for (int i = 0; i < infos.Length; i++) { MailInfo info = infos[i]; Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}", info.Index, info.Size, info.UIDL); // Download email from GMail IMAP4 server Mail oMail = oClient.GetMail(info); Console.WriteLine("From: {0}", oMail.From.ToString()); Console.WriteLine("Subject: {0}\r\n", oMail.Subject); // Generate an email file name based on date time. System.DateTime d = System.DateTime.Now; System.Globalization.CultureInfo cur = new System.Globalization.CultureInfo("en-US"); string sdate = d.ToString("yyyyMMddHHmmss", cur); string fileName = String.Format("{0}\\{1}{2}{3}.eml", mailbox, sdate, d.Millisecond.ToString("d3"), i); // Save email to local disk oMail.SaveAs(fileName, true); // Mark email as deleted in GMail account. oClient.Delete(info); } // Quit and purge emails marked as deleted from Gmail IMAP4 server. oClient.Quit(); } catch (Exception ep) { Console.WriteLine(ep.Message); } }
private void btndescargarcorreo_Click(object sender, EventArgs e) { try { string mensajError = ""; if (InfoCuenta == null) { mail_Cuentas_Correo_Bus bus_correo = new mail_Cuentas_Correo_Bus(); List <mail_Cuentas_Correo_Info> lista_Correo = new List <mail_Cuentas_Correo_Info>(); lista_Correo = bus_correo.consultar(ref mensajError); InfoCuenta = lista_Correo.FirstOrDefault(q => q.direccion_correo == dir_correo); } if (InfoCuenta.ServidorCorreoEntrante.Length == 0 || InfoCuenta.Usuario.Length == 0 || InfoCuenta.Password.Length == 0) { MessageBox.Show("Por favor ingrese servidor, usuario y contraseña."); return; } // cargo los ID de mensaje para no tener q ir a la DB lista_codMensajeId_Existentes = new List <string>(); lista_codMensajeId_Existentes = Bus_Mensaje.consultar_CodMail_Existentes(); btndescargarcorreo.Enabled = false; btnCancel.Enabled = true; lista_Mensaje = new List <mail_Mensaje_Info>(); string mensajeError = ""; ServerAuthType authType = ServerAuthType.AuthLogin; if (InfoCuenta.Tipo_Authenticacion == "APOP") { authType = ServerAuthType.AuthCRAM5; } else if (InfoCuenta.Tipo_Authenticacion == "NTLM") { authType = ServerAuthType.AuthNTLM; } // ServerProtocol protocol = (ServerProtocol)lstProtocol.SelectedIndex; ServerProtocol protocol = new ServerProtocol(); if (InfoCuenta.TipoCuenta == "POP3") { protocol = ServerProtocol.Pop3; } if (InfoCuenta.TipoCuenta == "IMAP4") { protocol = ServerProtocol.Imap4; } if (InfoCuenta.TipoCuenta == "EXCHA_WEB_SER") { protocol = ServerProtocol.ExchangeEWS; } if (InfoCuenta.TipoCuenta == "EXCHA_WEB_DAV") { protocol = ServerProtocol.ExchangeWebDAV; } usa_sll = (InfoCuenta.Usa_SSL_Conexion_para_Descarga_correo == null) ? false : (Boolean)InfoCuenta.Usa_SSL_Conexion_para_Descarga_correo; MailServer oServer = new MailServer(InfoCuenta.ServidorCorreoEntrante, InfoCuenta.Usuario, InfoCuenta.Password, usa_sll, authType, protocol); // Para el uso de la evaluación, por favor utilice "TryIt" como el código de licencia, de lo contrario el // será lanzado excepción "código de licencia no válida". Sin embargo, el objeto expirará en 1-2 meses, y luego // "versión de prueba expiró" se lanzará una excepción. MailClient oClient = new MailClient("EG-B1374632949-00215-D3BEB6416TE2E729-A84ADDF9C5A1C85F"); //Catching the following events is not necessary, //just make the application more user friendly. //If you use the object in asp.net/windows service or non-gui application, //You need not to catch the following events. //To learn more detail, please refer to the code in EAGetMail EventHandler region oClient.OnAuthorized += new MailClient.OnAuthorizedEventHandler(OnAuthorized); oClient.OnConnected += new MailClient.OnConnectedEventHandler(OnConnected); oClient.OnIdle += new MailClient.OnIdleEventHandler(OnIdle); oClient.OnSecuring += new MailClient.OnSecuringEventHandler(OnSecuring); oClient.OnReceivingDataStream += new MailClient.OnReceivingDataStreamEventHandler(OnReceivingDataStream); bool bMantener_copia_correo = (InfoCuenta.Guardar_1_copia_de_corre_en_server_mail == null) ? false : (Boolean)InfoCuenta.Guardar_1_copia_de_corre_en_server_mail; UIDLManager oUIDLManager = new UIDLManager(); try { // Carga existían registros UIDL a UIDLManager string uidlfile = String.Format("{0}\\{1}", m_curpath, m_uidlfile); oUIDLManager.Load(uidlfile); string mailFolder = String.Format("{0}\\inbox", m_curpath); if (!Directory.Exists(mailFolder)) { Directory.CreateDirectory(mailFolder); } m_bcancel = false; lblStatus.Text = "Conectando ..."; oClient.Connect(oServer); MailInfo[] infos = oClient.GetMailInfos(); lblStatus.Text = String.Format("Total {0} email(s)", infos.Length); // Eliminar el uidl local que no se existía en el servidor. oUIDLManager.SyncUIDL(oServer, infos); oUIDLManager.Update(); int count = infos.Length; if (count > 0) { lista_Mensaje = new List <mail_Mensaje_Info>(); } int CountError = 0; for (int i = 0; i < count; i++) { MailInfo info = infos[i]; CountError = i; //if (i == 2587) { MessageBox.Show(""); } //verificar en base NO debo ir a la base uno a uno sino se hace muy largo if (lista_codMensajeId_Existentes.Contains(info.UIDL) == false) { lblStatus.Text = String.Format("Retrieving {0}/{1}...", info.Index, count); Mail oMail = oClient.GetMail(info); System.DateTime d = System.DateTime.Now; System.Globalization.CultureInfo cur = new System.Globalization.CultureInfo("en-US"); string sdate = d.ToString("yyyyMMddHHmmss", cur); string fileName = String.Format("{0}\\{1}{2}{3}.eml", mailFolder, sdate, d.Millisecond.ToString("d3"), i); try//try1 { oMail.SaveAs(fileName, true); conta = 0; conta = oMail.To.ToList().Count(); sec = 0; foreach (var itemTo in oMail.To.ToList()) { sec = sec + 1; if (sec != conta) { para += itemTo.Address + "; "; } else { para += itemTo.Address; } } conta = 0; conta = oMail.Cc.ToList().Count(); sec = 0; foreach (var itemCopia in oMail.Cc.ToList()) { sec = sec + 1; if (sec != conta) { CC += itemCopia.Address + "; "; } else { CC += itemCopia.Address; } } } catch (Exception EX) { MessageBox.Show(EX.Message + " try 1"); } try//try2 { infoMensaje = new mail_Mensaje_Info(); infoMensaje.Asunto = oMail.Subject; infoMensaje.Asunto_texto_mostrado = oMail.Subject; // infoMensaje.codMensajeId = MessageID; infoMensaje.codMensajeId = info.UIDL; infoMensaje.fileName = fileName; infoMensaje.Para = para; infoMensaje.Para_CC = CC; infoMensaje.Fecha = oMail.ReceivedDate; infoMensaje.Texto_mensaje = oMail.TextBody; infoMensaje.Tiene_Adjunto = oMail.Attachments.Count() == 0 ? false : true; if (Convert.ToString(oMail.Priority) == "Normal") { infoMensaje.Prioridad = 0; } if (Convert.ToString(oMail.Priority) == "Alta") { infoMensaje.Prioridad = 1; } if (Convert.ToString(oMail.Priority) == "Baja") { infoMensaje.Prioridad = -1; } infoMensaje.Leido = false; infoMensaje.Respondido = false; infoMensaje.No_Leido = false; infoMensaje.mail_remitente = dir_correo; infoMensaje.Eliminado = false; infoMensaje.IdTipo_Mensaje = eTipoMail.Buzon_Ent; infoMensaje.IdCuenta = IdCuenta; foreach (var itemAdju in oMail.Attachments) { mail_Mensaje_Archi_Adjunto_Info infoAdju = new mail_Mensaje_Archi_Adjunto_Info(); string nomAdju = itemAdju.Name; string extAdj = Path.GetExtension(nomAdju); if (extAdj.ToUpper() == ".PDF" || extAdj.ToUpper() == ".XML") { infoAdju.extensionArchivo = extAdj; infoAdju.Archivo_adjunto = itemAdju.Content; infoAdju.descripcion_archi = itemAdju.Name; infoMensaje.list_Archivos_Adjuntos.Add(infoAdju); } } infoMensaje.Archivo_correo = System.IO.File.ReadAllBytes(infoMensaje.fileName); Bus_Mensaje.GrabarMensajeDB(infoMensaje, ref mensajeError); //lista_Mensaje.Add(infoMensaje); } catch (Exception ex) { MessageBox.Show(ex.Message + " try 2"); } oMail.Clear(); // si lblTotal.Text = String.Format("Total {0} email(s)", lstMail.Items.Count); if (bMantener_copia_correo) { // añadir el uidl correo electrónico a uidl archivo para evitar recuperamos la próxima vez. oUIDLManager.AddUIDL(oServer, info.UIDL, fileName); } } } if (!bMantener_copia_correo) { lblStatus.Text = "Borrando ..."; for (int i = 0; i < count; i++) { oClient.Delete(infos[i]); // Eliminar UIDL de archivo uidl local. oUIDLManager.RemoveUIDL(oServer, infos[i].UIDL); } } // Eliminar método sólo marcar el correo electrónico como eliminado, // Salir método puro los mensajes de correo electrónico desde el servidor exactamente. oClient.Quit(); //if (lista_Mensaje.Count() == 0) //{ // MessageBox.Show("No existen Correos de Entrada Nuevos"); // btndescargarcorreo.Enabled = true; // btnCancel.Enabled = false; // return; //} } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); BusSisLog.Log_Error(ex.Message.ToString(), eTipoError.ERROR, this.ToString()); } // Actualizar la lista uidl de archivo uidl local y luego podemos cargar la próxima vez. oUIDLManager.Update(); lblStatus.Text = "Completed"; pgBar.Maximum = 100; pgBar.Minimum = 0; pgBar.Value = 0; btndescargarcorreo.Enabled = true; btnCancel.Enabled = false; //mostrar_mensajes(eTipoMail.Buzon_Ent, dtp_desde.Value, dtp_hasta.Value, dir_correo); } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); BusSisLog.Log_Error(ex.Message.ToString(), eTipoError.ERROR, this.ToString()); } }
private void btnStart_Click(object sender, System.EventArgs e) { string server, user, password; server = textServer.Text.Trim(); user = textUser.Text.Trim(); password = textPassword.Text.Trim(); if (server.Length == 0 || user.Length == 0 || password.Length == 0) { MessageBox.Show("Please input server, user and password."); return; } btnStart.Enabled = false; btnCancel.Enabled = true; ServerAuthType authType = ServerAuthType.AuthLogin; if (lstAuthType.SelectedIndex == 1) { authType = ServerAuthType.AuthCRAM5; } else if (lstAuthType.SelectedIndex == 2) { authType = ServerAuthType.AuthNTLM; } ServerProtocol protocol = (ServerProtocol)lstProtocol.SelectedIndex; MailServer oServer = new MailServer(server, user, password, chkSSL.Checked, authType, protocol); //For evaluation usage, please use "TryIt" as the license code, otherwise the //"invalid license code" exception will be thrown. However, the object will expire in 1-2 months, then //"trial version expired" exception will be thrown. MailClient oClient = new MailClient("TryIt"); //Catching the following events is not necessary, //just make the application more user friendly. //If you use the object in asp.net/windows service or non-gui application, //You need not to catch the following events. //To learn more detail, please refer to the code in EAGetMail EventHandler region oClient.OnAuthorized += new MailClient.OnAuthorizedEventHandler(OnAuthorized); oClient.OnConnected += new MailClient.OnConnectedEventHandler(OnConnected); oClient.OnIdle += new MailClient.OnIdleEventHandler(OnIdle); oClient.OnSecuring += new MailClient.OnSecuringEventHandler(OnSecuring); oClient.OnReceivingDataStream += new MailClient.OnReceivingDataStreamEventHandler(OnReceivingDataStream); bool bLeaveCopy = chkLeaveCopy.Checked; // UIDL is the identifier of every email on POP3/IMAP4/Exchange server, to avoid retrieve // the same email from server more than once, we record the email UIDL retrieved every time // if you delete the email from server every time and not to leave a copy of email on // the server, then please remove all the function about uidl. // UIDLManager wraps the function to write/read uidl record from a text file. UIDLManager oUIDLManager = new UIDLManager(); try { // load existed uidl records to UIDLManager string uidlfile = String.Format("{0}\\{1}", m_curpath, m_uidlfile); oUIDLManager.Load(uidlfile); string mailFolder = String.Format("{0}\\inbox", m_curpath); if (!Directory.Exists(mailFolder)) { Directory.CreateDirectory(mailFolder); } m_bcancel = false; lblStatus.Text = "Connecting ..."; oClient.Connect(oServer); MailInfo[] infos = oClient.GetMailInfos(); lblStatus.Text = String.Format("Total {0} email(s)", infos.Length); // remove the local uidl which is not existed on the server. oUIDLManager.SyncUIDL(oServer, infos); oUIDLManager.Update(); int count = infos.Length; ArrayList arReport = new ArrayList(); for (int i = 0; i < count; i++) { MailInfo info = infos[i]; if (oUIDLManager.FindUIDL(oServer, info.UIDL) != null) { // This email has been downloaded or checked before. continue; } lblStatus.Text = String.Format("Retrieving mail header {0}/{1}...", info.Index, count); System.DateTime d = System.DateTime.Now; System.Globalization.CultureInfo cur = new System.Globalization.CultureInfo("en-US"); string sdate = d.ToString("yyyyMMddHHmmss", cur); string fileName = String.Format("{0}\\{1}{2}{3}.eml", mailFolder, sdate, d.Millisecond.ToString("d3"), i); Mail oMail = new Mail("TryIt"); oMail.Load(oClient.GetMailHeader(info)); if (!oMail.IsReport) { // Not a report, continue // Add the email uidl to uidl file to avoid we check it next time. oUIDLManager.AddUIDL(oServer, info.UIDL, fileName); continue; } // This is a report, get the entire email. oMail = oClient.GetMail(info); oMail.SaveAs(fileName, true); ListViewItem item = new ListViewItem(oMail.From.ToString()); item.SubItems.Add(oMail.Subject); item.SubItems.Add(oMail.ReceivedDate.ToString("yyyy-MM-dd HH:mm:ss")); item.Font = new System.Drawing.Font(item.Font, FontStyle.Bold); item.Tag = fileName; lstMail.Items.Insert(0, item); oMail.Clear(); lblTotal.Text = String.Format("Total {0} email(s)", lstMail.Items.Count); arReport.Add(info); // Add the report mail info to arraylist, // then we can delete it later. if (bLeaveCopy) { // Add the email uidl to uidl file to avoid we retrieve it next time. oUIDLManager.AddUIDL(oServer, info.UIDL, fileName); } } if (!bLeaveCopy) { lblStatus.Text = "Deleting ..."; count = arReport.Count; for (int i = 0; i < count; i++) { MailInfo info = arReport[i] as MailInfo; oClient.Delete(info); // Remove UIDL from local uidl file. oUIDLManager.RemoveUIDL(oServer, info.UIDL); } } // Delete method just mark the email as deleted, // Quit method pure the emails from server exactly. oClient.Quit(); } catch (Exception ep) { MessageBox.Show(ep.Message); } // Update the uidl list to local uidl file and then we can load it next time. oUIDLManager.Update(); lblStatus.Text = "Completed"; pgBar.Maximum = 100; pgBar.Minimum = 0; pgBar.Value = 0; btnStart.Enabled = true; btnCancel.Enabled = false; }
static void Main(string[] args) { SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY"); oExcel.CreateSpreadsheet(); try { string sFullPath = ""; string sLocalInbox = sBackupDir; // Create a folder named "inbox" under current directory // to save the email retrieved. if (!Directory.Exists(sLocalInbox)) { // If the folder is not existed, create it. Directory.CreateDirectory(sLocalInbox); } MailServer oServer = new MailServer("imap.gmail.com", // Gmail IMAP4 server is "imap.gmail.com" oConfig.Mail, oConfig.Password, ServerProtocol.Imap4); oServer.SSLConnection = true; // Enable SSL connection. oServer.Port = 993; // Set 993 SSL port MailClient oClient = new MailClient("TryIt"); oClient.Connect(oServer); MailInfo[] infos = oClient.GetMailInfos(); Console.WriteLine("Total {0} email(s)\r\n", infos.Length); for (int i = 0; i < infos.Length; i++) { MailInfo info = infos[i]; Mail oMail = oClient.GetMail(info); // Receive email from IMAP4 server DateTime dDate = oMail.ReceivedDate; if (oMail.From.ToString().Contains(oConfig.Bank)) { Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}", info.Index, info.Size, info.UIDL); Console.WriteLine("From: {0}", oMail.From.ToString()); Console.WriteLine("Subject: {0}\r\n", oMail.Subject); } string sMailContent = Regex.Replace(oMail.HtmlBody, @"\t|\n|\r", ""); if (oMail.From.ToString().Contains(oConfig.Bank)) { // if FROM contains our bank string sFrom = Regex.Replace(oMail.From.ToString(), @"\s+", "").Replace("\"", "").Replace("<", "").Replace(">", "-"); // Add "from" to name of the mail string sFileName = _generateTemporaryFileName(i + 1, sFrom); // Generate an unqiue email file name based on date time. sFullPath = string.Format("{0}\\{1}", sLocalInbox, sFileName); if (oMail.From.ToString().Contains(oConfig.Bank)) { oMail.SaveAs(sFullPath, true); // Save email to local disk } using (StreamReader srFullMailTxt = new StreamReader(sFullPath)) { string[] sLinesList = File.ReadAllLines(sFullPath); bool bIsMatch = false; for (int x = 0; x < sLinesList.Length - 1; x++) { if (oUtf8Converter.Utf8Convert(sMailContent) == sLinesList[x]) { //convert all to UTF-8, coz in mails are some polish chars srFullMailTxt.Close(); oExcel.AddToSpreadsheet(oIpkoConverter.CutDate(dDate.ToString(), oIpkoConverter.CutMessage(sMailContent))); bIsMatch = true; } } if (!bIsMatch) { srFullMailTxt.Close(); Console.WriteLine("nope, sry.."); // if value from match doesn't exist } } } if (oMail.From.ToString().Contains(oConfig.Bank)) { // function to delete values from gmail inbox after downloading them to local disc oClient.Delete(info); } } string[] sTxtList = Directory.GetFiles(sBackupDir, "*.txt"); foreach (string f in sTxtList) { //delete all FULL maill txt files from directory File.Delete(f); } // Quit and expunge emails marked as deleted from IMAP4 server. oClient.Quit(); Console.WriteLine("Completed!"); } catch (Exception ep) { Console.WriteLine(ep.Message); Console.ReadKey(); } }
public List<PurchaseEmail> CheckEmail() { string curpath = Directory.GetCurrentDirectory(); string mailbox = String.Format("{0}\\inbox", curpath); string htmlMailbox = String.Format("{0}\\htmlInbox", curpath); // If the .eml and .htm folders do not exist, create it. if (!Directory.Exists(mailbox)) { Directory.CreateDirectory(mailbox); } if (!Directory.Exists(htmlMailbox)) { Directory.CreateDirectory(htmlMailbox); } // Gmail IMAP4 server is "imap.gmail.com" MailServer oServer = new MailServer("imap.gmail.com", "*****@*****.**", "**Jessica8", ServerProtocol.Imap4); MailClient oClient = new MailClient("TryIt"); // Set SSL connection, oServer.SSLConnection = true; // Set 993 IMAP4 port oServer.Port = 993; try { oClient.Connect(oServer); MailInfo[] infos = oClient.GetMailInfos(); for (int i = 0; i < infos.Length; i++) { MailInfo info = infos[i]; //Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}", info.Index, info.Size, info.UIDL); // Download email from GMail IMAP4 server Mail oMail = oClient.GetMail(info); if (oMail.From.ToString().Contains("*****@*****.**")) { // Generate an email file name based on date time. System.DateTime d = System.DateTime.Now; var cur = new System.Globalization.CultureInfo("en-US"); string sdate = d.ToString("yyyyMMddHHmmss", cur); string fileName = String.Format("{0}\\{1}{2}{3}.eml", mailbox, sdate, d.Millisecond.ToString("d3"), i); // Save email to local disk oMail.SaveAs(fileName, true); } // Mark email as deleted in GMail account. oClient.Delete(info); } // Quit and purge emails marked as deleted from Gmail IMAP4 server. oClient.Quit(); } catch (Exception ep) { MessageBox.Show(ep.Message); } // Get all *.eml files in specified folder and parse it one by one. string[] files = Directory.GetFiles(mailbox, "*.eml"); var purchaseList = new List<PurchaseEmail>(); for (int i = 0; i < files.Length; i++) { var convertedMessage = ConvertMailToHtml(files[i]); if (System.IO.File.Exists(files[i])) { // Use a try block to catch IOExceptions, to // handle the case of the file already being // opened by another process. try { System.IO.File.Delete(files[i]); } catch (System.IO.IOException e) { MessageBox.Show(e.Message); } } purchaseList.Add(convertedMessage); } return purchaseList; }
public string Rec() { // Create a folder named "inbox" under current directory // to save the email retrieved. string curpath = Directory.GetCurrentDirectory(); string mailbox = String.Format("{0}\\inbox", curpath); // If the folder is not existed, create it. if (!Directory.Exists(mailbox)) { Directory.CreateDirectory(mailbox); } MailServer oServer = new MailServer("pop.gmail.com", "*****@*****.**", "11041191104091", EAGetMail.ServerProtocol.Pop3); MailClient oClient = new MailClient("TryIt"); // If your POP3 server requires SSL connection, // Please add the following codes: oServer.SSLConnection = true; oServer.Port = 995; // Console.WriteLine("connection"); try { oClient.Connect(oServer); MailInfo[] infos = oClient.GetMailInfos(); string tx = ""; // Console.WriteLine("connection2"); for (int i = 0; i < infos.Length; i++) { MailInfo info = infos[i]; //Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}", // info.Index, info.Size, info.UIDL); // Receive email from POP3 server Mail oMail = oClient.GetMail(info); // Console.WriteLine("From: {0}", oMail.From.ToString()); // Console.WriteLine("Subject: {0}\r\n", oMail.Subject); // Console.WriteLine("Text: {0}\n", oMail.TextBody); // Generate an email file name based on date time. System.DateTime d = System.DateTime.Now; System.Globalization.CultureInfo cur = new System.Globalization.CultureInfo("en-US"); string sdate = d.ToString("yyyyMMddHHmmss", cur); string fileName = String.Format("{0}\\{1}{2}{3}.eml", mailbox, sdate, d.Millisecond.ToString("d3"), i); // Save email to local disk oMail.SaveAs(fileName, true); string text = System.IO.File.ReadAllText(fileName); // Console.WriteLine(text); string sub = oMail.Subject; // Mark email as deleted from POP3 server. oClient.Delete(info); if (sub == "test email from c# project") { ; } tx = oMail.TextBody; } // Quit and pure emails marked as deleted from POP3 server. oClient.Quit(); return(tx);; } catch (Exception ep) { //Console.WriteLine(ep.Message); return(ep.Message); } //Console.ReadLine(); }
public static List <String> RecieveEmailsPop3() { List <string> infosGot = new List <string>(); // Create a folder named "inbox" under current directory // to save the email retrieved. string curpath = Directory.GetCurrentDirectory(); string mailbox = String.Format("{0}\\inbox", curpath); // If the folder is not existed, create it. if (!Directory.Exists(mailbox)) { Directory.CreateDirectory(mailbox); } MailServer oServer = new MailServer("pop.gmail.com", "*****@*****.**", "Europesbiggestowl", ServerProtocol.Pop3); MailClient oClient = new MailClient("TryIt"); // If your POP3 server requires SSL connection, // Please add the following codes: oServer.SSLConnection = true; oServer.Port = 995; try { oClient.Connect(oServer); MailInfo[] infos = oClient.GetMailInfos(); for (int i = 0; i < infos.Length; i++) { MailInfo info = infos[i]; infosGot.Add(info.Index.ToString()); infosGot.Add(info.Size.ToString()); infosGot.Add(info.UIDL.ToString()); Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}", info.Index, info.Size, info.UIDL); // Receive email from POP3 server Mail oMail = oClient.GetMail(info); infosGot.Add(oMail.From.ToString()); infosGot.Add(oMail.Subject); Console.WriteLine("From: {0}", oMail.From.ToString()); Console.WriteLine("Subject: {0}\r\n", oMail.Subject); // Generate an email file name based on date time. System.DateTime d = System.DateTime.Now; System.Globalization.CultureInfo cur = new System.Globalization.CultureInfo("en-US"); string sdate = d.ToString("yyyyMMddHHmmss", cur); string fileName = String.Format("{0}\\{1}{2}{3}.eml", mailbox, sdate, d.Millisecond.ToString("d3"), i); // Save email to local disk oMail.SaveAs(fileName, true); // Mark email as deleted from POP3 server. oClient.Delete(info); } // Quit and purge emails marked as deleted from POP3 server. oClient.Quit(); } catch (Exception ep) { Console.WriteLine(ep.Message); } return(infosGot); }
private void btnStart_Click(object sender, EventArgs e) { try { string server, user, password; //server = textServer.Text.Trim(); //user = textUser.Text.Trim(); //password = textPassword.Text.Trim(); server = "mail.it-corp.com"; user = "******"; password = "******"; //user = "******"; //password = "******"; if (server.Length == 0 || user.Length == 0 || password.Length == 0) { MessageBox.Show("Por favor ingrese servidor, usuario y contraseña."); return; } btnStart.Enabled = false; btnCancel.Enabled = true; ServerAuthType authType = ServerAuthType.AuthLogin; if (lstAuthType.SelectedIndex == 1) { authType = ServerAuthType.AuthCRAM5; } else if (lstAuthType.SelectedIndex == 2) { authType = ServerAuthType.AuthNTLM; } ServerProtocol protocol = (ServerProtocol)lstProtocol.SelectedIndex; MailServer oServer = new MailServer(server, user, password, chkSSL.Checked, authType, protocol); // Para el uso de la evaluación, por favor utilice "TryIt" como el código de licencia, de lo contrario el // será lanzado excepción "código de licencia no válida". Sin embargo, el objeto expirará en 1-2 meses, y luego // "versión de prueba expiró" se lanzará una excepción. MailClient oClient = new MailClient("EG-B1374632949-00215-D3BEB6416TE2E729-A84ADDF9C5A1C85F"); //Catching the following events is not necessary, //just make the application more user friendly. //If you use the object in asp.net/windows service or non-gui application, //You need not to catch the following events. //To learn more detail, please refer to the code in EAGetMail EventHandler region oClient.OnAuthorized += new MailClient.OnAuthorizedEventHandler(OnAuthorized); oClient.OnConnected += new MailClient.OnConnectedEventHandler(OnConnected); oClient.OnIdle += new MailClient.OnIdleEventHandler(OnIdle); oClient.OnSecuring += new MailClient.OnSecuringEventHandler(OnSecuring); oClient.OnReceivingDataStream += new MailClient.OnReceivingDataStreamEventHandler(OnReceivingDataStream); bool bLeaveCopy = chkLeaveCopy.Checked; // UIDL es el identificador de cada correo electrónico de POP3 / IMAP4 / servidor de Exchange, para evitar recuperar // El mismo correo electrónico desde el servidor más de una vez, que registra el email UIDL recuperada cada vez // Si elimina el correo electrónico desde el servidor cada vez y no dejar una copia del correo electrónico en // El servidor, por favor, elimine toda la función sobre uidl. // UIDLManager envuelve la función de escribir / leer el registro uidl desde un archivo de texto. UIDLManager oUIDLManager = new UIDLManager(); try { // Carga existían registros UIDL a UIDLManager string uidlfile = String.Format("{0}\\{1}", m_curpath, m_uidlfile); oUIDLManager.Load(uidlfile); string mailFolder = String.Format("{0}\\inbox", m_curpath); if (!Directory.Exists(mailFolder)) { Directory.CreateDirectory(mailFolder); } m_bcancel = false; lblStatus.Text = "Connecting ..."; oClient.Connect(oServer); MailInfo[] infos = oClient.GetMailInfos(); lblStatus.Text = String.Format("Total {0} email(s)", infos.Length); // Eliminar el uidl local que no se existía en el servidor. oUIDLManager.SyncUIDL(oServer, infos); oUIDLManager.Update(); int count = infos.Length; if (count > 0) { lista_Mensaje = new List <mail_Mensaje_Info>(); } for (int i = 0; i < count; i++) { MailInfo info = infos[i]; //verificar en base if (Bus_Mensaje.Verifica_codMensajeId(info.UIDL) == false) { //} //if (oUIDLManager.FindUIDL(oServer, info.UIDL) != null /*&& "si esta en base"|| oUIDLManager.FindUIDL(oServer, info.UIDL) == null && "si esta en base"*/ ) //{ // // este correo electrónico se ha descargado antes. // continue; //} lblStatus.Text = String.Format("Retrieving {0}/{1}...", info.Index, count); Mail oMail = oClient.GetMail(info); System.DateTime d = System.DateTime.Now; System.Globalization.CultureInfo cur = new System.Globalization.CultureInfo("en-US"); string sdate = d.ToString("yyyyMMddHHmmss", cur); string fileName = String.Format("{0}\\{1}{2}{3}.eml", mailFolder, sdate, d.Millisecond.ToString("d3"), i); oMail.SaveAs(fileName, true); //llenar grid //int conta = oMail.Headers.Count; //string MessageID = ""; //for (int y = 0; y < conta; y++) //{ // string valida = "Message-ID"; // string extrae = oMail.Headers[y].ToString().Substring(0, 10); // string result = ""; // if (extrae == valida) // { // MessageID = oMail.Headers[y].ToString(); // break; // } // // break; //} conta = 0; conta = oMail.To.ToList().Count(); sec = 0; foreach (var itemTo in oMail.To.ToList()) { sec = sec + 1; if (sec != conta) { para += itemTo.Address + "; "; } else { para += itemTo.Address; } } conta = 0; conta = oMail.Cc.ToList().Count(); sec = 0; foreach (var itemCopia in oMail.Cc.ToList()) { sec = sec + 1; if (sec != conta) { CC += itemCopia.Address + "; "; } else { CC += itemCopia.Address; } } infoMensaje = new mail_Mensaje_Info(); infoMensaje.Asunto = oMail.Subject; infoMensaje.Asunto_texto_mostrado = oMail.Subject; // infoMensaje.codMensajeId = MessageID; infoMensaje.codMensajeId = info.UIDL; infoMensaje.fileName = fileName; infoMensaje.Para = para; infoMensaje.Para_CC = CC; infoMensaje.Fecha = oMail.ReceivedDate; infoMensaje.Texto_mensaje = oMail.TextBody; infoMensaje.Tiene_Adjunto = oMail.Attachments.Count() == 0 ? false : true; if (Convert.ToString(oMail.Priority) == "Normal") { infoMensaje.Prioridad = 0; } if (Convert.ToString(oMail.Priority) == "Alta") { infoMensaje.Prioridad = 1; } if (Convert.ToString(oMail.Priority) == "Baja") { infoMensaje.Prioridad = -1; } infoMensaje.Leido = false; infoMensaje.Respondido = false; infoMensaje.No_Leido = false; infoMensaje.mail_remitente = correo; infoMensaje.Eliminado = false; infoMensaje.IdTipo_Mensaje = eTipoMail.Buzon_Ent; infoMensaje.IdCuenta = IdCuenta; foreach (var itemAdju in oMail.Attachments) { mail_Mensaje_Archi_Adjunto_Info infoAdju = new mail_Mensaje_Archi_Adjunto_Info(); string nomAdju = itemAdju.Name; string extAdj = Path.GetExtension(nomAdju); if (extAdj == ".pdf" || extAdj == ".xml") { infoAdju.extensionArchivo = extAdj; infoAdju.Archivo_adjunto = itemAdju.Content; infoAdju.descripcion_archi = itemAdju.Name; infoMensaje.list_Archivos_Adjuntos.Add(infoAdju); } } infoMensaje.Archivo_correo = System.IO.File.ReadAllBytes(infoMensaje.fileName); lista_Mensaje.Add(infoMensaje); gridControl_Correo.DataSource = lista_Mensaje; gridControl_Correo.RefreshDataSource(); oMail.Clear(); // si lblTotal.Text = String.Format("Total {0} email(s)", lstMail.Items.Count); if (bLeaveCopy) { // añadir el uidl correo electrónico a uidl archivo para evitar recuperamos la próxima vez. oUIDLManager.AddUIDL(oServer, info.UIDL, fileName); } } } if (!bLeaveCopy) { lblStatus.Text = "Deleting ..."; for (int i = 0; i < count; i++) { oClient.Delete(infos[i]); // Eliminar UIDL de archivo uidl local. oUIDLManager.RemoveUIDL(oServer, infos[i].UIDL); } } // Eliminar método sólo marcar el correo electrónico como eliminado, // Salir método puro los mensajes de correo electrónico desde el servidor exactamente. oClient.Quit(); if (lista_Mensaje.Count() == 0) { MessageBox.Show("No existen Correos de Entrada Nuevos"); return; } } catch (Exception ex) { BusSisLog.Log_Error(ex.Message.ToString(), eTipoError.ERROR, this.ToString()); MessageBox.Show(ex.Message.ToString()); } // Actualizar la lista uidl de archivo uidl local y luego podemos cargar la próxima vez. oUIDLManager.Update(); lblStatus.Text = "Completed"; pgBar.Maximum = 100; pgBar.Minimum = 0; pgBar.Value = 0; btnStart.Enabled = true; btnCancel.Enabled = false; } catch (Exception ex) { BusSisLog.Log_Error(ex.Message.ToString(), eTipoError.ERROR, this.ToString()); MessageBox.Show(ex.Message.ToString()); } }
static void getemailattachments() { // Create a folder named inbox under current directory // to save the email retrieved. string curpath = Directory.GetCurrentDirectory(); string mailbox = String.Format("{0}\\inbox", curpath); // If the folder is not existed, create it. if (!Directory.Exists(mailbox)) { Directory.CreateDirectory(mailbox); } // Gmail IMAP4 server is "imap.gmail.com" MailServer oServer = new MailServer("imap.gmail.com", "*****@*****.**", "RCISkey1", ServerProtocol.Imap4); MailClient oClient = new MailClient("TryIt"); oServer.SSLConnection = true; // Set SSL connection, oServer.Port = 993; // Set 993 IMAP4 port try { oClient.Connect(oServer); MailInfo[] infos = oClient.GetMailInfos(); for (int i = 0; i < infos.Length; i++) { MailInfo info = infos[i]; Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}", info.Index, info.Size, info.UIDL); // Download email from GMail IMAP4 server Mail oMail = oClient.GetMail(info); oMail.DecodeTNEF(); Attachment[] atts = oMail.Attachments; int count = atts.Length; string tempFolder = "c:\\temp"; if (!Directory.Exists(tempFolder)) { Directory.CreateDirectory(tempFolder); } //Saves attachments. for (int c = 0; c < count; c++) { Attachment att = atts[c]; string attname = String.Format("{0}\\{1}", tempFolder, att.Name); att.SaveAs(attname, true); } // Mark email as deleted in GMail account to prevent duplicats. oClient.Delete(info); } // Quit and purge emails marked as deleted from Gmail IMAP4 server. oClient.Quit(); } catch (Exception ep) { Console.WriteLine(ep.Message); Console.ReadKey(); } } //Method that gets emails and saves attachments to temp folder
private void tryFindLostedToolStripMenuItem_Click(object sender, EventArgs e) { //load acc myCons.Text = "load data" + Environment.NewLine; var loadAcc = new LoadAccount() { Path = this.Path }; acc = loadAcc.GetAccountList(Path + '/' + _blaster, Path + '/' + _base, Path); var allGmail = acc.FindAll(w => w.Email.Contains("@gmail.com")); List <string> done = new List <string>(); foreach (var acc in allGmail) { myCons.Text = acc.Email; string clearEmail = acc.Email.Replace(".", ""); if (done.Contains(clearEmail)) { continue; } done.Add(clearEmail); string pass = (new Settings().GetEmailPassword(acc.Email) == null) ? acc.EmailPassword : new Settings().GetEmailPassword(acc.Email); MailServer oServer = new MailServer(new Settings().GetEmailHost(acc.Email), acc.Email, pass, ServerProtocol.Pop3); MailClient oClient = new MailClient("TryIt"); // Please add the following codes: oServer.SSLConnection = true; oServer.Port = 995; acc.Time = DateTime.Now; try { oClient.Connect(oServer); MailInfo[] infos = oClient.GetMailInfos(); infos = infos.Reverse().ToArray(); for (int i = 0; i < 75; i++) { string resetEmailUrl = null; MailInfo info = infos[i]; Mail oMail = oClient.GetMail(info); if ((DateTime.Today - oMail.SentDate).TotalHours > 24) { continue; } var subj = oMail.Subject; var rep = oMail.To[0].Address; myCons.Text += i.ToString(); var x = allGmail.FindAll(em => em.Email == rep); if (allGmail.FindAll(em => em.Email == rep).Count > 0) { continue; } //false if (oMail.From.Address.ToString().Contains("pinterest")) { resetEmailUrl = new GetLink().FindLink(oMail.HtmlBody); } if (resetEmailUrl != null) { TryReset(acc, resetEmailUrl, rep, "missed.txt"); // yea we do reset here } File.AppendAllText(this._res + '/' + acc.Nick + ".html", "<h1>" + acc.Email + "</h1><h3>" + oMail.From.Address + "</h3><h3>" + oMail.ReceivedDate + "</h3><br>" + oMail.HtmlBody + "<br><br><br>"); // Mark email as deleted from POP3 server. oClient.Delete(info); } // Quit and pure emails marked as deleted from POP3 server. oClient.Quit(); } catch (Exception ep) { File.AppendAllText(this._res + System.IO.Path.DirectorySeparatorChar + "total_bad.txt", acc.Email + Environment.NewLine); } } //naiti vse gmail // proverit vse pochti gmail gde netu acc }
public Account Read(Account acc) { string pass = (new Settings().GetEmailPassword(acc.Email) == null) ? acc.EmailPassword : new Settings().GetEmailPassword(acc.Email); MailServer oServer = new MailServer(new Settings().GetEmailHost(acc.Email), acc.Email, acc.EmailPassword, ServerProtocol.Pop3); MailClient oClient = new MailClient("TryIt"); // Please add the following codes: oServer.SSLConnection = true; oServer.Port = 995; if (acc.Email.Contains("gmail")) { oServer.Port = 993; } acc.Time = DateTime.Now; try { oClient.Connect(oServer); MailInfo[] infos = oClient.GetMailInfos(); infos = infos.Reverse().ToArray(); for (int i = 0; i < 25; i++) { string resetEmailUrl = null; MailInfo info = infos[i]; Mail oMail = oClient.GetMail(info); if ((DateTime.Today - oMail.SentDate).TotalHours > 12) { continue; } var subj = oMail.Subject; var rep = oMail.To[0].Address; if (acc.Email.Contains("@gmail.com")) { if (acc.Email != rep) { continue; } } if (acc.Email == "*****@*****.**") { var x = 0; } //false if (oMail.From.Address.ToString().Contains("pinterest.com")) { resetEmailUrl = new GetLink().FindLink(oMail.HtmlBody); } if (resetEmailUrl != null) { TryReset(acc, resetEmailUrl, rep); // yea we do reset here } File.AppendAllText(this._res + '/' + acc.Nick + ".html", "<h1>" + acc.Email + "</h1><h3>" + oMail.From.Address + "</h3><h3>" + oMail.ReceivedDate + "</h3><br>" + oMail.HtmlBody + "<br><br><br>"); // Mark email as deleted from POP3 server. oClient.Delete(info); } // Quit and pure emails marked as deleted from POP3 server. oClient.Quit(); return(acc); } catch (Exception ep) { File.AppendAllText(this._res + System.IO.Path.DirectorySeparatorChar + "total_bad.txt", acc.Email + Environment.NewLine); acc.Status = ep.Message; return(acc); } }
//private static PhantomJSDriverService _GetJsSettings() //{ // var serviceJs = PhantomJSDriverService.CreateDefaultService(); // serviceJs.HideCommandPromptWindow = true; // return serviceJs; //} public void Read(int x) { count++; // this.Text = count.ToString(); Account account = acc[x]; string pass = (new Settings().GetEmailPassword(account.Email) == null) ? account.EmailPassword : new Settings().GetEmailPassword(account.Email); var serverproto = (account.Email.Contains("@gmail.com")) ? ServerProtocol.Imap4 : ServerProtocol.Pop3; MailServer oServer = new MailServer(new Settings().GetEmailHost(account.Email), account.Email, pass, serverproto); MailClient oClient = new MailClient("TryIt"); // oClient.LogFileName = "maillog.txt"; // Please add the following codes: oServer.SSLConnection = true; oServer.Port = (account.Email.Contains("@gmail.com")) ? 993 : 995; account.Time = DateTime.Now; try { oClient.Connect(oServer); MailInfo[] infos = oClient.GetMailInfos(); infos = infos.Reverse().ToArray(); /////////////// here :) just read all int gmailCount = account.Email.Contains("gmail") ? 100 : 25; for (int i = 0; i < gmailCount; i++) { string resetEmailUrl = null; MailInfo info = infos[i]; Mail oMail; oMail = oClient.GetMail(info); if (oMail.HtmlBody.Contains("suspended your Pinterest")) { HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); doc.LoadHtml(oMail.HtmlBody); HtmlNodeCollection links = doc.DocumentNode.SelectNodes("//a"); foreach (HtmlNode link in links) { if (link.InnerText.Contains("this link")) { var driver = GetDriver(); driver.Navigate().GoToUrl(link.GetAttributeValue("href", null)); Thread.Sleep(5000); driver.Quit(); myCons.Text = "spam policy"; oClient.Delete(info); } } continue; } else if (oMail.HtmlBody.Contains("Confirm your email")) { HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); doc.LoadHtml(oMail.HtmlBody); HtmlNodeCollection links = doc.DocumentNode.SelectNodes("//a"); foreach (HtmlNode link in links) { if (link.InnerText.Contains("Confirm your email")) { var driver = GetDriver(); driver.Navigate().GoToUrl(link.GetAttributeValue("href", null)); Thread.Sleep(5000); driver.Quit(); myCons.Text = "Confirm"; oClient.Delete(info); } } continue; } if ((DateTime.Today - oMail.SentDate).TotalHours > 12) { continue; } var subj = oMail.Subject; var rep = oMail.To[0].Address; //if (account.Email.Contains("@gmail.com")) //{ // if (account.Email != rep) // { // continue; // } //} //false if (oMail.From.Address.ToString().Contains("pinterest")) { resetEmailUrl = new GetLink().FindLink(oMail.HtmlBody); } if (resetEmailUrl != null) { TryReset(account, resetEmailUrl, rep); } } // Quit and pure emails marked as deleted from POP3 server. acc[x] = account; dataGridView.Update(); dataGridView.Refresh(); } catch (Exception ep) { try { File.AppendAllText(this._res + System.IO.Path.DirectorySeparatorChar + "total_bad.txt", account.Email + ep.Message + Environment.NewLine); account.Status = ep.Message; } catch { } } finally { try { oClient.Quit(); } catch { } } }
private void Delete_Click(object sender, RoutedEventArgs e) { client.Delete((lbMail.SelectedItem as MyLetter).info); lbMail.Items.Remove(lbMail.SelectedItem); }
public void ReceiveMailByOauth() { try { string client_id = "3ac1c2b8-9518-4f7d-9520-f886515364d6"; // "8f54719b-4070-41ae-91ad-f48e3c793c5f"; string client_secret = "s3y39]smt_rQ5D.-WXbol0RV6=9mFUaz"; // "cbmYyGQjz[d29wL2ArcgoO7HLwJXL/-."; // If your application is not created by Office365 administrator, // please use Office365 directory tenant id, you should ask Offic365 administrator to send it to you. // Office365 administrator can query tenant id in https://portal.azure.com/ - Azure Active Directory. string tenant = "b5b8b483-5597-4ae7-8e27-fcc464a3b584";// "79a42c6f-5a9a-439b-a2ca-7aa1b0ed9776"; string scopes = "https://outlook.office.com/EWS.AccessAsUser.All%20offline_access%20email%20openid"; //string scopes = "https://outlook.office365.com/EWS.AccessUserEmail"; string requestData = string.Format("client_id={0}&client_secret={1}&scope={2}", client_id, client_secret, scopes); string tokenUri = string.Format("https://login.microsoftonline.com/{0}/oauth2/v2.0/token", tenant); //string tokenUri = string.Format("https://login.microsoftonline.com/{0}", tenant); string responseText = _postString(tokenUri, requestData); OAuthResponseParser parser = new OAuthResponseParser(); parser.Load(responseText); // Create a folder named "inbox" under current directory // to save the email retrieved. string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory()); // If the folder is not existed, create it. if (!Directory.Exists(localInbox)) { Directory.CreateDirectory(localInbox); } string officeUser = "******"; string token = parser.AccessToken; //token = "eyJ0eXAiOiJKV1QiLCJub25jZSI6Imhhc2VaaEZUQ3gtY1RmVFM4ZGtUN1lydVEzQ3BwUFl5ZE1xUDdjT3d1RFkiLCJhbGciOiJSUzI1NiIsIng1dCI6IllNRUxIVDBndmIwbXhvU0RvWWZvbWpxZmpZVSIsImtpZCI6IllNRUxIVDBndmIwbXhvU0RvWWZvbWpxZmpZVSJ9.eyJhdWQiOiJodHRwczovL291dGxvb2sub2ZmaWNlLmNvbSIsImlzcyI6Imh0dHBzOi8vc3RzLndpbmRvd3MubmV0L2I1YjhiNDgzLTU1OTctNGFlNy04ZTI3LWZjYzQ2NGEzYjU4NC8iLCJpYXQiOjE1ODUxNDA4NzgsIm5iZiI6MTU4NTE0MDg3OCwiZXhwIjoxNTg1MTQ0Nzc4LCJhY2N0IjowLCJhY3IiOiIxIiwiYWlvIjoiQVRRQXkvOE9BQUFBaTFCQTFnQmw0dXpCRkVIOTlVWnEzTjIwRFFUUjkwZjM2eU1DNkoxeWRqNzkxRjZSZzJ5YnlFNUs1RzZ0WWVRUCIsImFtciI6WyJwd2QiXSwiYXBwX2Rpc3BsYXluYW1lIjoiVHJhYzIgRVdTIENvbm5lY3Rpb24iLCJhcHBpZCI6IjNhYzFjMmI4LTk1MTgtNGY3ZC05NTIwLWY4ODY1MTUzNjRkNiIsImFwcGlkYWNyIjoiMCIsImRldmljZWlkIjoiNmNlMTc2MDgtMTUyOC00N2I5LWIwODItOTc3ZDJhNmE1N2E2IiwiZW5mcG9saWRzIjpbXSwiZmFtaWx5X25hbWUiOiJZYXJsYWdhZGRhIiwiZ2l2ZW5fbmFtZSI6IlBhdmFuIiwiaXBhZGRyIjoiMTY1LjIyNS4wLjc5IiwibmFtZSI6IllhcmxhZ2FkZGEsIFBhdmFuIiwib2lkIjoiZDNiMTMzMzYtMGFlZC00MzQ1LWE1ZmQtMmNjODM4YTZiNWYxIiwib25wcmVtX3NpZCI6IlMtMS01LTIxLTI3MjQxMTM3OTctNDI0MTE3MDAxNi0yNTY2NzgzOTgwLTIxNzU3NSIsInB1aWQiOiIxMDAzQkZGRDlBQ0VENjExIiwic2NwIjoiRVdTLkFjY2Vzc0FzVXNlci5BbGwgVXNlci5SZWFkIiwic2lkIjoiYzZhZDQwYWQtMTg4OC00ZGU0LTgxYTgtMmI5OTM0MzYxYzhjIiwic2lnbmluX3N0YXRlIjpbImR2Y19tbmdkIiwiZHZjX2RtamQiLCJrbXNpIl0sInN1YiI6IlRrdnVRU3NvV3p3MlZIaWtucVJpVnFJMXAtclpqaUJkc2JYbm81ZWRtUEEiLCJ0aWQiOiJiNWI4YjQ4My01NTk3LTRhZTctOGUyNy1mY2M0NjRhM2I1ODQiLCJ1bmlxdWVfbmFtZSI6InBhdmFuLnlhcmxhZ2FkZGFAYnNjaS5jb20iLCJ1cG4iOiJwYXZhbi55YXJsYWdhZGRhQGJzY2kuY29tIiwidXRpIjoiYUNsWXBZZzM4MGl2bkVMSlZZUk5BQSIsInZlciI6IjEuMCJ9.Yd4qV8E3jQAOzDKWU-H5e7__XvJvPXOa4QwT_ryauAVPLG8rV_3tIwZdVHdsYUb3T4dSjkivq7kpl2AvbJGiBF1tZSBhrKEjlpPtYNZyE_oqTtiB0G06ZsoDac37ZatPqKq3OhraYh4OO7VYM8WNCvoeebwHIxe3PZZYRuFCZ-Vu2E3HtkiXFduxXQlcsKXFvEI136xQXMPYw1onSGEybMiz5HYsPPTVHx0PW4WEAyb4tiTNtby2vfFxbMFUROkZhwvRzeQgsHXYuafer2ebiWHapPOmkIbrXHnIvyjEJH8vSg4gGRW2HWvDyLxwR5UhZDcn_if0wa16qdDkFz7qzg"; // use SSL EWS + OAUTH 2.0 MailServer oServer = new MailServer("outlook.office365.com", officeUser, token, true, ServerAuthType.AuthXOAUTH2, ServerProtocol.ExchangeEWS); Console.WriteLine("Connecting server ..."); MailClient oClient = new MailClient("TryIt"); oClient.Connect(oServer); Console.WriteLine("Retreiving email list ..."); MailInfo[] infos = oClient.GetMailInfos(); Console.WriteLine("Total {0} email(s)", infos.Length); for (int i = 0; i < infos.Length; i++) { Console.WriteLine("Checking {0}/{1} ...", i + 1, infos.Length); MailInfo info = infos[i]; // Generate an unqiue email file name based on date time. string fileName = _generateFileName(i + 1); string fullPath = string.Format("{0}\\{1}", localInbox, fileName); Console.WriteLine("Downloading {0}/{1} ...", i + 1, infos.Length); Mail oMail = oClient.GetMail(info); // Save mail to local file oMail.SaveAs(fullPath, true); // Mark the email as deleted on server. Console.WriteLine("Deleting ... {0}/{1}", i + 1, infos.Length); oClient.Delete(info); } Console.WriteLine("Disconnecting ..."); // Delete method just mark the email as deleted, // Quit method expunge the emails from server permanently. oClient.Quit(); Console.WriteLine("Completed!"); } catch (Exception ep) { Console.WriteLine("Error: {0}", ep.Message); } }
// public void searchForValidTicket() //{ // //OpenPoP--- // //var client = new POPClient(); // //client.Connect("pop.gmail.com", 995, true); // //client.Authenticate("*****@*****.**", "YourPasswordHere"); // //var count = client.GetMessageCount(); // //Message message = client.GetMessage(count); // //Console.WriteLine(message.Headers.Subject); //} public static void getMail() { try { // Create a folder named "inbox" under current directory // to save the email retrieved. string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory()); // If the folder is not existed, create it. if (!Directory.Exists(localInbox)) { Directory.CreateDirectory(localInbox); } MailServer oServer = new MailServer("pop3.emailarchitect.net", "*****@*****.**", "testpassword", ServerProtocol.Pop3); // Enable SSL/TLS connection, most modern email server require SSL/TLS by default oServer.SSLConnection = true; oServer.Port = 995; // if your server doesn't support SSL/TLS, please use the following codes // oServer.SSLConnection = false; // oServer.Port = 110; MailClient oClient = new MailClient("TryIt"); oClient.Connect(oServer); MailInfo[] infos = oClient.GetMailInfos(); Console.WriteLine("Total {0} email(s)\r\n", infos.Length); for (int i = 0; i < infos.Length; i++) { MailInfo info = infos[i]; Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}", info.Index, info.Size, info.UIDL); // Receive email from POP3 server Mail oMail = oClient.GetMail(info); Console.WriteLine("From: {0}", oMail.From.ToString()); Console.WriteLine("Subject: {0}\r\n", oMail.Subject); // Generate an unqiue email file name based on date time. string fileName = _generateFileName(i + 1); string fullPath = string.Format("{0}\\{1}", localInbox, fileName); //oMail. // Save email to local disk oMail.SaveAs(fullPath, true); // Mark email as deleted from POP3 server. oClient.Delete(info); } // Quit and expunge emails marked as deleted from POP3 server. oClient.Quit(); Console.WriteLine("Completed!"); } catch (Exception ep) { Console.WriteLine(ep.Message); } }
public static string[] DownloadEmail(string pop3Server, string email, string password, bool needSSL) { string[] retString = new string[2]; // Create a folder named "inbox" under current directory // to save the email retrieved. string curpath = HttpContext.Current.Server.MapPath("~"); string mailbox = string.Format("{0}inbox", curpath); // If the folder is not existed, create it. if (!Directory.Exists(mailbox)) { Directory.CreateDirectory(mailbox); } MailServer mailServer = new MailServer(pop3Server, email, password, ServerProtocol.Pop3); MailClient mailClient = new MailClient("TryIt"); // If your POP3 server requires SSL connection, // Please add the following codes: if (needSSL) { mailServer.SSLConnection = true; mailServer.Port = 995; } try { mailClient.Connect(mailServer); MailInfo[] infos = mailClient.GetMailInfos(); for (int i = 0; i < infos.Length; i++) { MailInfo info = infos[i]; // Receive email from POP3 server Mail mail = mailClient.GetMail(info); // Generate an email file name based on date time. System.Globalization.CultureInfo cur = new System.Globalization.CultureInfo("it-IT"); string subject = mail.Subject; if (subject.Length > 70) { subject = subject.Substring(0, 70); } string fileName = string.Format("{0}\\{1}.eml", mailbox, subject); fileName = fileName.Replace("(Trial Version)", ""); // Save email to local disk mail.SaveAs(fileName.Trim(), true); // Mark email as deleted from POP3 server. mailClient.Delete(info); retString[0] = mailbox; retString[1] = subject.Replace("(Trial Version)", ""); } // Quit and purge emails marked as deleted from POP3 server. mailClient.Quit(); } catch (Exception ex) { Console.WriteLine(ex.Message); } return(retString); }
private void btnStart_Click(object sender, System.EventArgs e) { _enableSettingControls(false, false); if (!_tryOauth()) { _enableSettingControls(true, false); return; } if (ComboBoxAuthType.SelectedIndex == (int)ServerAuthType.AuthXOAUTH2) { textUser.Text = _oauthWrapper.OauthProvider.UserEmail; textPassword.Text = _oauthWrapper.OauthProvider.AccessToken; } if (!_validateInput()) { _enableSettingControls(true, false); return; } _enableSettingControls(false, true); // UIDL is the identifier of every email on POP3/IMAP4/Exchange server, to avoid retrieve // the same email from server more than once, we record the email UIDL retrieved every time // if you delete the email from server every time and not to leave a copy of email on // the server, then please remove all the function about uidl. // UIDLManager wraps the function to write/read uidl record from a text file. UIDLManager oUIDLManager = new UIDLManager(); bool _isUidlLoaded = false; try { // For evaluation usage, please use "TryIt" as the license code, otherwise the // "Invalid license code" exception will be thrown. However, the object will expire in 1-2 months, then // "Trial version expired" exception will be thrown. MailClient client = new MailClient("TryIt"); // Catching the following events is not necessary, // just make the application more user friendly. // If you use the object in asp.net/windows service or non-gui application, // You need not to catch the following events. // To learn more detail, please refer to the code in EAGetMail EventHandler region client.OnAuthorized += new MailClient.OnAuthorizedEventHandler(OnAuthorized); client.OnConnected += new MailClient.OnConnectedEventHandler(OnConnected); client.OnIdle += new MailClient.OnIdleEventHandler(OnIdle); client.OnSecuring += new MailClient.OnSecuringEventHandler(OnSecuring); client.OnReceivingDataStream += new MailClient.OnReceivingDataStreamEventHandler(OnReceivingDataStream); _isCancelOperation = false; textStatus.Text = "Connecting ..."; // generate a log file for debug // client.LogFileName = string.Format("{0}\\log.txt", _currentPath); MailServer server = _buildServer(); client.Connect(server); string localInbox = _createLocalInbox(); // load existed uidl records to UIDLManager string uidlfile = string.Format("{0}\\{1}", localInbox, _uidlFile); oUIDLManager.Load(uidlfile); _isUidlLoaded = true; _setMailRange(ref client); textStatus.Text = "Retrieveing email list ..."; MailInfo[] infos = client.GetMailInfos(); textStatus.Text = string.Format("Total {0} email(s)", infos.Length); if (ComboBoxDateRange.SelectedIndex == 0) { // Remove the local uidl that is not existed on the server, // we only synchronize it with uidl of all emails in current mail folder oUIDLManager.SyncUIDL(server, infos); oUIDLManager.Update(); } for (int i = 0; i < infos.Length; i++) { pgBar.Maximum = 100; pgBar.Minimum = 0; pgBar.Value = 0; textStatus.Text = string.Format("Checking {0}/{1}...", i + 1, infos.Length); MailInfo info = infos[i]; if (oUIDLManager.FindUIDL(server, info.UIDL) != null) { //this email has been downloaded before. continue; } textStatus.Text = string.Format("Retrieving {0}/{1}...", i + 1, infos.Length); Mail mail = client.GetMail(info); string fileName = _generateFileName(i + 1); string fullFileName = string.Format("{0}\\{1}", localInbox, fileName); mail.SaveAs(fullFileName, true); _addNewMailToListView(ref mail, fullFileName); mail.Clear(); LabelTotal.Text = string.Format("Total {0} email(s)", ListViewMail.Items.Count); // If retrieve only new emails, after we retrieved it, mark it as read, // With this feature, you don't have to UIDLManager to prevent duplicated emails. if (chkNewOnly.Checked && ComboBoxProtocol.SelectedIndex != (int)ServerProtocol.Pop3) { client.MarkAsRead(info, true); } if (chkLeaveCopy.Checked) { // Add the email uidl to uidl file to avoid we retrieve it next time. oUIDLManager.AddUIDL(server, info.UIDL, fileName); } else { textStatus.Text = string.Format("Deleting {0}...", i + 1); client.Delete(info); // Remove UIDL from local uidl file. oUIDLManager.RemoveUIDL(server, info.UIDL); } } // Delete method just mark the email as deleted, // Quit method expunge the emails from server exactly. client.Quit(); // Update the uidl list to local uidl file and then we can load it next time. oUIDLManager.Update(); textStatus.Text = "Completed"; } catch (Exception ep) { if (_isUidlLoaded) { // Update the uidl list to local uidl file and then we can load it next time. oUIDLManager.Update(); } MessageBox.Show(ep.Message); textStatus.Text = ep.Message; } _enableSettingControls(true, false); }
public static void RunProgram() { string curpath = String.Format("{0}", directory); string mailbox = String.Format("{0}\\Входящие", curpath); //Определяет надобность появления уведомления // Если директории не существует, создать ее if (!Directory.Exists(mailbox)) { Directory.CreateDirectory(mailbox); } MailServer oServer = new MailServer(String.Format("imap.{0}", site), String.Format("{0}", mailAdress), String.Format("{0}", mailPassword), ServerProtocol.Imap4); MailClient oClient = new MailClient(""); oClient.GetMailInfosParam.GetMailInfosOptions = GetMailInfosOptionType.NewOnly; FilterAssign(); oServer.SSLConnection = true; oServer.Port = 993; //while (true) //{ try { oClient.Connect(oServer); MailInfo[] infos = oClient.GetMailInfos(); for (int i = 0; i < infos.Length; i++) { MailInfo info = infos[i]; // Получение письма с POP3 сервера Mail oMail = oClient.GetMail(info); string from = oMail.From.ToString(); string temp = oMail.Subject; string subject = temp.Replace("(Trial Version)", ""); // Генерация файла письма на основе имени отправителя и даты System.DateTime d = System.DateTime.Now; System.Globalization.CultureInfo cur = new System.Globalization.CultureInfo("ru-RU"); string sdate = d.ToString("yyyyMMddHHmmss", cur); string syear = d.ToString("yyyy", cur); string smonth = d.ToString("MM", cur); string sday = d.ToString("dd", cur); string crtD = String.Format("{0}\\{1}\\{2}\\{3}\\{4}\\{5}", mailbox, syear, smonth, sday, RRS(oMail.From.Name.ToString()).Trim(), RRS(subject).Trim()); // Пометить письмо как прочитанное oClient.MarkAsRead(info, true); // Обработка вложений Attachment[] atts = oMail.Attachments; int count = atts.Length; bool danger = false; string dangerPath = String.Format("{0}\\Подозрительные лица", directory.ToString()); string dangerName = String.Format("{0}\\{1}.txt", dangerPath, RRS(oMail.From.Name.ToString())); for (int j = 0; j < count; j++) { Attachment att = atts[j]; string attname = String.Format("{0}\\{1}_{2}_{3}", crtD, RRS(oMail.From.Name.ToString()).Trim(), RRS(subject).Trim(), att.Name); for (int k = 0; k < filters.Count(); k++) { if (attname.Contains(filters[k])) { danger = true; //break; } } if (danger == true) { notification = true; if (!Directory.Exists(dangerPath)) { Directory.CreateDirectory(dangerPath); } System.IO.File.WriteAllText(dangerName, String.Format("Письмо, присланное c почтового адреса {0}, содержит потенциально вредоносные файлы", oMail.From.Address)); break; } else { if (!System.IO.Directory.Exists(crtD) && danger == false) { System.IO.Directory.CreateDirectory(crtD); } att.SaveAs(attname, true); } } if (danger == false) { Directory.CreateDirectory(crtD); string fileName = String.Format("{0}\\{1}_{2}_{3}_{4}.txt", crtD, RRS(oMail.From.Name.ToString()).Trim(), RRS(subject).Trim(), RRS(sdate).Trim(), i); //Исключение возможности попадания запрещенных символов в название файла System.IO.File.WriteAllText(fileName, oMail.TextBody); } // Сохранить письмо на диск //oMail.SaveAs(fileName, true); if (delete == true) { oClient.Delete(info); } } } catch (Exception ep) { } //Thread.Sleep(latency*1000); //} }