public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir_POP3(); string dstEmail = dataDir + "message.msg"; //Create an instance of the Pop3Client class Pop3Client client = new Pop3Client(); //Specify host, username and password for your client client.Host = "pop.gmail.com"; // Set username client.Username = "******"; // Set password client.Password = "******"; // Set the port to 995. This is the SSL port of POP3 server client.Port = 995; // Enable SSL client.SecurityOptions = SecurityOptions.Auto; try { int messageCount = client.GetMessageCount(); // Create an instance of the MailMessage class MailMessage msg; for (int i = 1; i <= messageCount; i++) { //Retrieve the message in a MailMessage class msg = client.FetchMessage(i); Console.WriteLine("From:" + msg.From.ToString()); Console.WriteLine("Subject:" + msg.Subject); Console.WriteLine(msg.HtmlBody); } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { client.Disconnect(); } Console.WriteLine(Environment.NewLine + "Retrieved email messages using POP3 "); }
public static void Run() { //ExStart:RetrievingEmailMessages // Create an instance of the Pop3Client class Pop3Client client = new Pop3Client(); // Specify host, username, password, Port and SecurityOptions for your client client.Host = "pop.gmail.com"; client.Username = "******"; client.Password = "******"; client.Port = 995; client.SecurityOptions = SecurityOptions.Auto; try { int messageCount = client.GetMessageCount(); // Create an instance of the MailMessage class and Retrieve message MailMessage message; for (int i = 1; i <= messageCount; i++) { message = client.FetchMessage(i); Console.WriteLine("From:" + message.From); Console.WriteLine("Subject:" + message.Subject); Console.WriteLine(message.HtmlBody); } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { client.Dispose(); } //ExEnd:RetrievingEmailMessages Console.WriteLine(Environment.NewLine + "Retrieved email messages using POP3 "); }
public void FetchBalanceMessage() { while (true) { int messageCount = 0; List <BalanceMessage> listBalanceMessage = new List <BalanceMessage>(); Pop3Client client = new Pop3Client(); try { client.Connect(hostname, port, useSsl); client.Authenticate(username, password); messageCount = client.GetMessageCount(); for (int i = 1; i <= messageCount; i++) { MessageHeader headers = client.GetMessageHeaders(i); RfcMailAddress from = headers.From; if (from.HasValidMailAddress && from.Address.Contains("*****@*****.**")) { DateTime date = Convert.ToDateTime(headers.Date); Message message = client.GetMessage(i); //MessagePart plainText = message.FindFirstPlainTextVersion(); BalanceMessage bMessage = new BalanceMessage(); bMessage.date = date; bMessage.text = message.MessagePart.GetBodyAsText(); Regex regex = new Regex(@"\d\.\d+"); MatchCollection matches = regex.Matches(bMessage.text); try { NumberFormatInfo provider = new NumberFormatInfo(); provider.NumberDecimalSeparator = "."; double amount = Convert.ToDouble(matches[0].Value, provider); bMessage.amount = amount; //Console.WriteLine(bMessage.date + " : " + bMessage.amount); listBalanceMessage.Add(bMessage); client.DeleteMessage(i); } catch (Exception ex) { //Console.WriteLine(ex.Message); if (_del != null) { _del(this.GetType().ToString() + " : " + System.Reflection.MethodBase.GetCurrentMethod().Name + ex.Message); } break; } } } client.Disconnect(); } catch (Exception ex) { //Console.WriteLine(ex.Message); if (_del != null) { _del(this.GetType().ToString() + " : " + System.Reflection.MethodBase.GetCurrentMethod().Name + ex.Message); } } client.Dispose(); SaveTxt(listBalanceMessage); Thread.Sleep(1000 * 60 * 60); } }
private void updateData() { suara[0] = 0; suara[1] = 0; suara[2] = 0; suara[3] = 0; suara[4] = 0; lblCalon[0] = lblCalon1; //lblCalon[1] = lblCalon2; lblCalon[2] = lblCalon3; //lblCalon[3] = lblCalon4; lblCalon[4] = lblCalon5; try { if (pop3Client.Connected) { pop3Client.Disconnect(); } pop3Client.Connect("pop.gmail.com", 995, true); pop3Client.Authenticate("*****@*****.**", passEMAIL); int count = pop3Client.GetMessageCount(); progressBar1.Maximum = count; int success = 0; int fail = 0; for (int i = count; i >= 1; i -= 1) { // Check if the form is closed while we are working. If so, abort if (IsDisposed) { return; } // Refresh the form while fetching emails // This will fix the "Application is not responding" problem Application.DoEvents(); try { Message message = pop3Client.GetMessage(i); String pesan; if (message.MessagePart.IsText) { pesan = message.MessagePart.GetBodyAsText(); } else { MessagePart plainTextPart = message.FindFirstPlainTextVersion(); if (plainTextPart != null) { pesan = plainTextPart.GetBodyAsText(); } else { // Try to find a body to show in some of the other text versions List <MessagePart> textVersions = message.FindAllTextVersions(); if (textVersions.Count >= 1) { pesan = textVersions[0].GetBodyAsText(); } else { pesan = "<<OpenPop>> Cannot find a text version body in this message to show <<OpenPop>>"; } } } if (message.Headers.Subject == "2SUARA KAHIM") { //MessageBox.Show("IBM"); String[] komponen = pesan.Split('|'); if (komponen.Count() == 4) { if (komponen[0] == "COMBODUO") { if (!kupon.Contains(komponen[2])) { int pilihan = 0; if (Int32.TryParse(komponen[3], out pilihan)) { kupon.Add(komponen[2]); textBox1.AppendText(komponen[2] + " " + komponen[3] + "\n"); suara[pilihan - 1] += 1; lblCalon[pilihan - 1].Text = suara[pilihan - 1].ToString(); chart1.Series.Clear(); chart1.Series.Add(""); chart1.Series[0].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Pie; chart1.Series[0].Points.Add(0); chart1.Series[0].Points.Add(0); chart1.Series[0].Points.Add(0); //chart1.Series[0].Points.Add(0); //chart1.Series[0].Points.Add(0); chart1.Series[0].Points[0].IsValueShownAsLabel = true; chart1.Series[0].Points[0].Label = "Joshua Belzalel A"; chart1.Series[0].Points[0].SetValueY(suara[0]); //chart1.Series[0].Points[1].IsValueShownAsLabel = true; //chart1.Series[0].Points[1].Label = "Farid Fadhil H"; //chart1.Series[0].Points[1].SetValueY(suara[1]); chart1.Series[0].Points[1].IsValueShownAsLabel = true; chart1.Series[0].Points[1].Label = "Aryya Dwisatya W"; chart1.Series[0].Points[1].SetValueY(suara[2]); //chart1.Series[0].Points[3].IsValueShownAsLabel = true; //chart1.Series[0].Points[3].Label = "Vidia Anindhita"; //chart1.Series[0].Points[3].SetValueY( suara[3] ); chart1.Series[0].Points[2].IsValueShownAsLabel = true; chart1.Series[0].Points[2].Label = "Abstain"; chart1.Series[0].Points[2].SetValueY(suara[4]); progressBar1.Value++; } } } } } //MessageBox.Show(message.Headers.Subject + "\n\n" + pesan); success++; } catch (Exception ex) { MessageBox.Show(ex.Message); DefaultLogger.Log.LogError( "TestForm: Message fetching failed: " + ex.Message + "\r\n" + "Stack trace:\r\n" + ex.StackTrace); fail++; } //progressBar.Value = (int)(((double)(count - i) / count) * 100); } //MessageBox.Show(this, "Mail received!\nSuccesses: " + success + "\nFailed: " + fail, "Message fetching done"); if (fail > 0) { //MessageBox.Show(this, ""); } } catch (InvalidLoginException) { MessageBox.Show(this, "The server did not accept the user credentials!", "POP3 Server Authentication"); } catch (PopServerNotFoundException) { MessageBox.Show(this, "The server could not be found", "POP3 Retrieval"); } catch (PopServerLockedException) { MessageBox.Show(this, "The mailbox is locked. It might be in use or under maintenance. Are you connected elsewhere?", "POP3 Account Locked"); } catch (LoginDelayException) { MessageBox.Show(this, "Login not allowed. Server enforces delay between logins. Have you connected recently?", "POP3 Account Login Delay"); } catch (Exception ex) { MessageBox.Show(this, "Error occurred retrieving mail. " + ex.Message, "POP3 Retrieval"); } progressBar1.Value = progressBar1.Maximum; MessageBox.Show("Selesai, selamat untuk yang menang :)", "", MessageBoxButtons.OK, MessageBoxIcon.Information); }
private string ReceiveMailsfromPOPServer(string passcode) { try { // Get message Unique ID from the database using the Passcode mapped. //SQL call DataSet ds = FileController.GETMessagesByPassCode(passcode); foreach (DataRow dr in ds.Tables[0].Rows) { if (dr["Active"].ToString().ToUpper() == "FALSE") { return("Invalid Passcode"); } } string messageID = ""; if (ds.Tables[0].Rows.Count > 0) { messageID = ds.Tables[0].Rows[0][1].ToString(); if (messageID != "") { if (pop3Client.Connected) { pop3Client.Disconnect(); } pop3Client.Connect(ConfigurationManager.AppSettings["Server"], int.Parse(ConfigurationManager.AppSettings["Port"]), Convert.ToBoolean(ConfigurationManager.AppSettings["SSL"])); pop3Client.Authenticate(ConfigurationManager.AppSettings["Login"], ConfigurationManager.AppSettings["Password"]); int count = pop3Client.GetMessageCount(); messages.Clear(); for (int i = count; i >= 1; i -= 1) { try { Message message = pop3Client.GetMessage(i); if (message.Headers.MessageId == messageID) { messages.Add(i, message); GetAttachmentsFromMessage(messages, i); FileController.UpdByPassCode(passcode); pop3Client.DeleteMessage(i); break; } } catch (Exception e) { MessageBox.Show("Exception occured while reading emails", "Information!", MessageBoxButton.OK, MessageBoxImage.Information); } } return("Attachments for the given passcode has been downloaded in the Standard path"); } else { return(""); } } else { return(""); } } catch (Exception e) { return(""); } }
public int GetMessageCount() { return(fClient.GetMessageCount()); }
/// <summary> /// 获取所有符合规则的daily report邮件 /// </summary> /// <param name="monthDate">月份参数(201708)</param> /// <returns></returns> public List <DailyReport> getAvailableMonthMail(string monthDate) { //MailPopService mps = new MailPopService("*****@*****.**", "Report1234", monthDate); Pop3Client client = new Pop3Client(); if (client.Connected) { client.Disconnect(); } //连接263服务器 client.Connect("pop3.263.net", 110, false); client.Authenticate("*****@*****.**", "Report1234"); //读取月份所有邮件信息 //var list = client.GetMessageInfos(); int count = client.GetMessageCount(); int index = 1; List <MailProperty> lmp = new List <MailProperty>(); for (int i = index; i < count + 1; i++) { if (i % 40 == 0) { Thread.Sleep(1000); } try { Message message = client.GetMessage(i); DateTime sendDate = DateTime.MinValue; if (DateTime.TryParse(message.Headers.Date.Replace("(CST)", ""), out sendDate)) { if (sendDate.ToString("yyyyMMdd").StartsWith(monthDate)) { MailProperty mp = new MailProperty(); mp.subject = message.Headers.Subject; mp.sender = message.Headers.From.Address; mp.sendDate = sendDate; lmp.Add(mp); } } } catch (Exception ex) { index = i; continue; //throw; } } //读取符合规则的daily report邮件 List <DailyReport> allReports = new List <DailyReport>(); foreach (var pro in lmp) { DailyReport report = new DailyReport(); if (GetMorningPlanRule(pro.subject)) { report.type = "morning"; string[] rlt = morningReg.Match(pro.subject).Groups[0].Value.Split('_'); if (rlt.Length != 3) { continue; throw new Exception("邮件标题不符合{XX_XXX_XX}的规则"); } report.chineseName = rlt[1]; report.sendDate = pro.sendDate; report.signIn = true; allReports.Add(report); continue; } if (GetNoonUpdateRule(pro.subject)) { report.type = "noon"; string[] rlt = noonReg.Match(pro.subject).Groups[0].Value.Split('_'); if (rlt.Length != 3) { continue; throw new Exception("邮件标题不符合{XX_XXX_XX}的规则"); } report.chineseName = rlt[1]; report.sendDate = pro.sendDate; report.signIn = true; allReports.Add(report); continue; } if (GetDailySummaryRule(pro.subject)) { report.type = "summary"; Match ss = summaryReg.Match(pro.subject); string[] rlt = summaryReg.Match(pro.subject).Groups[0].Value.Split('_'); if (rlt.Length != 3) { continue; throw new Exception("邮件标题不符合{XX_XXX_XX}的规则"); } report.chineseName = rlt[1]; report.sendDate = pro.sendDate; report.signIn = true; allReports.Add(report); continue; } } return(allReports); }
private void ReceiveMails() { connectButton.Enabled = false; progressBar.Value = 0; try { if (pop3Client.Connected) { pop3Client.Disconnect(); } pop3Client.Connect(popServerTextBox.Text, int.Parse(portTextBox.Text), useSslCheckBox.Checked); pop3Client.Authenticate(loginTextBox.Text, passwordTextBox.Text, AuthenticationMethod.UsernameAndPassword); int count = pop3Client.GetMessageCount(); totalMessagesTextBox.Text = count.ToString(); messageTextBox.Text = ""; messages.Clear(); listMessages.Nodes.Clear(); listAttachments.Nodes.Clear(); int s = 0; int f = 0; for (int i = count; i >= 1; i -= 1) { Application.DoEvents(); try { Message message = pop3Client.GetMessage(i); messages.Add(i, message); TreeNode node = new TreeNodeBuilder().VisitMessage(message); node.Tag = i; listMessages.Nodes.Add(node); s++; } catch (Exception e) { DefaultLogger.Log.LogError( "Retrieving Emails: Message fetching failed: " + e.Message); f++; } progressBar.Value = (int)(((double)(count - 1) / count) * 100); } MessageBox.Show(this, "Mail received! \n Succesfully: " + s + "\nFailed: " + f, "Messages Retrieved."); if (f > 0) { MessageBox.Show("Some messages were not parsed correctly"); } } catch (InvalidLoginException) { MessageBox.Show(this, "The server did not accept the username and password."); } catch (PopServerNotFoundException) { MessageBox.Show(this, "The server couldnt be found"); } catch (PopServerLockedException) { MessageBox.Show(this, "The mailbox is locked and seems to be in use."); } catch (LoginDelayException) { MessageBox.Show(this, "You tried to log in too quickly between two logins."); } catch (Exception e) { MessageBox.Show(this, "Error ocurred retrieveing mail " + e.Message); } finally { connectButton.Enabled = true; progressBar.Value = 100; } }
public void TestAuthenticationExceptions() { var commands = new List <Pop3ReplayCommand> (); commands.Add(new Pop3ReplayCommand("", "comcast.greeting.txt")); commands.Add(new Pop3ReplayCommand("CAPA\r\n", "comcast.capa1.txt")); commands.Add(new Pop3ReplayCommand("USER username\r\n", "comcast.ok.txt")); commands.Add(new Pop3ReplayCommand("PASS password\r\n", "comcast.err.txt")); commands.Add(new Pop3ReplayCommand("QUIT\r\n", "comcast.quit.txt")); using (var client = new Pop3Client()) { try { client.ReplayConnect("localhost", new Pop3ReplayStream(commands, false), CancellationToken.None); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue(client.IsConnected, "Client failed to connect."); Assert.AreEqual(ComcastCapa1, client.Capabilities); Assert.AreEqual(0, client.AuthenticationMechanisms.Count); Assert.AreEqual(31, client.ExpirePolicy); try { var credentials = new NetworkCredential("username", "password"); client.Authenticate(credentials, CancellationToken.None); Assert.Fail("Expected AuthenticationException"); } catch (AuthenticationException) { // we expect this exception... } catch (Exception ex) { Assert.Fail("Did not expect an exception in Authenticate: {0}", ex); } Assert.IsTrue(client.IsConnected, "AuthenticationException should not cause a disconnect."); try { var count = client.GetMessageCount(CancellationToken.None); Assert.Fail("Expected UnauthorizedAccessException"); } catch (UnauthorizedAccessException) { // we expect this exception... } catch (Exception ex) { Assert.Fail("Did not expect an exception in Count: {0}", ex); } Assert.IsTrue(client.IsConnected, "UnauthorizedAccessException should not cause a disconnect."); try { var sizes = client.GetMessageSizes(CancellationToken.None); Assert.Fail("Expected UnauthorizedAccessException"); } catch (UnauthorizedAccessException) { // we expect this exception... } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetMessageSizes: {0}", ex); } Assert.IsTrue(client.IsConnected, "UnauthorizedAccessException should not cause a disconnect."); try { var size = client.GetMessageSize("uid", CancellationToken.None); Assert.Fail("Expected UnauthorizedAccessException"); } catch (UnauthorizedAccessException) { // we expect this exception... } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetMessageSize(uid): {0}", ex); } Assert.IsTrue(client.IsConnected, "UnauthorizedAccessException should not cause a disconnect."); try { var size = client.GetMessageSize(0, CancellationToken.None); Assert.Fail("Expected UnauthorizedAccessException"); } catch (UnauthorizedAccessException) { // we expect this exception... } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetMessageSize(int): {0}", ex); } Assert.IsTrue(client.IsConnected, "UnauthorizedAccessException should not cause a disconnect."); try { var uids = client.GetMessageUids(CancellationToken.None); Assert.Fail("Expected UnauthorizedAccessException"); } catch (UnauthorizedAccessException) { // we expect this exception... } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetMessageUids: {0}", ex); } Assert.IsTrue(client.IsConnected, "UnauthorizedAccessException should not cause a disconnect."); try { var uid = client.GetMessageUid(0, CancellationToken.None); Assert.Fail("Expected UnauthorizedAccessException"); } catch (UnauthorizedAccessException) { // we expect this exception... } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetMessageUid: {0}", ex); } Assert.IsTrue(client.IsConnected, "UnauthorizedAccessException should not cause a disconnect."); try { var message = client.GetMessage("uid", CancellationToken.None); Assert.Fail("Expected UnauthorizedAccessException"); } catch (UnauthorizedAccessException) { // we expect this exception... } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetMessage(uid): {0}", ex); } Assert.IsTrue(client.IsConnected, "UnauthorizedAccessException should not cause a disconnect."); try { var message = client.GetMessage(0, CancellationToken.None); Assert.Fail("Expected UnauthorizedAccessException"); } catch (UnauthorizedAccessException) { // we expect this exception... } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetMessage(int): {0}", ex); } Assert.IsTrue(client.IsConnected, "UnauthorizedAccessException should not cause a disconnect."); try { client.DeleteMessage("uid", CancellationToken.None); Assert.Fail("Expected UnauthorizedAccessException"); } catch (UnauthorizedAccessException) { // we expect this exception... } catch (Exception ex) { Assert.Fail("Did not expect an exception in DeleteMessage(uid): {0}", ex); } Assert.IsTrue(client.IsConnected, "UnauthorizedAccessException should not cause a disconnect."); try { client.DeleteMessage(0, CancellationToken.None); Assert.Fail("Expected UnauthorizedAccessException"); } catch (UnauthorizedAccessException) { // we expect this exception... } catch (Exception ex) { Assert.Fail("Did not expect an exception in DeleteMessage(int): {0}", ex); } Assert.IsTrue(client.IsConnected, "UnauthorizedAccessException should not cause a disconnect."); try { client.Disconnect(true, CancellationToken.None); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse(client.IsConnected, "Failed to disconnect"); } }
/// <summary> /// Пересылка с почты oit на пользователей Lotus /// </summary> /// <param name="parameters"></param> public void StartMessageOit(ConfigFile.ConfigFile parameters) { try { int count = 0; ZipAttachments zip = new ZipAttachments(); using (Pop3Client client = new Pop3Client()) { client.CheckCertificateRevocation = false; client.Connect(parameters.Pop3Address, 995, true); MailSender mail = new MailSender(); Loggers.Log4NetLogger.Info(new Exception($"Соединение с сервером eups.tax.nalog.ru установлено (OIT)")); client.Authenticate(parameters.LoginOit, parameters.PasswordOit); Loggers.Log4NetLogger.Info(new Exception($"Пользователь проверен (OIT)")); if (client.IsConnected) { MailLogicLotus mailSave = new MailLogicLotus(); SelectSql select = new SelectSql(); UserLotus userSqlDefault = select.FindUserGroup(7); int messageCount = client.GetMessageCount(); for (int i = 0; i < messageCount; i++) { MimeMessage message = client.GetMessage(i); var messageAttaches = message.Attachments as List <MimeEntity> ?? new List <MimeEntity>(); var messageBodyAttaches = new List <MimeEntity>(); messageBodyAttaches.AddRange(message.BodyParts); var calendar = messageBodyAttaches.Where(x => x.ContentType.MimeType == "text/calendar").ToList(); var file = messageBodyAttaches.Where(x => x.ContentType.MediaType == "image" || x.ContentType.MediaType == "application").ToList(); if (file.Count > 0) { messageAttaches.AddRange(file); } string body; var isHtmlMime = false; if (string.IsNullOrWhiteSpace(message.TextBody)) { body = message.HtmlBody; isHtmlMime = true; } else { body = message.TextBody; } var date = message.Date; if (date.Date >= DateTime.Now.Date) { if (!mailSave.IsExistsBdMail(message.MessageId)) { if (calendar.Count > 0) { var calendarVks = new CalendarVks(); body = calendarVks.CalendarParser(calendar, message); } var address = (MailboxAddress)message.From[0]; var mailSender = address.Address; var nameFile = date.ToString("dd.MM.yyyy_HH.mm.ss") + "_" + mailSender.Split('@')[0] + ".zip"; var fullPath = Path.Combine(parameters.PathSaveArchive, nameFile); MailLotusOutlookIn mailMessage = new MailLotusOutlookIn() { IdMail = message.MessageId, MailAdressSend = parameters.LoginOit, SubjectMail = message.Subject, Body = body, MailAdress = mailSender, DateInputServer = date.DateTime, NameFile = nameFile, FullPathFile = fullPath, FileMail = zip.StartZipArchive(messageAttaches, fullPath) }; mailSave.AddModelMailIn(mailMessage); var mailUsers = mail.FindUserLotusMail(select.FindUserOnUserGroup(userSqlDefault, mailMessage.SubjectMail), "(OIT)"); if (!string.IsNullOrWhiteSpace(message.HtmlBody)) { var math = Regex.Match(body, @"CN=(.+)МНС"); if (!string.IsNullOrWhiteSpace(math.Value)) { mailUsers.Add(math.Value); } } if (isHtmlMime) { mail.SendMailMimeHtml(mailMessage, mailUsers); } else { mail.SendMailIn(mailMessage, mailUsers); } count++; Loggers.Log4NetLogger.Info(new Exception($"УН: {mailMessage.IdMail} Дата/Время: {date} От кого: {mailMessage.MailAdress}")); } } else { //Удаление сообщения/письма client.DeleteMessage(i); } } mailSave.Dispose(); Loggers.Log4NetLogger.Info(new Exception("Количество пришедшей (OIT) почты:" + count)); } mail.Dispose(); client.Disconnect(true); } //Очистить временную папку с файлами zip.DropAllFileToPath(parameters.PathSaveArchive); foreach (FileInfo file in new DirectoryInfo(parameters.PathSaveArchive).GetFiles()) { Loggers.Log4NetLogger.Info(new Exception($"Наименование удаленных файлов: {file.FullName}")); file.Delete(); } Loggers.Log4NetLogger.Info(new Exception("Очистили папку от файлов (OIT)!")); Loggers.Log4NetLogger.Info(new Exception("Перерыв 5 минут (OIT)")); } catch (Exception x) { Loggers.Log4NetLogger.Debug(x); } }
// pegar as mensaguens public List <Email> GetMensagens() { // The client disconnects from the server when being disposed using (Pop3Client client = new Pop3Client()) { // Connect to the server client.Connect(hostname, port, useSsl); // Authenticate ourselves towards the server client.Authenticate(username, password); // Get the number of messages in the inbox int messageCount = client.GetMessageCount(); // We want to download all messages List <Message> allMessages = new List <Message>(messageCount); List <Email> ListEmails = new List <Email>(); // Messages are numbered in the interval: [1, messageCount] // Ergo: message numbers are 1-based. // Most servers give the latest message the highest number // adicionando mensagens na classe allMessages for (int i = messageCount; i > 0; i--) { allMessages.Add(client.GetMessage(i)); } // Numero da mensagem server para identificar a mensagem que sera apagada. // verificando se tem emails foreach (var message in allMessages) { List <Anexo> anexos = new List <Anexo>(); var popText = message.FindFirstPlainTextVersion(); var popHtml = message.FindFirstHtmlVersion(); string mailText = string.Empty; string mailHtml = string.Empty; if (popText != null) { mailText = popText.GetBodyAsText(); } if (popHtml != null) { mailHtml = popHtml.GetBodyAsText(); } // verificando se possue anexos e adicionando na classe ANEXO if (message.MessagePart.MessageParts[1].IsAttachment == true) { foreach (MessagePart attachment in message.FindAllAttachments()) { anexos.Add(new Anexo { FileByte = attachment.Body, FileName = attachment.FileName, FileType = attachment.ContentType.MediaType }); } } //adicionando os emails na classe desiginada ListEmails.Add(new Email() { Id = message.Headers.MessageId, Assunto = message.Headers.Subject, De = message.Headers.From.Address, Para = string.Join("; ", message.Headers.To.Select(to => to.Address)), Data = message.Headers.DateSent, ConteudoTexto = mailText, ConteudoHtml = !string.IsNullOrWhiteSpace(mailHtml) ? mailHtml : mailText, Anexos = anexos }); //apagar mensagens por id //if (message.Headers.Subject == "teste 6") //{ // var teste = DeleteMessageByMessageId(message.Headers.MessageId); //} } return(ListEmails); } }
/// <summary> /// Example showing: /// - how to fetch all messages from a POP3 server /// </summary> /// <param name="hostname">Hostname of the server. For example: pop3.live.com</param> /// <param name="port">Host port to connect to. Normally: 110 for plain POP3, 995 for SSL POP3</param> /// <param name="useSsl">Whether or not to use SSL to connect to server</param> /// <param name="username">Username of the user on the server</param> /// <param name="password">Password of the user on the server</param> /// <returns>All Messages on the POP3 server</returns> public static List <Message> FetchAllMessages(string hostname, int port, bool useSsl, string username, string password) { bool ConOk = false; bool AuthOk = false; // The client disconnects from the server when being disposed using (Pop3Client client = new Pop3Client()) { // Connect to the server client.Connect(hostname, port, useSsl, 500, 500, certificateValidator); ConOk = true; try { // Authenticate ourselves towards the server client.Authenticate(username, password); AuthOk = true; } catch (Exception e) { //Console.WriteLine("ERROR : " + username + " : Auth not successfull", e.Message); DefaultLogger.Log.LogError("ERROR : " + username + " : Auth not successfull : " + e.Message); } if (ConOk & AuthOk) { // Get the number of messages in the inbox int messageCount = client.GetMessageCount(); // We want to download all messages List <Message> allMessages = new List <Message>(messageCount); // Messages are numbered in the interval: [1, messageCount] // Ergo: message numbers are 1-based. // Most servers give the latest message the highest number for (int i = messageCount; i > 0; i--) { // allMessages.Add(client.GetMessage(i)); Message m = client.GetMessage(i); String filename = "mail_" + m.Headers.MessageId + ".eml"; FileInfo file = new FileInfo(System.Environment.CurrentDirectory + @"\INBOUND\" + filename); // Save the full message to some file try { m.Save(file); client.DeleteMessage(i); } catch (Exception e) { DefaultLogger.Log.LogError("Error writing mail to file : " + e.Message); } } // Now return the fetched messages return(allMessages); } else { DefaultLogger.Log.LogError("ERROR : " + username + "No connection or not authenticated..."); //Console.WriteLine("ERROR: no connection or not authenticated..."); return(null); } } }
public void LoginForm_LoginWithWrongPassword() { using (IWebDriver driver = new FirefoxDriver()) { driver.Navigate().GoToUrl(gg); //Открытие формы IWebElement formLink = driver.FindElement(By.XPath(@"//*[@id=""top_back""]/div[3]/a[1]")); formLink.Click(); WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5)); IWebElement overlay = driver.FindElement(By.Id("cboxOverlay")); IWebElement colorbox = driver.FindElement(By.Id("colorbox")); IWebElement messageBox = driver.FindElement(By.ClassName("status-error")); IWebElement loginButton = wait.Until(ExpectedConditions.ElementToBeClickable(By.XPath(@"//*[@id=""authblock""]/div[2]/form/div[7]/button"))); IWebElement emailField = wait.Until(ExpectedConditions.ElementToBeClickable(By.Name("Email"))); IWebElement passwordField = wait.Until(ExpectedConditions.ElementToBeClickable(By.Name("Password"))); Assert.IsTrue(colorbox.Displayed, "Форма не открылась"); //Ввод реквизитов emailField.SendKeys(validEmail); passwordField.SendKeys(wrongPassword); loginButton.Click(); try { wait.Until(ExpectedConditions.TextToBePresentInElement(messageBox, "Неправильный пароль.")); } catch (Exception e) { Assert.Fail("Не появилось сообщение об ошибке"); }; Assert.IsTrue(colorbox.Displayed, "Форма закрылась"); Assert.IsTrue(overlay.Displayed, "Оверлей пропал"); //Восстановление пароля; IWebElement restorePasswordLink = wait.Until(ExpectedConditions.ElementToBeClickable(By.XPath(@"//*[@id=""authblock""]/div[2]/form/div[2]/a"))); restorePasswordLink.Click(); try { wait.Until(ExpectedConditions.TextToBePresentInElementLocated(By.ClassName("status-message"), "Инструкция по восстановлению отправлена")); } catch (Exception e) { Assert.Fail("Не появилось сообщение об отправке письма"); }; } using (Pop3Client client = new Pop3Client()) { client.Connect(hostname, port, useSsl); client.Authenticate(validEmail, emailPass); int messageNumber = client.GetMessageCount(); int i = 0; while (messageNumber == 0 && i < 60) { client.Disconnect(); System.Threading.Thread.Sleep(5000); client.Connect(hostname, port, useSsl); client.Authenticate(validEmail, emailPass); messageNumber = client.GetMessageCount(); i = i++; } Assert.IsTrue(messageNumber > 0, "Письмо не пришло"); MessageHeader headers = client.GetMessageHeaders(messageNumber); RfcMailAddress from = headers.From; string subject = headers.Subject; client.DeleteAllMessages(); Assert.IsFalse(from.HasValidMailAddress && from.Address.Equals("*****@*****.**") && "Восстановление пароля на Gama - Gama".Equals(subject), "Письмо не пришло"); } }
public override TaskStatus Run() { Info("Receiving mails..."); bool success = true; bool atLeastOneSucceed = false; try { switch (Protocol) { case Protocol.Imap: using (var client = new ImapClient()) { client.Connect(Host, Port, EnableSsl); client.Authenticate(User, Password); client.Inbox.Open(FolderAccess.ReadOnly); var uids = client.Inbox.Search(SearchQuery.All); var count = uids.Count(); for (int i = Math.Min(MessageCount, count); i > 0; i--) { var message = client.Inbox.GetMessage(uids[i]); string messageFileName = "message_" + i + "_" + string.Format("{0:yyyy-MM-dd-HH-mm-ss-fff}", message.Date); string messagePath = Path.Combine(Workflow.WorkflowTempFolder, messageFileName + ".eml"); message.WriteTo(messagePath); Files.Add(new FileInf(messagePath, Id)); InfoFormat("Message {0} received. Path: {1}", i, messagePath); // save attachments var j = 0; var attachments = message.Attachments.ToList(); foreach (var attachment in attachments) { if (attachment.IsAttachment) { string attachmentPath = Path.Combine(Workflow.WorkflowTempFolder, messageFileName + "_" + (attachment is MessagePart ? ++j + ".eml" : ((MimePart)attachment).FileName)); if (attachment is MessagePart) { ((MessagePart)attachment).WriteTo(attachmentPath); } else { using (var stream = File.Create(attachmentPath)) { ((MimePart)attachment).Content.DecodeTo(stream); } } Files.Add(new FileInf(attachmentPath, Id)); InfoFormat("Attachment {0} of mail {1} received. Path: {2}", (attachment is MessagePart ? j + ".eml" : ((MimePart)attachment).FileName), i, attachmentPath); } } if (!atLeastOneSucceed) { atLeastOneSucceed = true; } } client.Disconnect(true); } break; case Protocol.Pop3: using (var client = new Pop3Client()) { client.Connect(Host, Port, EnableSsl); client.AuthenticationMechanisms.Remove("XOAUTH2"); client.Authenticate(User, Password); var count = client.GetMessageCount(); // We want to download messages // Messages are numbered in the interval: [1, messageCount] // Ergo: message numbers are 1-based. // Most servers give the latest message the highest number for (int i = Math.Min(MessageCount, count); i > 0; i--) { var message = client.GetMessage(i); string messageFileName = "message_" + i + "_" + string.Format("{0:yyyy-MM-dd-HH-mm-ss-fff}", message.Date); string messagePath = Path.Combine(Workflow.WorkflowTempFolder, messageFileName + ".eml"); message.WriteTo(messagePath); Files.Add(new FileInf(messagePath, Id)); InfoFormat("Message {0} received. Path: {1}", i, messagePath); // save attachments var attachments = message.Attachments.ToList(); foreach (var attachment in attachments) { if (attachment.IsAttachment) { string attachmentPath = Path.Combine(Workflow.WorkflowTempFolder, messageFileName + "_" + attachment.ContentId); attachment.WriteTo(attachmentPath); Files.Add(new FileInf(attachmentPath, Id)); InfoFormat("Attachment {0} of mail {1} received. Path: {2}", attachment.ContentId, i, attachmentPath); } } if (DeleteMessages) { client.DeleteMessage(i); } if (!atLeastOneSucceed) { atLeastOneSucceed = true; } } client.Disconnect(true); } break; } } catch (ThreadAbortException) { throw; } catch (Exception e) { ErrorFormat("An error occured while receiving mails.", e); success = false; } var status = Status.Success; if (!success && atLeastOneSucceed) { status = Status.Warning; } else if (!success) { status = Status.Error; } Info("Task finished."); return(new TaskStatus(status, false)); }
public List <EmailMessage> LerEmail(ConfiguracaoContasEmails configuracaoContaEmail, Container container, IEmailServico emailServico, IConfiguracaoServico configuracaoServico, IAtividadeServico atividadeServico, IFilaServico filaServico, List <EmailRemetenteRegra> emailsSpamFila, List <Email> uIdsExistentes, string diretorioArquivos) { var dirLog = ConfigurationManager.AppSettings["DiretorioLog"]; using (var emailClient = new Pop3Client()) { emailClient.Connect(_hostname, _port, _useSsl); emailClient.AuthenticationMechanisms.Remove("XOAUTH2"); emailClient.Authenticate(_username, _password); var emails = new List <EmailMessage>(); var messageCount = emailClient.GetMessageCount(); var contador = 0; for (int i = messageCount; i > 0; i--) { if (contador > 150) { break; } contador++; var message = emailClient.GetMessage(i - 1); if (message.Date.DateTime < DateTime.Now.AddDays(-10)) { continue; } if (message.Date.DateTime > DateTime.Now.AddHours(-3)) { continue; } //var emailExistente = // uIdsExistentes.Find( // p => // p.MessageId == message.MessageId.Replace("<", "").Replace(">", "")); // // && p.CriadoEm == message.Date.DateTime); //if (emailExistente != null) continue; if (message.MessageId.Replace("<", "").Replace(">", "") == "[email protected]") { var emailRetornado = uIdsExistentes.FirstOrDefault(x => x.MessageId.Replace("<", "").Replace(">", "") == message.MessageId.Replace("<", "").Replace(">", "")); try { var processar = new ProcessamentoEmail2(configuracaoContaEmail, message, null, emailServico, diretorioArquivos, atividadeServico, emailServico, emailsSpamFila); var retorno = processar.ProcessarEmail(); } catch (Exception ex) { continue; } } //var emailMessage = new EmailMessage //{ // Content = !string.IsNullOrEmpty(message.HtmlBody) ? message.HtmlBody : message.TextBody, // Subject = message.Subject //}; //emailMessage.ToAddresses.AddRange(message.To.Select(x => (MailboxAddress)x) // .Select(x => new EmailAddress { Address = x.Address, Name = x.Name })); //emailMessage.FromAddresses.AddRange(message.From.Select(x => (MailboxAddress)x) // .Select(x => new EmailAddress { Address = x.Address, Name = x.Name })); //emails.Add(emailMessage); } return(emails); } }
//private SaveFileDialog saveFile; private void ReceiveMails() { // Disable buttons while working //connectAndRetrieveButton.Enabled = false; //uidlButton.Enabled = false; //progressBar.Value = 0; try { if (pop3Client.Connected) { pop3Client.Disconnect(); } pop3Client.Connect(Con.Pop, int.Parse(Con.Portpop), true); pop3Client.Authenticate(Con.Mail, Con.password); int count = pop3Client.GetMessageCount(); //totalMessagesTextBox.Text = count.ToString(); //messageTextBox.Text = ""; messages.Clear(); treeView1.Nodes.Clear(); // listAttachments.Nodes.Clear(); int success = 0; int fail = 0; for (int i = count; i >= 1; i -= 1) { // Check if the form is closed while we are working. If so, abort if (IsDisposed) { return; } // Refresh the form while fetching emails // This will fix the "Application is not responding" problem Application.DoEvents(); try { Message message = pop3Client.GetMessage(i); // Add the message to the dictionary from the messageNumber to the Message messages.Add(i, message); // Create a TreeNode tree that mimics the Message hierarchy TreeNode node = new OpenPop.TestApplication.TreeNodeBuilder().VisitMessage(message); // Set the Tag property to the messageNumber // We can use this to find the Message again later node.Tag = i; // Show the built node in our list of messages treeView1.Nodes.Add(node); success++; } catch (Exception e) { DefaultLogger.Log.LogError( "TestForm: Message fetching failed: " + e.Message + "\r\n" + "Stack trace:\r\n" + e.StackTrace); fail++; } //progressBar.Value = (int)(((double)(count - i) / count) * 100); } MessageBox.Show(this, "Почта получена!\nУспешно: " + success + "\nПровалено: " + fail, "Загрузка Сообщений завершена"); } catch (InvalidLoginException) { MessageBox.Show(this, "The server did not accept the user credentials!", "POP3 Server Authentication"); } catch (PopServerNotFoundException) { MessageBox.Show(this, "The server could not be found", "POP3 Retrieval"); } catch (PopServerLockedException) { MessageBox.Show(this, "The mailbox is locked. It might be in use or under maintenance. Are you connected elsewhere?", "POP3 Account Locked"); } catch (LoginDelayException) { MessageBox.Show(this, "Login not allowed. Server enforces delay between logins. Have you connected recently?", "POP3 Account Login Delay"); } catch (Exception e) { MessageBox.Show(this, "Error occurred retrieving mail. " + e.Message, "POP3 Retrieval"); } }
public LerCaixaResult LerCaixaDeEntrada() { var result = new LerCaixaResult(); try { using (Pop3Client client = new Pop3Client()) { client.Connect(ServidorEmailPop3, Porta, UsarSSL); client.Authenticate(Usuario, Senha); List <Message> mensagens = new List <Message>(); for (int i = client.GetMessageCount(); i > 0; i--) { mensagens.Add(client.GetMessage(i)); } result.Emails = new List <Email>(); foreach (Message mensagem in mensagens) { var destinatarios = new List <string>(); var copia = new List <string>(); foreach (var dest in mensagem.Headers.To) { destinatarios.Add(dest.Address); } foreach (var cc in mensagem.Headers.Cc) { copia.Add(cc.Address); } string body = null; MessagePart mpText = mensagem.FindFirstPlainTextVersion(); MessagePart mpHtml = mensagem.FindFirstHtmlVersion(); if (mpText != null) { body = mpText.GetBodyAsText(); } else if (mpHtml != null) { body = mpHtml.GetBodyAsText(); } result.Emails.Add(new Email() { Data = mensagem.Headers.Date, Remetente = mensagem.Headers.From.Address, Para = destinatarios, CC = copia, Assunto = mensagem.Headers.Subject, Corpo = body }); } } result.ProcessOk = true; } catch (Exception ex) { result.ProcessOk = false; result.MsgCatch = ex.Message; } return(result); }
public void TestExchangePop3Client() { var commands = new List <Pop3ReplayCommand> (); commands.Add(new Pop3ReplayCommand("", "exchange.greeting.txt")); commands.Add(new Pop3ReplayCommand("CAPA\r\n", "exchange.capa.txt")); commands.Add(new Pop3ReplayCommand("AUTH PLAIN\r\n", "exchange.plus.txt")); commands.Add(new Pop3ReplayCommand("AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "exchange.auth.txt")); commands.Add(new Pop3ReplayCommand("CAPA\r\n", "exchange.capa.txt")); commands.Add(new Pop3ReplayCommand("STAT\r\n", "exchange.stat.txt")); commands.Add(new Pop3ReplayCommand("UIDL\r\n", "exchange.uidl.txt")); commands.Add(new Pop3ReplayCommand("RETR 1\r\n", "exchange.retr1.txt")); commands.Add(new Pop3ReplayCommand("QUIT\r\n", "exchange.quit.txt")); using (var client = new Pop3Client()) { try { client.ReplayConnect("localhost", new Pop3ReplayStream(commands, false), CancellationToken.None); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue(client.IsConnected, "Client failed to connect."); Assert.AreEqual(ExchangeCapa, client.Capabilities); Assert.AreEqual(3, client.AuthenticationMechanisms.Count); Assert.IsTrue(client.AuthenticationMechanisms.Contains("GSSAPI"), "Expected SASL GSSAPI auth mechanism"); Assert.IsTrue(client.AuthenticationMechanisms.Contains("NTLM"), "Expected SASL NTLM auth mechanism"); Assert.IsTrue(client.AuthenticationMechanisms.Contains("PLAIN"), "Expected SASL PLAIN auth mechanism"); try { var credentials = new NetworkCredential("username", "password"); client.Authenticate(credentials, CancellationToken.None); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Authenticate: {0}", ex); } Assert.AreEqual(ExchangeCapa, client.Capabilities); Assert.AreEqual(3, client.AuthenticationMechanisms.Count); Assert.IsTrue(client.AuthenticationMechanisms.Contains("GSSAPI"), "Expected SASL GSSAPI auth mechanism"); Assert.IsTrue(client.AuthenticationMechanisms.Contains("NTLM"), "Expected SASL NTLM auth mechanism"); Assert.IsTrue(client.AuthenticationMechanisms.Contains("PLAIN"), "Expected SASL PLAIN auth mechanism"); try { var count = client.GetMessageCount(CancellationToken.None); Assert.AreEqual(7, count, "Expected 7 messages"); } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetMessageCount: {0}", ex); } try { var uids = client.GetMessageUids(CancellationToken.None); Assert.AreEqual(7, uids.Length, "Expected 7 uids"); } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetMessageUids: {0}", ex); } try { var message = client.GetMessage(0, CancellationToken.None); // TODO: assert that the message is byte-identical to what we expect } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetMessage: {0}", ex); } try { client.Disconnect(true, CancellationToken.None); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse(client.IsConnected, "Failed to disconnect"); } }
public void ReadMail() { try { Pop3Client pop3Client; pop3Client = new Pop3Client(); pop3Client.Connect(emailaccount.POP3, Convert.ToInt32(emailaccount.POP3port), emailaccount.IsSecured); pop3Client.Authenticate(emailaccount.emailid, emailaccount.password); // int MessageNum; int count = pop3Client.GetMessageCount(); var Emails = new List <POPEmail>(); int counter = 0; for (int i = count; i >= 1; i--) { OpenPop.Mime.Message message = pop3Client.GetMessage(i); POPEmail email = new POPEmail() { // MessageNumber = i, MessageNumber = message.Headers.MessageId, // message.Headers.Received. //MessageNum=MessageNumber, Subject = message.Headers.Subject, DateSent = message.Headers.DateSent, From = message.Headers.From.Address, //From = string.Format("<a href = 'mailto:{1}'>{0}</a>", message.Headers.From.DisplayName, message.Headers.From.Address), }; MessagePart body = message.FindFirstHtmlVersion(); if (body != null) { email.Body = body.GetBodyAsText(); } else { body = message.FindFirstPlainTextVersion(); if (body != null) { email.Body = body.GetBodyAsText(); } } List <MessagePart> attachments = message.FindAllAttachments(); foreach (MessagePart attachment in attachments) { email.Attachments.Add(new Attachment { FileName = attachment.FileName, ContentType = attachment.ContentType.MediaType, Content = attachment.Body }); } InsertEmailMessages(email.MessageNumber, email.Subject, email.DateSent, email.From, email.Body); Emails.Add(email); counter++; //if (counter > 2) //{ // break; //} } var emails = Emails; } catch (Exception ex) { // continue; throw ex; } }
public void TestBasicPop3Client() { var commands = new List <Pop3ReplayCommand> (); commands.Add(new Pop3ReplayCommand("", "comcast.greeting.txt")); commands.Add(new Pop3ReplayCommand("CAPA\r\n", "comcast.capa1.txt")); commands.Add(new Pop3ReplayCommand("USER username\r\n", "comcast.ok.txt")); commands.Add(new Pop3ReplayCommand("PASS password\r\n", "comcast.ok.txt")); commands.Add(new Pop3ReplayCommand("CAPA\r\n", "comcast.capa2.txt")); commands.Add(new Pop3ReplayCommand("STAT\r\n", "comcast.stat1.txt")); commands.Add(new Pop3ReplayCommand("RETR 1\r\n", "comcast.retr1.txt")); commands.Add(new Pop3ReplayCommand("QUIT\r\n", "comcast.quit.txt")); using (var client = new Pop3Client()) { try { client.ReplayConnect("localhost", new Pop3ReplayStream(commands, false), CancellationToken.None); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue(client.IsConnected, "Client failed to connect."); Assert.AreEqual(ComcastCapa1, client.Capabilities); Assert.AreEqual(0, client.AuthenticationMechanisms.Count); Assert.AreEqual(31, client.ExpirePolicy); try { var credentials = new NetworkCredential("username", "password"); client.Authenticate(credentials, CancellationToken.None); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Authenticate: {0}", ex); } Assert.AreEqual(ComcastCapa2, client.Capabilities); Assert.AreEqual("ZimbraInc", client.Implementation); Assert.AreEqual(2, client.AuthenticationMechanisms.Count); Assert.IsTrue(client.AuthenticationMechanisms.Contains("PLAIN"), "Expected SASL PLAIN auth mechanism"); Assert.IsTrue(client.AuthenticationMechanisms.Contains("X-ZIMBRA"), "Expected SASL X-ZIMBRA auth mechanism"); Assert.AreEqual(-1, client.ExpirePolicy); try { var count = client.GetMessageCount(CancellationToken.None); Assert.AreEqual(1, count, "Expected 1 message"); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Count: {0}", ex); } try { var message = client.GetMessage(0, CancellationToken.None); // TODO: assert that the message is byte-identical to what we expect } catch (Exception ex) { Assert.Fail("Did not expect an exception in GetMessage: {0}", ex); } try { client.Disconnect(true, CancellationToken.None); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse(client.IsConnected, "Failed to disconnect"); } }
private void ReceiveMails() { // Disable buttons while working connectAndRetrieveButton.Enabled = false; uidlButton.Enabled = false; progressBar.Value = 0; try { if (pop3Client.Connected) { pop3Client.Disconnect(); } pop3Client.Connect(popServerTextBox.Text, int.Parse(portTextBox.Text), useSslCheckBox.Checked); pop3Client.Authenticate(loginTextBox.Text, passwordTextBox.Text); int count = pop3Client.GetMessageCount(); totalMessagesTextBox.Text = count.ToString(); messageTextBox.Text = ""; messages.Clear(); listMessages.Nodes.Clear(); listAttachments.Nodes.Clear(); int success = 0; int fail = 0; for (int i = count; i >= 1; i -= 1) { // Check if the form is closed while we are working. If so, abort if (IsDisposed) { return; } // Refresh the form while fetching emails // This will fix the "Application is not responding" problem Application.DoEvents(); try { Message message = pop3Client.GetMessage(i); // Add the message to the dictionary from the messageNumber to the Message messages.Add(i, message); // Create a TreeNode tree that mimics the Message hierarchy TreeNode node = new TreeNodeBuilder().VisitMessage(message); // Set the Tag property to the messageNumber // We can use this to find the Message again later node.Tag = i; // Show the built node in our list of messages listMessages.Nodes.Add(node); success++; } catch (Exception e) { DefaultLogger.Log.LogError( "TestForm: Message fetching failed: " + e.Message + "\r\n" + "Stack trace:\r\n" + e.StackTrace); fail++; } progressBar.Value = (int)(((double)(count - i) / count) * 100); } MessageBox.Show(this, "Mail received!\nSuccesses: " + success + "\nFailed: " + fail, "Message fetching done"); if (fail > 0) { MessageBox.Show(this, "Since some of the emails were not parsed correctly (exceptions were thrown)\r\n" + "please consider sending your log file to the developer for fixing.\r\n" + "If you are able to include any extra information, please do so.", "Help improve OpenPop!"); } } catch (InvalidLoginException) { MessageBox.Show(this, "The server did not accept the user credentials!", "POP3 Server Authentication"); } catch (PopServerNotFoundException) { MessageBox.Show(this, "The server could not be found", "POP3 Retrieval"); } catch (PopServerLockedException) { MessageBox.Show(this, "The mailbox is locked. It might be in use or under maintenance. Are you connected elsewhere?", "POP3 Account Locked"); } catch (LoginDelayException) { MessageBox.Show(this, "Login not allowed. Server enforces delay between logins. Have you connected recently?", "POP3 Account Login Delay"); } catch (Exception e) { MessageBox.Show(this, "Error occurred retrieving mail. " + e.Message, "POP3 Retrieval"); } finally { // Enable the buttons again connectAndRetrieveButton.Enabled = true; uidlButton.Enabled = true; progressBar.Value = 100; } }
//private void DepartSent_SMS() //{ // DataTable dtDepartmentSMSSent = new DataTable(); // dtDepartmentSMSSent = DataAccessManager.GetSMSSent( Convert.ToString(Session["DeptID"]), Convert.ToInt32(Session["CampusID"])); // Session["dtDepartmentSMSSent"] = dtDepartmentSMSSent; // rgvDepartmentSent.DataSource = (DataTable)Session["dtDepartmentSMSSent"]; //} //protected void rgvDepartmentSent_SortCommand(object sender, GridSortCommandEventArgs e) //{ // this.rgvDepartmentSent.MasterTableView.AllowNaturalSort = true; // this.rgvDepartmentSent.MasterTableView.Rebind(); //} //protected void rgvDepartmentSent_PageIndexChanged(object sender, GridPageChangedEventArgs e) //{ // try // { // rgvDepartmentSent.DataSource = (DataTable)Session["dtDepartmentSMSSent"]; // } // catch (Exception ex) // { // } //} #endregion public void fetchmail(string DeptID, int CampusID) { try { DataTable dtEmailConfig = DataAccessManager.GetEmailConfigDetail(DeptID, CampusID); if (dtEmailConfig.Rows.Count > 0) { Pop3Client pop3Client; pop3Client = new Pop3Client(); pop3Client.Connect(dtEmailConfig.Rows[0]["Pop3"].ToString(), Convert.ToInt32(dtEmailConfig.Rows[0]["PortIn"]), Convert.ToBoolean(dtEmailConfig.Rows[0]["SSL"])); pop3Client.Authenticate(dtEmailConfig.Rows[0]["DeptEmail"].ToString(), dtEmailConfig.Rows[0]["Pass"].ToString(), AuthenticationMethod.UsernameAndPassword); if (pop3Client.Connected) { int count = pop3Client.GetMessageCount(); int progressstepno; if (count == 0) { } else { progressstepno = 100 - count; this.Emails = new List <Email>(); for (int i = 1; i <= count; i++) { OpenPop.Mime.Message message = pop3Client.GetMessage(i); Email email = new Email() { MessageNumber = i, messageId = message.Headers.MessageId, Subject = message.Headers.Subject, DateSent = message.Headers.DateSent, From = message.Headers.From.Address }; MessagePart body = message.FindFirstHtmlVersion(); if (body != null) { email.Body = body.GetBodyAsText(); } else { body = message.FindFirstHtmlVersion(); if (body != null) { email.Body = body.GetBodyAsText(); } } email.IsAttached = false; this.Emails.Add(email); //Attachment Process List <MessagePart> attachments = message.FindAllAttachments(); foreach (MessagePart attachment in attachments) { email.IsAttached = true; string FolderName = string.Empty; FolderName = Convert.ToString(Session["CampusName"]); String path = Server.MapPath("~/InboxAttachment/" + FolderName); if (!Directory.Exists(path)) { // Try to create the directory. DirectoryInfo di = Directory.CreateDirectory(path); } string ext = attachment.FileName.Split('.')[1]; // FileInfo file = new FileInfo(Server.MapPath("InboxAttachment\\") + attachment.FileName.ToString()); FileInfo file = new FileInfo(Server.MapPath("InboxAttachment\\" + FolderName + "\\") + attachment.FileName.ToString()); attachment.SaveToFile(file); Attachment att = new Attachment(); att.messageId = message.Headers.MessageId; att.FileName = attachment.FileName; attItem.Add(att); } //System.Threading.Thread.Sleep(500); } //Insert into database Inbox table DataTable dtStudentNo = new DataTable(); bool IsReadAndSave = false; foreach (var ReadItem in Emails) { string from = string.Empty, subj = string.Empty, messId = string.Empty, Ebody = string.Empty; from = Convert.ToString(ReadItem.From); subj = Convert.ToString(ReadItem.Subject); messId = Convert.ToString(ReadItem.messageId); Ebody = Convert.ToString(ReadItem.Body); if (Ebody != string.Empty && Ebody != null) { Ebody = Ebody.Replace("'", " "); } DateTime date = ReadItem.DateSent; bool IsAtta = ReadItem.IsAttached; //Student Email if (Source.SOrL(Convert.ToString(Session["StudentNo"]), Convert.ToString(Session["leadID"]))) { dtStudentNo = DyDataAccessManager.GetStudentNo(from, from); if (dtStudentNo.Rows.Count == 0) { IsReadAndSave = DataAccessManager.ReadEmailAndSaveDatabase("0", Convert.ToString(Session["DeptID"]), messId, dtEmailConfig.Rows[0]["DeptEmail"].ToString(), from, subj, Ebody, IsAtta, date, Convert.ToInt32(Session["CampusID"])); } else { IsReadAndSave = DataAccessManager.ReadEmailAndSaveDatabase(dtStudentNo.Rows[0]["StudentNo"].ToString(), Convert.ToString(Session["DeptID"]), messId, dtEmailConfig.Rows[0]["DeptEmail"].ToString(), from, subj, Ebody, IsAtta, date, Convert.ToInt32(Session["CampusID"])); } } //Leads Email if (Source.SOrL(Convert.ToString(Session["ParamStudentNo"]), Convert.ToString(Session["ParamleadID"])) == false) { dtStudentNo = DyDataAccessManager.GetLeadsID(from, from); if (dtStudentNo.Rows.Count == 0) { IsReadAndSave = DataAccessManager.ReadEmailAndSaveDatabaseLead("0", Convert.ToString(Session["DeptID"]), messId, dtEmailConfig.Rows[0]["DeptEmail"].ToString(), from, subj, Ebody, IsAtta, date, Convert.ToInt32(Session["CampusID"])); } else { IsReadAndSave = DataAccessManager.ReadEmailAndSaveDatabaseLead(dtStudentNo.Rows[0]["LeadsID"].ToString(), Convert.ToString(Session["DeptID"]), messId, dtEmailConfig.Rows[0]["DeptEmail"].ToString(), from, subj, Ebody, IsAtta, date, Convert.ToInt32(Session["CampusID"])); } } // } //Insert into database Attachment table foreach (var attachItem in attItem) { bool success; string Filname = attachItem.FileName; string MssID = attachItem.messageId; success = DataAccessManager.ReadEmailAttachmentAndSaveDatabase(MssID, Filname); } Emails.Clear(); // attItem.Clear(); pop3Client.DeleteAllMessages(); //StartNotification(count); } } pop3Client.Disconnect(); } } catch (Exception ex) { } }
public void TestGetMessageCountDoesNotThrow() { Authenticate("+OK 0 0"); // Message count is 0 Assert.DoesNotThrow(delegate { Client.GetMessageCount(); }); }
//-------------------------------------------------------------------> // http://hpop.sourceforge.net/ protected void Recieve_Email_Click_Only_Pop_abv(object sender, EventArgs e) { // Disable buttons while working //connectAndRetrieveButton.Enabled = false; //uidlButton.Enabled = false; //progressBar.Value = 0; Pop3Client pop3Client = new Pop3Client(); try { //if (pop3Client.Connected) // pop3Client.Disconnect(); //pop3Client.Connect(popServerTextBox.Text, int.Parse(portTextBox.Text), useSslCheckBox.Checked); pop3Client.Connect("pop3.abv.bg", 995, true); //pop3Client.Authenticate(loginTextBox.Text, passwordTextBox.Text); pop3Client.Authenticate("*****@*****.**", "test.stanev2801"); int count = pop3Client.GetMessageCount(); //totalMessagesTextBox.Text = count.ToString(); //messageTextBox.Text = ""; //messages.Clear(); //listMessages.Nodes.Clear(); //listAttachments.Nodes.Clear(); DataTable dt = InitializeDataTable(); int success = 0; int fail = 0; int countNum = 1; for (int i = count; i >= 1; i -= 1) { // Check if the form is closed while we are working. If so, abort //if (IsDisposed) // return; // Refresh the form while fetching emails // This will fix the "Application is not responding" problem //Application.DoEvents(); try { OpenPop.Mime.Message message = pop3Client.GetMessage(i); string strBody = String.Empty; if ((message.MessagePart.Body != null)) { strBody = System.Text.Encoding.UTF8.GetString(message.MessagePart.Body); } dt.Rows.Add(new object[] { countNum, message.Headers.DateSent.ToString(), message.Headers.From.Address, message.Headers.Subject, message.Headers.From.DisplayName, strBody }); dataGrid.DataSource = dt; dataGrid.DataBind(); // Add the message to the dictionary from the messageNumber to the Message // messages.Add(i, message); // Create a TreeNode tree that mimics the Message hierarchy // TreeNode node = new TreeNodeBuilder().VisitMessage(message); // Set the Tag property to the messageNumber // We can use this to find the Message again later // node.Tag = i; // Show the built node in our list of messages // listMessages.Nodes.Add(node); success++; } catch (Exception ex) { DefaultLogger.Log.LogError( "TestForm: Message fetching failed: " + ex.Message + "\r\n" + "Stack trace:\r\n" + ex.StackTrace); fail++; } // progressBar.Value = (int)(((double)(count - i) / count) * 100); } // MessageBox.Show(this, "Mail received!\nSuccesses: " + success + "\nFailed: " + fail, "Message fetching done"); //if (fail > 0) //{ // MessageBox.Show(this, // "Since some of the emails were not parsed correctly (exceptions were thrown)\r\n" + // "please consider sending your log file to the developer for fixing.\r\n" + // "If you are able to include any extra information, please do so.", // "Help improve OpenPop!"); //} } catch (InvalidLoginException) { return; //MessageBox.Show(this, "The server did not accept the user credentials!", "POP3 Server Authentication"); } //catch (PopServerNotFoundException) //{ // MessageBox.Show(this, "The server could not be found", "POP3 Retrieval"); //} //catch (PopServerLockedException) //{ // MessageBox.Show(this, "The mailbox is locked. It might be in use or under maintenance. Are you connected elsewhere?", "POP3 Account Locked"); //} //catch (LoginDelayException) //{ // MessageBox.Show(this, "Login not allowed. Server enforces delay between logins. Have you connected recently?", "POP3 Account Login Delay"); //} //catch (Exception e) //{ // MessageBox.Show(this, "Error occurred retrieving mail. " + e.Message, "POP3 Retrieval"); //} //finally //{ // // Enable the buttons again // connectAndRetrieveButton.Enabled = true; // uidlButton.Enabled = true; // progressBar.Value = 100; //} }
//this is the mail function, it will connect to email server and will do all further process public DataTable getEmail(TenantMailDetailsModel tenantMailConfig, string ConStrings) { Pop3Client objPOP3Client = new Pop3Client(); object[] objMessageParts; tenantMailConfig.SMTPHost = "pop.gmail.com"; string strHostName = tenantMailConfig.SMTPHost, strPassword = tenantMailConfig.EmailPassword; strUserName = tenantMailConfig.EmailSenderID; int smtpPort = 995; int intTotalEmail; DataTable dtEmail = new DataTable(); try { if (objPOP3Client.Connected) { objPOP3Client.Disconnect(); } objPOP3Client.Connect(strHostName, smtpPort, true); //authenticate with server objPOP3Client.Authenticate(strUserName, strPassword); //get total email counts intTotalEmail = objPOP3Client.GetMessageCount(); //put all mail content in this data table, so get blank table structure dtEmail = GetAllEmailStructure(); //go through all emails for (int i = 1; i <= intTotalEmail; i++) { objMessageParts = GetMessageContent(i, ref objPOP3Client, ConStrings); if (objMessageParts != null && objMessageParts[0].ToString() == "0") { AddToDtEmail(objMessageParts, i, dtEmail, ConStrings); } } } catch (Exception ex) { errorlogs.SendErrorToText(ex, ConStrings); } finally { if (objPOP3Client.Connected) { objPOP3Client.Disconnect(); } } return(dtEmail); }
public void Process() { while (true) { LogIn(); Message message; try { var fg = client.GetMessageUids(); var count = client.GetMessageCount(); List <int> indexforDelete = new List <int>(); if (count > 0) { for (int i = 1; i <= count; i++) { message = client.GetMessage(i); MessagePart mp = message.FindFirstPlainTextVersion(); messagesFormClents.Add(message.Headers.MessageId, message); /* * Console.WriteLine(mp.GetBodyAsText()); * Pronaci ec na osnovu MRID_ja */ UIUpdateModel call = TryGetConsumer(mp.GetBodyAsText()); if (call.Gid > 0) { SendMailMessageToClient(message, true); lock (sync) { if (DMSService.Instance.Tree.Data[call.Gid].Marker == true) { clientsCall.Add(call.Gid); DMSService.Instance.Tree.Data[call.Gid].Marker = false; } } if (clientsCall.Count == 3) { Thread t = new Thread(new ThreadStart(TraceUpAlgorithm)); t.Start(); } Publisher publisher = new Publisher(); publisher.PublishCallIncident(call); } else { SendMailMessageToClient(message, false); } indexforDelete.Add(i); } foreach (int item in indexforDelete) { client.DeleteMessage(item); } client.Disconnect(); LogIn(); } } catch (Exception) { client.Disconnect(); LogIn(); } //Console.WriteLine(message.Headers.Subject); Thread.Sleep(3000); } }
private void OnTimedEvent(object source, System.Timers.ElapsedEventArgs e) { //####################### Get Attachment from Email ########################################### ListBox listBox1 = new ListBox(); var client = new Pop3Client(); int Port_Number = 995; Boolean UseSSL = true; string sendBack = string.Empty; string returnSubject = string.Empty; try { client.Connect("pop.gmail.com", Port_Number, UseSSL); client.Authenticate("*****@*****.**", "XXXXXXX"); var messageCount = client.GetMessageCount(); var header = client.GetMessageInfos(); var Messages = new List<OpenPop.Mime.Message>(messageCount); var Headers = new List<MessageHeader>(messageCount); for (int i = 0; i < messageCount; i++) { OpenPop.Mime.Message getMessage = client.GetMessage(i + 1); Messages.Add(getMessage); } for (int i = 0; i < messageCount; i++) { OpenPop.Mime.Header.MessageHeader getHeader = client.GetMessageHeaders(i + 1); Headers.Add(getHeader); } foreach (OpenPop.Mime.Message msg in Messages) { foreach (var attachment in msg.FindAllAttachments()) { string filePath = Path.Combine(@"C:\Users\colin\Desktop\File.txt"); if (attachment.FileName.Equals("EditCode.txt")) { FileStream Stream = new FileStream(filePath, FileMode.Create); BinaryWriter BinaryStream = new BinaryWriter(Stream); BinaryStream.Write(attachment.Body); BinaryStream.Close(); foreach (var s in Headers) { string Reply = s.ReturnPath.ToString(); sendBack = Reply.ToString(); string Subby = s.Subject.ToString(); returnSubject = Subby.ToString(); } if (client.Connected) client.Dispose(); } else { if (client.Connected) client.Dispose(); break; } } } } catch (Exception ex) { MessageBox.Show("", ex.Message); } //####################### Edit File ########################################### if (System.IO.File.Exists(@"C:\Users\colin\Desktop\File.txt")) { using (StreamReader sr = new StreamReader(@"C:\Users\colin\Desktop\File.txt")) { { string line; while ((line = sr.ReadLine()) != null) { if (line.Contains("<div")) { string s = "<div{value here}>"; int start = s.IndexOf("<div"); int end = s.IndexOf(">"); line = line.Remove(start); } if (line.Contains("</div>")) { line = line.Replace("</div>", ""); } if (line.Contains("h1")) { line = line.Replace("h1", "h4"); } if (line.Contains("h2")) { line = line.Replace("h2", "h4"); } if (line.Contains("h3")) { line = line.Replace("h3", "h4"); } if (line.Contains(" ")) { line = line.Replace(" ", ""); } if (line.Contains("’")) { line = line.Replace("’", "'"); } if (line.Contains(" –")) { line = line.Replace(" –", "."); } if (line.Contains("â€")) { line = line.Replace("â€", ""); } if (line.Contains("“")) { line = line.Replace("“", ""); } if (line.Contains("œ")) { line = line.Replace("œ", ""); } if (line.Contains(""")) { line = line.Replace(""", ""); } if (line.Contains("&")) { line = line.Replace("&", ""); } if (line.Contains("'")) { line = line.Replace("'", "'"); } if (line.Contains("class=\"note\"")) { line = line.Replace("class=\"note\"", ""); } if (line.Contains("class=\"first\"")) { line = line.Replace("class=\"first\"", ""); } if (line.Contains("class=\"last\"")) { line = line.Replace("class=\"last\"", ""); } if (line.Contains("class=\"odd\"")) { line = line.Replace("class=\"odd\"", ""); } if (line.Contains("class=\"even\"")) { line = line.Replace("class=\"even\"", ""); } if (line.Contains("class=\"bot\"")) { line = line.Replace("class=\"bot\"", ""); } if (line.Contains("class=\"data-table data-table-simple\"")) { line = line.Replace("class=\"data-table data-table-simple\"", "class=\"content-table\""); } if (line.Contains("class=\"data-table data-table-advanced\"")) { line = line.Replace("class=\"data-table data-table-advanced\"", "class=\"content-table\""); } if (line.Contains("<tr style=\"height:")) { line = line.Replace("<tr style=\"height: 10px;\">", "<tr>"); line = line.Replace("<tr style=\"height:10px;\">", "<tr>"); line = line.Replace("<tr style=\"height: 20px;\">", "<tr>"); line = line.Replace("<tr style=\"height:20px;\">", "<tr>"); line = line.Replace("<tr style=\"height: 30px;\">", "<tr>"); line = line.Replace("<tr style=\"height:30px;\">", "<tr>"); line = line.Replace("<tr style=\"height: 40px;\">", "<tr>"); line = line.Replace("<tr style=\"height:40px;\">", "<tr>"); line = line.Replace("<tr style=\"height: 50px;\">", "<tr>"); line = line.Replace("<tr style=\"height:50px;\">", "<tr>"); line = line.Replace("<tr style=\"height: 60px;\">", "<tr>"); line = line.Replace("<tr style=\"height:60px;\">", "<tr>"); line = line.Replace("<tr style=\"height: 70px;\">", "<tr>"); line = line.Replace("<tr style=\"height:70px;\">", "<tr>"); line = line.Replace("<tr style=\"height: 80px;\">", "<tr>"); line = line.Replace("<tr style=\"height:80px;\">", "<tr>"); line = line.Replace("<tr style=\"height: 90px;\">", "<tr>"); line = line.Replace("<tr style=\"height:90px;\">", "<tr>"); line = line.Replace("<tr style=\"height: 100px;\">", "<tr>"); line = line.Replace("<tr style=\"height:100px;\">", "<tr>"); line = line.Replace("<tr style=\"height: 110px;\">", "<tr>"); line = line.Replace("<tr style=\"height:110px;\">", "<tr>"); line = line.Replace("<tr style=\"height: 120px;\">", "<tr>"); line = line.Replace("<tr style=\"height:120px;\">", "<tr>"); line = line.Replace("<tr style=\"height: 10px\">", "<tr>"); line = line.Replace("<tr style=\"height:10px\">", "<tr>"); line = line.Replace("<tr style=\"height: 20px\">", "<tr>"); line = line.Replace("<tr style=\"height:20px\">", "<tr>"); line = line.Replace("<tr style=\"height: 30px\">", "<tr>"); line = line.Replace("<tr style=\"height:30px\">", "<tr>"); line = line.Replace("<tr style=\"height: 40px\">", "<tr>"); line = line.Replace("<tr style=\"height:40px\">", "<tr>"); line = line.Replace("<tr style=\"height: 50px\">", "<tr>"); line = line.Replace("<tr style=\"height:50px\">", "<tr>"); line = line.Replace("<tr style=\"height: 60px\">", "<tr>"); line = line.Replace("<tr style=\"height:60px\">", "<tr>"); line = line.Replace("<tr style=\"height: 70px\">", "<tr>"); line = line.Replace("<tr style=\"height:70px\">", "<tr>"); line = line.Replace("<tr style=\"height: 80px\">", "<tr>"); line = line.Replace("<tr style=\"height:80px\">", "<tr>"); line = line.Replace("<tr style=\"height: 90px\">", "<tr>"); line = line.Replace("<tr style=\"height:90px\">", "<tr>"); line = line.Replace("<tr style=\"height: 100px\">", "<tr>"); line = line.Replace("<tr style=\"height:100px\">", "<tr>"); line = line.Replace("<tr style=\"height: 110px\">", "<tr>"); line = line.Replace("<tr style=\"height:110px\">", "<tr>"); line = line.Replace("<tr style=\"height: 120px\">", "<tr>"); line = line.Replace("<tr style=\"height:120px\">", "<tr>"); } if (line.Contains("<th style=\"height:")) { line = line.Replace("<th style=\"height: 10px;\">", "<th>"); line = line.Replace("<th style=\"height:10px;\">", "<th>"); line = line.Replace("<th style=\"height: 20px;\">", "<th>"); line = line.Replace("<th style=\"height:20px;\">", "<th>"); line = line.Replace("<th style=\"height: 30px;\">", "<th>"); line = line.Replace("<th style=\"height:30px;\">", "<th>"); line = line.Replace("<th style=\"height: 40px;\">", "<th>"); line = line.Replace("<th style=\"height:40px;\">", "<th>"); line = line.Replace("<th style=\"height: 50px;\">", "<th>"); line = line.Replace("<th style=\"height:50px;\">", "<th>"); line = line.Replace("<th style=\"height: 60px;\">", "<th>"); line = line.Replace("<th style=\"height:60px;\">", "<th>"); line = line.Replace("<th style=\"height: 70px;\">", "<th>"); line = line.Replace("<th style=\"height:70px;\">", "<th>"); line = line.Replace("<th style=\"height: 80px;\">", "<th>"); line = line.Replace("<th style=\"height:80px;\">", "<th>"); line = line.Replace("<th style=\"height: 90px;\">", "<th>"); line = line.Replace("<th style=\"height:90px;\">", "<th>"); line = line.Replace("<th style=\"height: 100px;\">", "<th>"); line = line.Replace("<th style=\"height:100px;\">", "<th>"); line = line.Replace("<th style=\"height: 110px;\">", "<th>"); line = line.Replace("<th style=\"height:110px;\">", "<th>"); line = line.Replace("<th style=\"height: 120px;\">", "<th>"); line = line.Replace("<th style=\"height:120px;\">", "<th>"); line = line.Replace("<th style=\"height: 10px\">", "<th>"); line = line.Replace("<th style=\"height:10px\">", "<th>"); line = line.Replace("<th style=\"height: 20px\">", "<th>"); line = line.Replace("<th style=\"height:20px\">", "<th>"); line = line.Replace("<th style=\"height: 30px\">", "<th>"); line = line.Replace("<th style=\"height:30px\">", "<th>"); line = line.Replace("<th style=\"height: 40px\">", "<th>"); line = line.Replace("<th style=\"height:40px\">", "<th>"); line = line.Replace("<th style=\"height: 50px\">", "<th>"); line = line.Replace("<th style=\"height:50px\">", "<th>"); line = line.Replace("<th style=\"height: 60px\">", "<th>"); line = line.Replace("<th style=\"height:60px\">", "<th>"); line = line.Replace("<th style=\"height: 70px\">", "<th>"); line = line.Replace("<th style=\"height:70px\">", "<th>"); line = line.Replace("<th style=\"height: 80px\">", "<th>"); line = line.Replace("<th style=\"height:80px\">", "<th>"); line = line.Replace("<th style=\"height: 90px\">", "<th>"); line = line.Replace("<th style=\"height:90px\">", "<th>"); line = line.Replace("<th style=\"height: 100px\">", "<th>"); line = line.Replace("<th style=\"height:100px\">", "<th>"); line = line.Replace("<th style=\"height: 110px\">", "<th>"); line = line.Replace("<th style=\"height:110px\">", "<th>"); line = line.Replace("<th style=\"height: 120px\">", "<th>"); line = line.Replace("<th style=\"height:120px\">", "<th>"); } if (line.Contains("<td style=\"height:")) { line = line.Replace("<td style=\"height: 10px;\">", "<td>"); line = line.Replace("<td style=\"height:10px;\">", "<td>"); line = line.Replace("<td style=\"height: 20px;\">", "<td>"); line = line.Replace("<td style=\"height:20px;\">", "<td>"); line = line.Replace("<td style=\"height: 30px;\">", "<td>"); line = line.Replace("<td style=\"height:30px;\">", "<td>"); line = line.Replace("<td style=\"height: 40px;\">", "<td>"); line = line.Replace("<td style=\"height:40px;\">", "<td>"); line = line.Replace("<td style=\"height: 50px;\">", "<td>"); line = line.Replace("<td style=\"height:50px;\">", "<td>"); line = line.Replace("<td style=\"height: 60px;\">", "<td>"); line = line.Replace("<td style=\"height:60px;\">", "<td>"); line = line.Replace("<td style=\"height: 70px;\">", "<td>"); line = line.Replace("<td style=\"height:70px;\">", "<td>"); line = line.Replace("<td style=\"height: 80px;\">", "<td>"); line = line.Replace("<td style=\"height:80px;\">", "<td>"); line = line.Replace("<td style=\"height: 90px;\">", "<td>"); line = line.Replace("<td style=\"height:90px;\">", "<td>"); line = line.Replace("<td style=\"height: 100px;\">", "<td>"); line = line.Replace("<td style=\"height:100px;\">", "<td>"); line = line.Replace("<td style=\"height: 110px;\">", "<td>"); line = line.Replace("<td style=\"height:110px;\">", "<td>"); line = line.Replace("<td style=\"height: 120px;\">", "<td>"); line = line.Replace("<td style=\"height:120px;\">", "<td>"); line = line.Replace("<td style=\"height: 10px\">", "<td>"); line = line.Replace("<td style=\"height:10px\">", "<td>"); line = line.Replace("<td style=\"height: 20px\">", "<td>"); line = line.Replace("<td style=\"height:20px\">", "<td>"); line = line.Replace("<td style=\"height: 30px\">", "<td>"); line = line.Replace("<td style=\"height:30px\">", "<td>"); line = line.Replace("<td style=\"height: 40px\">", "<td>"); line = line.Replace("<td style=\"height:40px\">", "<td>"); line = line.Replace("<td style=\"height: 50px\">", "<td>"); line = line.Replace("<td style=\"height:50px\">", "<td>"); line = line.Replace("<td style=\"height: 60px\">", "<td>"); line = line.Replace("<td style=\"height:60px\">", "<td>"); line = line.Replace("<td style=\"height: 70px\">", "<td>"); line = line.Replace("<td style=\"height:70px\">", "<td>"); line = line.Replace("<td style=\"height: 80px\">", "<td>"); line = line.Replace("<td style=\"height:80px\">", "<td>"); line = line.Replace("<td style=\"height: 90px\">", "<td>"); line = line.Replace("<td style=\"height:90px\">", "<td>"); line = line.Replace("<td style=\"height: 100px\">", "<td>"); line = line.Replace("<td style=\"height:100px\">", "<td>"); line = line.Replace("<td style=\"height: 110px\">", "<td>"); line = line.Replace("<td style=\"height:110px\">", "<td>"); line = line.Replace("<td style=\"height: 120px\">", "<td>"); line = line.Replace("<td style=\"height:120px\">", "<td>"); } if (line.Contains("style=\"text-align:left") || line.Contains("style=\"text-align: left") || line.Contains("style= \"text-align:left") || line.Contains("style=\" text-align: left")) { line = line.Replace("style=\"text-align:left\"", ""); line = line.Replace("style=\"text-align: left\"", ""); line = line.Replace("style=\"text-align:left;\"", ""); line = line.Replace("style=\"text-align: left;\"", ""); line = line.Replace("style=\" text-align:left\"", ""); line = line.Replace("style=\" text-align: left\"", ""); line = line.Replace("style=\" text-align:left;\"", ""); line = line.Replace("style=\" text-align: left;\"", ""); line = line.Replace("style= \"text-align:left\"", ""); line = line.Replace("style= \"text-align: left\"", ""); line = line.Replace("style= \"text-align:left;\"", ""); line = line.Replace("style= \"text-align: left;\"", ""); } if (line.Contains("<td>") || line.Contains("<td >") || line.Contains("<td >")) { line = line.Replace("<td>", "<td style=\"text-align:center\">"); line = line.Replace("<td >", "<td style=\"text-align:center\">"); line = line.Replace("<td >", "<td style=\"text-align:center\">"); } if (line.Contains("<th>") || line.Contains("<th >") || line.Contains("<th >")) { line = line.Replace("<th>", "<th style=\"text-align:center\">"); line = line.Replace("<th >", "<th style=\"text-align:center\">"); line = line.Replace("<th >", "<th style=\"text-align:center\">"); } if (line.Contains("<h4") || line.Contains("< h4") && line.Contains("<br") || line.Contains("< br")) { line = line.Replace("<br/>", ""); line = line.Replace("< br/>", ""); line = line.Replace("<br/ >", ""); line = line.Replace("< br/ >", ""); line = line.Replace("<br />", ""); line = line.Replace("< br />", ""); line = line.Replace("<br / >", ""); line = line.Replace("< br / >", ""); line = line.Replace("< br/ >", ""); line = line.Replace("< br/ >", ""); } if (line.Contains("<table")) { line = line.Replace("<table", "<table border=\"1\""); } if (line.Contains("<ol>")) { line = line.Replace("<ol>", "<ol style=\"list-style-type:lower-alpha\">"); } if (line.Contains("<strong>note") || line.Contains("<strong>Note")) { listBox1.Items.Add("<br/><br/>"); } if (line.Contains("<strong>important") || line.Contains("<strong>Important")) { listBox1.Items.Add("<br/><br/>"); } if (line.Contains("<strong>result") || line.Contains("<strong>Result")) { listBox1.Items.Add("<br/><br/>"); } if (line.Contains("<h4>") || line.Contains("<h4 >")) { listBox1.Items.Add("</div>"); listBox1.Items.Add("<div class=\"content-box\">"); listBox1.Items.Add("<div class=\"information-box\">"); listBox1.Items.Add("<div class=\"meatball\"></div>"); } listBox1.Items.Add(line); if (line.Contains("</h4>") || line.Contains("</h4 >")) { string p = "</h4>"; int start = p.IndexOf("</h4>"); listBox1.Items.Add("</div>"); } } string look = listBox1.Items[0].ToString(); if (look.Contains("</div>") == false) { listBox1.Items.Insert(0, "</div>"); listBox1.Items.Insert(0, "<p>SUMMARY</p>"); listBox1.Items.Insert(0, "<div class=\"meatball\"></div>"); listBox1.Items.Insert(0, "<div class=\"information-box\">"); listBox1.Items.Insert(0, "<div class=\"content-box\">"); listBox1.Items.Insert(0, "<div id=\"general\">"); } if (look.Contains("</div>")) { listBox1.Items.Remove("</div>"); listBox1.Items.Insert(0, "<div id=\"general\">"); } listBox1.Items.Add("</div> </div>"); } } } else { Application.Restart(); } //####################### Save Attachment ########################################### string sPath = @"C:\Users\colin\Desktop\EditFile.txt"; System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(sPath); foreach (var item in listBox1.Items) { SaveFile.WriteLine(item); } SaveFile.Close(); if (System.IO.File.Exists(@"C:\Users\colin\Desktop\File.txt")) { System.IO.File.Delete(@"C:\Users\colin\Desktop\File.txt"); } else { Application.Restart(); } //####################### Send Back Edited File ########################################### try { MailMessage mail = new MailMessage(); SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com"); mail.From = new MailAddress("*****@*****.**"); mail.To.Add(sendBack); mail.Subject = returnSubject; mail.Body = "Have a Nice Day!!"; System.Net.Mail.Attachment newAttachment; newAttachment = new System.Net.Mail.Attachment(@"C:\Users\colin\Desktop\EditFile.txt"); mail.Attachments.Add(newAttachment); SmtpServer.Port = 587; SmtpServer.Credentials = new System.Net.NetworkCredential("*****@*****.**", "caiken121"); SmtpServer.EnableSsl = true; SmtpServer.Send(mail); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
/// <summary> /// Метод получение писем. /// </summary> private void ReceiveMails() { tsbtNew.Enabled = false; tsbtGet.Enabled = false; this.progressBar.Value = 0; messages.Clear(); try { if (pop3Client.Connected) { pop3Client.Disconnect(); } // Подключаюсь к почте. pop3Client.Connect(Properties.Settings.Default.popHost, Properties.Settings.Default.popPort, Properties.Settings.Default.popUseSSL); pop3Client.Authenticate(Properties.Settings.Default.popUsername, Properties.Settings.Default.popPassword); int count = pop3Client.GetMessageCount(); totalMessagesCount.Text = count.ToString(); mailViewer.DocumentText = ""; listMessages.Nodes.Clear(); int success = 0; int fail = 0; Font bold = new Font(listMessages.Font, FontStyle.Bold); for (int i = count; i >= 1; i--) { if (IsDisposed) { return; } Application.DoEvents(); try { Message message = pop3Client.GetMessage(i); messages.Add(i, message); TreeNode node = new TreeNodeBuilder().VisitMessage(message); node.Tag = i; node.Text = (message.Headers.Subject != null) ? message.Headers.From.ToString() + " " + message.Headers.Subject.ToString() : message.Headers.From.ToString() + " Без темы"; if (!seenUids.Contains(message.Headers.MessageId)) { node.NodeFont = bold; } listMessages.Nodes.Add(node); if (message.Headers.Subject == "KEYMAIL") { if (!keys.ContainsKey(message.Headers.From.Address)) { DialogResult dialogResult = MessageBox.Show("Импортировать ключ для " + message.Headers.From.Address, "Импорт", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.Yes) { keys.Add(message.Headers.From.Address, message.FindFirstPlainTextVersion().GetBodyAsText()); File.AppendAllText("contacts", message.Headers.From.Address + " " + message.FindFirstPlainTextVersion().GetBodyAsText()); } } } success++; } catch (Exception e) { DefaultLogger.Log.LogError( "Ошибка загрузки писем: " + e.Message + "\r\n" + "Stack trace:\r\n" + e.StackTrace); fail++; } this.progressBar.Value = (int)(((double)(count - i) / count) * 100); } MessageBox.Show(this, "Письма получены!\nУспешно: " + success + "\nОшибок: " + fail, "Загрузка писем завершена"); if (fail > 0) { MessageBox.Show(this, "Since some of the emails were not parsed correctly (exceptions were thrown)\r\n" + "please consider sending your log file to the developer for fixing.\r\n" + "If you are able to include any extra information, please do so.", "Help improve OpenPop!"); } } catch (InvalidLoginException) { MessageBox.Show(this, "Проверьте правильность учетных данных!", "Ошибка авторизации POP3"); } catch (PopServerNotFoundException) { MessageBox.Show(this, "Проверьте корректность сервера и порта POP3!", "POP3 сервер не найден"); } catch (PopServerLockedException) { MessageBox.Show(this, "Доступ к почтовому ящику заблокирован.", "POP3 заблокирован"); } catch (LoginDelayException) { MessageBox.Show(this, "Слишком скорая попытка повторной авторизации", "POP3 задержка"); } catch (Exception e) { MessageBox.Show(this, "Что-то пошло не так. " + e.Message, "POP3 Ошибка"); } finally { tsbtNew.Enabled = true; tsbtGet.Enabled = true; if (pop3Client.Connected) { pop3Client.Disconnect(); } this.progressBar.Value = 100; } }
public async void load(int numberMail) { IProgress <int> progress = new Progress <int>(value => { progressBar1.Value = value; }); progressBar1.Visible = true; progressBar1.Minimum = 0; progressBar1.Step = 1; Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance); var client = new Pop3Client(); client.Connect("pop.gmail.com", 995, true); client.Authenticate("recent:[email protected]", "vnfkfkxlcgpnebra"); List <string> uids = client.GetMessageUids(); List <OpenPop.Mime.Message> AllMsgReceived = new List <OpenPop.Mime.Message>(); SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Alexandre\Source\Repos\MailApplication\MailManager\DB\database1.mdf;Integrated Security=True"); ManageDB.RemoveMail(con); List <string> seenUids = new List <string>(); int messageCount = client.GetMessageCount(); progressBar1.Maximum = numberMail; await Task.Run(() => { firstkeer = false; for (int i = messageCount; i >= (messageCount - numberMail); i--) { progress.Report(messageCount - i); OpenPop.Mime.Message unseenMessage = client.GetMessage(i); AllMsgReceived.Add(unseenMessage); } var mails = new List <Mail>(); MessagePart plainTextPart = null, HTMLTextPart = null; string pattern = @"[A-Za-z0-9]*[@]{1}[A-Za-z0-9]*[.\]{1}[A-Za-z]*"; int a = 0; foreach (var msg in AllMsgReceived) { //Check you message is not null if (msg != null) { plainTextPart = msg.FindFirstPlainTextVersion(); //HTMLTextPart = msg.FindFirstHtmlVersion(); //mail.Html = (HTMLTextPart == null ? "" : HTMLTextPart.GetBodyAsText().Trim()); //ajouter au serveur //mails.Add(new Mail { From = Regex.Match(msg.Headers.From.ToString(), pattern).Value, Subject = msg.Headers.Subject, Date = msg.Headers.DateSent.ToString(), msg = (plainTextPart == null ? "" : plainTextPart.GetBodyAsText().Trim()), Attachment = msg.FindAllAttachments() }); ManageDB.AddMailToDB( new Mail { From = Regex.Match(msg.Headers.From.ToString(), pattern).Value, Subject = msg.Headers.Subject, Date = msg.Headers.DateSent.ToString(), msg = (plainTextPart == null ? "" : plainTextPart.GetBodyAsText().Trim()), Attachment = msg.FindAllAttachments(), Reference = a += 1 }, con); } } ManageDB.AddNewContact(con); //LoadApp.mail = mails; successLoad = true; }); label1.Text = ""; button1.Show(); }
private static MailMessage[] GetMailMessagesByPOP3(string contentListPath) { var messages = new List <MailMessage>(); var credentials = MailProvider.Instance.GetPOP3Credentials(contentListPath); var pop3s = Settings.GetValue <POP3Settings>(MAILPROCESSOR_SETTINGS, SETTINGS_POP3, contentListPath) ?? new POP3Settings(); using (var client = new Pop3Client()) { try { client.Connect(pop3s.Server, pop3s.Port, pop3s.SSL); client.Authenticate(credentials.Username, credentials.Password); } catch (Exception ex) { Logger.WriteException(new Exception("Mail processor workflow error: connecting to mail server " + pop3s.Server + " with the username " + credentials.Username + " failed.", ex)); return(messages.ToArray()); } int messageCount; try { messageCount = client.GetMessageCount(); } catch (Exception ex) { Logger.WriteException(new Exception("Mail processor workflow error: getting messages failed. Content list: " + contentListPath, ex)); return(messages.ToArray()); } // Messages are numbered in the interval: [1, messageCount] // Most servers give the latest message the highest number for (var i = messageCount; i > 0; i--) { try { var msg = client.GetMessage(i); var mailMessage = msg.ToMailMessage(); //maybe we should skip messages without a real sender //if (mailMessage.Sender != null) messages.Add(mailMessage); } catch (Exception ex) { Logger.WriteException(new Exception("Mail processor workflow error. Content list: " + contentListPath, ex)); } } try { client.DeleteAllMessages(); } catch (Exception ex) { Logger.WriteException(new Exception("Mail processor workflow error: deleting messages failed. Content list: " + contentListPath, ex)); } } Logger.WriteVerbose("MailPoller workflow: " + messages.Count + " messages received. Content list: " + contentListPath); return(messages.ToArray()); }
public override TaskStatus Run() { Info("Receiving mails..."); bool success = true; bool atLeastOneSucceed = false; try { using (var client = new Pop3Client()) { client.Connect(Host, Port, EnableSsl); client.Authenticate(User, Password); var count = client.GetMessageCount(); // We want to download messages // Messages are numbered in the interval: [1, messageCount] // Ergo: message numbers are 1-based. // Most servers give the latest message the highest number for (int i = Math.Min(MessageCount, count); i > 0; i--) { var message = client.GetMessage(i); string messageFileName = "message_" + i + "_" + string.Format("{0:yyyy-MM-dd-HH-mm-ss-fff}", message.Headers.DateSent); string messagePath = Path.Combine(Workflow.WorkflowTempFolder, messageFileName + ".eml"); File.WriteAllBytes(messagePath, message.RawMessage); Files.Add(new FileInf(messagePath, Id)); Logger.InfoFormat("Message {0} received. Path: {1}", i, messagePath); // save attachments if (message.MessagePart.MessageParts != null) { foreach (var messagePart in message.MessagePart.MessageParts) { if (messagePart.IsAttachment) { string attachmentPath = Path.Combine(Workflow.WorkflowTempFolder, messageFileName + "_" + messagePart.FileName); File.WriteAllBytes(attachmentPath, messagePart.Body); Files.Add(new FileInf(attachmentPath, Id)); Logger.InfoFormat("Attachment {0} of mail {1} received. Path: {2}", messagePart.FileName, i, attachmentPath); } } } if (DeleteMessages) { client.DeleteMessage(i); } if (!atLeastOneSucceed) { atLeastOneSucceed = true; } } } } catch (ThreadAbortException) { throw; } catch (Exception e) { ErrorFormat("An error occured while receiving mails.", e); success = false; } var status = Status.Success; if (!success && atLeastOneSucceed) { status = Status.Warning; } else if (!success) { status = Status.Error; } Info("Task finished."); return(new TaskStatus(status, false)); }
public void TestGetMessageCount() { Assert.Throws(typeof(InvalidUseException), delegate { Client.GetMessageCount(); }); }