/// <summary> /// 一次性获取邮件 /// </summary> /// <param name="mailIndex"></param> public override void GetMessage(int mailIndex) { message = _pop3Client.GetMessage(mailIndex); }
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 progressBar.Value = 0; Pop3Client pop3Client; try { pop3Client = new Pop3Client(); pop3Client.Connect(Settings.Default.PopServer, int.Parse(Settings.Default.PopPort), useSslCheckBox.Checked); pop3Client.Authenticate(Settings.Default.LoginUser, Settings.Default.LoginPw); 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 progressBar.Value = 100; } }
// 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); } }
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"); } }
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)); 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)); 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)); }
private void btnConnect_Click(object sender, EventArgs e) { if (!client.Connected) { btnConnect.Text = "Disconnect"; // Connect to the server try { client.Connect(txtServer.Text, Convert.ToInt32(txtPort.Text), SSL_bx.Checked); txtLog.AppendText(DateTime.Now.ToLongTimeString() + " 39. Server connected.\r\n\r\n"); txtLog.Update(); // Authenticate ourselves towards the server try { client.Authenticate(txtUser.Text, txtPass.Text); txtLog.AppendText(DateTime.Now.ToLongTimeString() + " 44. Server Authenticated.\r\n\r\n"); txtLog.Update(); // Get the number of messages in the inbox List <string> mssgs = client.GetMessageUids(); int messageCount = mssgs.Count; txtLog.AppendText(DateTime.Now.ToLongTimeString() + " 51. Total messages: " + messageCount.ToString() + "\r\n\r\n"); txtLog.Update(); // We want to download all messages allMessages = new List <OpenPop.Mime.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 > (messageCount - 10); i--) { OpenPop.Mime.Message curr_mssg = client.GetMessage(i); allMessages.Add(curr_mssg); this.mail_gridview.Rows.Add(curr_mssg.Headers.From.MailAddress.ToString(), (messageCount - i)); } } catch (Exception ex) { txtLog.AppendText(DateTime.Now.ToLongTimeString() + " 69. Error: " + ex.Message + "\r\n\r\n"); txtLog.Update(); client.Disconnect(); btnConnect.Text = "Connect"; txtLog.AppendText(DateTime.Now.ToLongTimeString() + " 73. Disconnected.\r\n\r\n"); return; } } catch (Exception ex) { txtLog.AppendText(DateTime.Now.ToLongTimeString() + " 79. Error: " + ex.Message + "\r\n\r\n"); txtLog.Update(); btnConnect.Text = "Connect"; return; } } else { btnConnect.Text = "Connect"; client.Disconnect(); txtLog.AppendText(DateTime.Now.ToLongTimeString() + " 89. Disconnected.\r\n\r\n"); } }
/// <summary> /// Return last mail's content stored in the database /// </summary> /// <param name="MailServerName">EMail server name</param> /// <param name="PortNo">EMail port no</param> /// <param name="isSslEnabled">Is SSL enabled</param> /// <param name="loginName">EMail Id for which you want ot get the data</param> /// <param name="Password">EMail password</param> /// <returns>Currently return last mail's data</returns> public DataTable mailcontents(string MailServerName, int PortNo, bool isSslEnabled, string loginName, string Password) { Dictionary <int, Message> messages = new Dictionary <int, Message>(); DataTable datatable = new DataTable(); //// This is how you would override the default logger type //// Here we want to log to a file DefaultLogger.SetLog(new FileLogger()); FileLogger.LogPath = HttpContext.Current.Server.MapPath("~/Attachments/"); // Enable file logging and include verbose information FileLogger.Enabled = true; FileLogger.Verbose = true; try { pop3Client = new Pop3Client(); data = new Pop3DataClient(); if (pop3Client.Connected) { pop3Client.Disconnect(); } pop3Client.Connect(MailServerName, PortNo, isSslEnabled); pop3Client.Authenticate(loginName, Password); //DateTime? lastmsgSavedDate = data.GetLastSavedDate(ConnString, loginName); //messages = pop3Client.GetAllMessages(lastmsgSavedDate); //Used to get all messages from the given EMail Id //foreach (Message message in messages.Values) //{ int msgcount = pop3Client.GetMessageCount(); Message message = pop3Client.GetMessage(msgcount); data.SaveMessageToDatabase(ConnString, message, FileLogger.LogPath); //} //Currently return last inserted data datatable = data.GetMessageFromDatabase(ConnString).Tables[0]; return(datatable); } catch (InvalidLoginException) { DefaultLogger.Log.LogError("POP3 Server Authentication: The server did not accept the user credentials!"); return(datatable); } catch (PopServerNotFoundException) { DefaultLogger.Log.LogError("POP3 Retrieval: The server could not be found"); return(datatable); } catch (PopServerLockedException) { DefaultLogger.Log.LogError("POP3 Account Locked: The mailbox is locked. It might be in use or under maintenance. Are you connected elsewhere?"); return(datatable); } catch (LoginDelayException) { DefaultLogger.Log.LogError("POP3 Account Login Delay: Login not allowed. Server enforces delay between logins. Have you connected recently?"); return(datatable); } catch (Exception ex) { DefaultLogger.Log.LogError("Failed Code due to: " + ex.Message + "\r\n" + "Stack trace:\r\n" + ex.StackTrace); return(datatable); } }
public async Task <int> ReceivedEmailAsync() { var pop3Client = new Pop3Client(); try { var emails = await _emailSettingsRepository.Find(x => true); var defaultEmail = emails.FirstOrDefault(); if (pop3Client.Connected) { pop3Client.Disconnect(); } pop3Client.Connect(defaultEmail.DomainPop, defaultEmail.PortPop, true); pop3Client.Authenticate(defaultEmail.Email, defaultEmail.Password); int count = pop3Client.GetMessageCount(); for (int i = 1; i < count + 1; i++) { try { var message = pop3Client.GetMessage(i); var messageId = message.Headers.MessageId.ToString(); var mailFind = await _mailSentAndReceivedRepository.FindOne(x => x.MessageId == messageId); if (mailFind != null) { continue; } var mail = new MailSentAndReceived(); mail.To = message.Headers.To.FirstOrDefault().Address; mail.From = message.Headers.From.MailAddress.Address; mail.Subject = message.Headers.Subject; mail.MessageId = message.Headers.MessageId.ToString(); mail.Date = DateTime.Now; mail.Type = "Received"; var messagePart = message.MessagePart.MessageParts[1]; mail.Body = messagePart.BodyEncoding.GetString(messagePart.Body); await _mailSentAndReceivedRepository.Add(mail); } catch (Exception exc) { var message = exc.ToString(); } } return(count); } catch (Exception exc) { var message = exc.ToString(); return(0); } finally { if (pop3Client.Connected) { pop3Client.Disconnect(); } } }
private string GetMessage(string lastMessageUid, out MimeMessage message) { try { // メール設定取得 var pref = PreferenceManager.GetDefaultSharedPreferences(this); var mailAddress = pref.GetString("mail_address", ""); var mailPassword = pref.GetString("mail_password", ""); var serverAddress = pref.GetString("mail_pop3_server", ""); var useSsl = pref.GetBoolean("mail_pop3_usessl", false); var strPort = pref.GetString("mail_pop3_port", ""); int port; if (string.IsNullOrWhiteSpace(strPort) || !int.TryParse(strPort, out port)) { port = useSsl ? 995 : 110; } // メールアドレス、サーバーアドレスの設定がなければ処理中断 if (string.IsNullOrWhiteSpace(mailAddress) || string.IsNullOrWhiteSpace(serverAddress)) { message = null; return(null); } // 返信済みメッセージID一覧取得 HashSet <string> repliedMessageIds; lock (Constants.DB_LOCK) { using (var db = new SQLiteConnection(Constants.DB_PATH)) { db.CreateTable <RepliedMessage>(); repliedMessageIds = new HashSet <string>(db.Table <RepliedMessage>().ToList().Select(rec => rec.MessageUid)); } } var cm = (ConnectivityManager)GetSystemService(Context.ConnectivityService); if (cm.ActiveNetworkInfo?.IsConnected ?? false) { using (var pop3Client = new Pop3Client()) { try { pop3Client.Connect(serverAddress, port, true); pop3Client.Authenticate(mailAddress, mailPassword); // メッセージID一覧を取得 var messageUids = pop3Client.GetMessageUids(); // メッセージIDの中から返信していない最初のメッセージIDのインデックスを取得 var newMessageInfo = messageUids .Select((uid, index) => new { uid, index }) .FirstOrDefault(obj => !repliedMessageIds.Contains(obj.uid)); if (newMessageInfo != null) { if (newMessageInfo.uid != lastMessageUid) { message = pop3Client.GetMessage(newMessageInfo.index); LogHelper.Debug($"New Mail MessageUid:{ newMessageInfo.uid }"); } else { // 前回と同じUIDの場合メール本文を取得しない message = null; LogHelper.Debug($"Same Last Mail MessageUid:{ newMessageInfo.uid }"); } return(newMessageInfo.uid); } else { LogHelper.Debug("No Mail"); } } finally { try { pop3Client.Disconnect(true); } catch (Exception) { } } } } else { LogHelper.Debug("No Network"); } } catch (Exception ex) { LogHelper.Error(ex, "GetMessage Error"); } message = null; return(null); }
private void button11_Click(object sender, EventArgs e) { dt = new DataTable("Inbox"); dt.Columns.Add("ID"); dt.Columns.Add("Temat"); dt.Columns.Add("Sender"); dt.Columns.Add("Email"); dt.Columns.Add("Tekst"); dt.Columns.Add("Czas"); dataGridView1.DataSource = dt; try { client.Connect(comboBox5.Text, 995, true); client.Authenticate(textBox6.Text, textBox5.Text, OpenPop.Pop3.AuthenticationMethod.UsernameAndPassword); int count = client.GetMessageCount(); string htmlContained = ""; if (client.Connected) { // for (int i = count; i > count - 100 && i >= 0; i--) // for (int i = 1; i <=100 && i <= count; i--) // for (int i = 1; i <= count && i <= 100 ; i++) // for (int i = count; i >= 100; i--) for (int i = count; i > count - Convert.ToInt32(textBox4.Text) && i >= 1; i--) { OpenPop.Mime.Message message = client.GetMessage(i); OpenPop.Mime.MessagePart html = message.FindFirstHtmlVersion(); OpenPop.Mime.MessagePart file = message.FindFirstMessagePartWithMediaType(""); if (html != null) { htmlContained = html.GetBodyAsText(); } else { html = message.FindFirstPlainTextVersion(); htmlContained = html.GetBodyAsText(); } string name = message.Headers.Subject; if (name == "") { name = "Brak Tematu"; } string nadawca = message.Headers.From.DisplayName; if (nadawca == "") { nadawca = "Brak Informacji"; } dt.Rows.Add(new object[] { i.ToString(), name.ToString(), nadawca.ToString(), message.Headers.From.Address, htmlContained, message.Headers.DateSent }); } } client.Disconnect(); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
/// <summary> /// Retorna una lista de mensajes que cumplen el filtro de Asunto /// </summary> /// <param name="hostname"></param> /// <param name="port"></param> /// <param name="useSsl"></param> /// <param name="username"></param> /// <param name="password"></param> /// <param name="idMessageEnd"></param> /// <param name="subject"></param> /// <returns></returns> public static List <Message> GetMessages(int port, string hostname, string username, string password, bool useSsl, string subject, int idMessageRead, string[] subjectOther, out int idMessageFinal) { using (Pop3Client client = new Pop3Client()) { // conectando al server client.Connect(hostname, port, useSsl); client.Authenticate(username, password); idMessageFinal = client.GetMessageCount(); List <Message> allMessages = new List <Message>(); if (idMessageFinal > idMessageRead) { int idMessage = idMessageFinal; //recupera mensajes sin revisar while (idMessage > idMessageRead) { MessageHeader headers = client.GetMessageHeaders(idMessage); bool valido = false; for (int i = 0; i < subjectOther.Length; i++) { if (subjectOther[i].Trim().ToUpper().Equals(headers.Subject.Trim().ToUpper())) { valido = true; } } //if (subject.ToUpper().Equals(headers.Subject.Trim().ToUpper())) if (valido) { // Download the full message allMessages.Add(client.GetMessage(idMessage)); } //else //{ // if (subjectOther.Length>0) // { // for (int i = 0; i < subjectOther.Length; i++) // { // if (!subjectOther[i].ToUpper().Equals(headers.Subject.Trim().ToUpper())) // { // ReplyMsg(client.GetMessage(idMessage), headers, username, password); // } // } // } //} idMessage -= 1; } return(allMessages); } else { if (idMessageFinal == idMessageRead) { //No hay cambio de idCorreo idMessageFinal = 0; } return(new List <Message>()); } } }
/// <summary> /// 接受邮件主函数 /// </summary> /// <param name="name">帐号全名</param> /// <param name="pwd">密码</param> /// <param name="keyWord">关键字</param> /// <returns></returns> public string ReceiveMails(string name, string pwd, string keyWord) { string content = string.Empty; string server = GetServer(name); Dictionary <int, Message> messages = new Dictionary <int, Message>(); messages = new Dictionary <int, Message>(); using (Pop3Client pop3Client = new Pop3Client()) { try { if (pop3Client.Connected) { pop3Client.Disconnect(); } pop3Client.Connect(server, 110, false); pop3Client.Authenticate(name, pwd); int count = pop3Client.GetMessageCount(); 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 url; // 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); success++; break; } catch (Exception ex) { this.WriteLog("读取邮件异常" + ex.ToString()); } } this.WriteLog("Mail received!\nSuccesses: " + success + "\nFailed: " + 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!"); } // 读取最后一封邮件 if (messages.Count > 0) { // 取时间距离当前最近的一封。 var list = (from f in messages where f.Value.Headers.From.DisplayName == keyWord orderby f.Value.Headers.DateSent descending select f).ToList(); if (list.Count > 0) { Message message = list[0].Value; // 得到的时间是东0区的时间 if (message.Headers.DateSent < DateTime.UtcNow.AddHours(-2)) { // 邮件已经失效了 // throw new Exception("邮件已经失效了"); } if (message.Headers.From.DisplayName == keyWord) { MessagePart plainTextPart = message.FindFirstPlainTextVersion(); if (plainTextPart != null) { // The message had a text/plain version - show that one content = plainTextPart.GetBodyAsText(); } } } } } catch (InvalidLoginException) { // 账号异常了。 this.WriteLog("The server did not accept the user credentials!"); } catch (PopServerNotFoundException) { this.WriteLog("The server could not be found"); } catch (PopServerLockedException) { this.WriteLog("The mailbox is locked. It might be in use or under maintenance. Are you connected elsewhere?"); } catch (LoginDelayException) { this.WriteLog("Login not allowed. Server enforces delay between logins. Have you connected recently?"); } catch (Exception e) { this.WriteLog("Error occurred retrieving mail. " + e.Message); } } return(content); }
static void Main(string[] args) { Console.WriteLine("Subject:"); var subject = Console.ReadLine(); Console.WriteLine("Receiver EMAIL: "); var receiver = Console.ReadLine(); Console.WriteLine("Sender EMAIL:"); var sender = Console.ReadLine(); Console.WriteLine("Sender PASSWORD:"******"Type Message:"); var messagetext = Console.ReadLine(); var message = new MimeMessage(); message.From.Add(new MailboxAddress(sender)); message.To.Add(new MailboxAddress(receiver)); message.Subject = subject; var builder = new BodyBuilder(); builder.TextBody = messagetext; var image = builder.LinkedResources.Add(@"C:\Users\Daniela\Desktop\simba.png"); image.ContentId = MimeUtils.GenerateMessageId(); builder.HtmlBody = string.Format($"<p>{messagetext} </p><br> " + @"<center><img src=""cid:{0}""></center>", image.ContentId); builder.Attachments.Add(@"C:\Users\Daniela\Desktop\WordFile.docx"); message.Body = builder.ToMessageBody(); try { using (var client = new SmtpClient(new ProtocolLogger(Console.OpenStandardOutput()))) { client.ServerCertificateValidationCallback = (s, c, h, e) => true; client.Connect("smtp.gmail.com", 587, MailKit.Security.SecureSocketOptions.StartTls); client.Authenticate(sender, psender); client.Send(message); client.Disconnect(true); Console.WriteLine("Send Mail Success."); } Console.WriteLine("Nummber of message to receive:"); var maxCount = Convert.ToInt32(Console.ReadLine()); using (var clientreceive = new Pop3Client()) { clientreceive.Connect("pop.gmail.com", 995, true); clientreceive.Authenticate(sender, psender); var emails = new List <MimeMessage>(); for (var i = 0; i < clientreceive.Count && i < maxCount; i++) { emails.Add(clientreceive.GetMessage(i)); } emails.ForEach(x => Console.WriteLine($"From: {x.From.Mailboxes.First()}\n" + $"Subject: {x.Subject}\nContent: {x.TextBody}")); clientreceive.Disconnect(true); Console.WriteLine("Receive Mail Success."); } } catch (Exception e) { Console.WriteLine("Send Mail Failed : " + e.Message); } Console.ReadLine(); }
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); } }
public List <Message> FetchAllMessagesWithMultipleAccounts() { V1Logging Logs = new V1Logging(); // The client disconnects from the server when being disposed using (Pop3Client client = new Pop3Client()) { // Get the number of messages in the inbox int messageCount; // We want to download all messages List <Message> allMessages = new List <Message>(); XmlDocument EmailConfig = new XmlDocument(); EmailConfig.PreserveWhitespace = true; EmailConfig.Load(AppDomain.CurrentDomain.BaseDirectory + "V1EmailConfig.xml"); XmlElement EmailRoot = EmailConfig.DocumentElement; XmlNodeList EmailNodes = EmailRoot.SelectNodes("/EmailInfo/EmailAccount"); try { foreach (XmlNode EmailNode in EmailNodes) { Logs.LogEvent("Operation - Checking Email Server " + EmailNode["EmailAddress"].InnerText); // Connect to the server client.Connect(EmailNode["EmailPOP3"].InnerText, Convert.ToInt32(EmailNode["POP3PortNumber"].InnerText), Convert.ToBoolean(EmailNode["EmailUseSSL"].InnerText)); // Authenticate ourselves towards the server client.Authenticate(EmailNode["EmailAddress"].InnerText, EmailNode["EmailPassword"].InnerText); if (client.Connected == true) { // Get the number of messages in the inbox messageCount = client.GetMessageCount(); // We want to download all messages //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)); } client.Disconnect(); } else { Logs.LogEvent("ERROR - Fetching Messages - Can't connect to mail server"); } } }catch (Exception e) { Logs.LogEvent("ERROR - Fetching Messages - " + e); } // Now return the fetched messages Debug.WriteLine("Total Number of Messages Found: " + allMessages.Count.ToString()); return(allMessages); } }
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 static async Task FetchAllMessagesOAuthAsync() { // The permission scope required for EWS access var ewsScopes = new string[] { "https://outlook.office365.com/POP.AccessAsUser.All" }; var ClientId = ""; var TenantId = ""; // Configure the MSAL client to get tokens var pcaOptions = new PublicClientApplicationOptions { ClientId = ClientId, TenantId = TenantId }; var pca = PublicClientApplicationBuilder .CreateWithApplicationOptions(pcaOptions).Build(); //SecureString passwordSecure = new NetworkCredential("", "myPass").SecurePassword; var securePassword = new SecureString(); foreach (char c in "") { securePassword.AppendChar(c); } try { // Make the interactive token request var authResult = await pca.AcquireTokenByUsernamePassword(ewsScopes, "", securePassword).ExecuteAsync(); using (var client = new Pop3Client(new ProtocolLogger("pop3.log"))) { client.Connect("outlook.office365.com", 995, SecureSocketOptions.SslOnConnect); client.Authenticate(new SaslMechanismOAuth2("", authResult.AccessToken)); for (int i = 0; i < client.Count; i++) { var message = client.GetMessage(i); // write the message to a file message.WriteTo(string.Format("{0}.msg", i)); // mark the message for deletion client.DeleteMessage(i); } client.Disconnect(true); } } catch (MsalException x) { Console.Write(x.Message); throw; } }
private void RetrievePOP3Mail() { EmailsToRead = ""; using (var client = new Pop3Client()) { // accept all SSL certificates (in case the server supports STARTTLS) client.ServerCertificateValidationCallback = (s, c, h, e) => true; //Console.WriteLine("Connecting to MailServer" + GetString(Resource.String.GDSSEMailServerHost) +" port 995"); //Toast.MakeText(this, "Email Sync: Authenticating to Server", ToastLength.Long).Show(); client.Connect(GetString(Resource.String.GDSSEMailServerHost), int.Parse(GetString(Resource.String.GDSSEMailServerPort)), true); // Note: since we don't have an OAuth2 token, disable // the XOAUTH2 authentication mechanism. client.AuthenticationMechanisms.Remove("XOAUTH2"); client.Authenticate(GetString(Resource.String.GDSSEMailAccount), GetString(Resource.String.GDSSEMailPwd)); var emails = new List <EmailObject>(); DBManagerHelper dbmgr = new DBManagerHelper(this); DatabaseUpdates tblEmail = new DatabaseUpdates(); //var tblEmail = new EmailEntity(); //Toast.MakeText(this, "Email Sync: Downloading Emails", ToastLength.Long).Show(); //for testing purpose only / clearing of table. if (int.Parse(GetString(Resource.String.TestDeleteEmailsOn)) == 1) { tblEmail.ClearMail(); } for (int i = client.Count - 1; i >= 0; i--) { var message = new MimeMessage(); try { message = client.GetMessage(i); } catch (Exception ex) { Console.WriteLine(ex.Source + " || " + ex.Message); } if (!tblEmail.IsEmailExist(message.MessageId)) { var curemail = new EmailObject(message.MessageId, message.From.ToString(), message.Subject, message.TextBody, message.Cc.ToString(), DateTime.Parse(message.Date.ToString())); try { tblEmail.AddEmail(new EmailEntity { EmailID = curemail.EmailID ?? "0", EmailFrom = curemail.From, EmailCC = curemail.CC, EmailDate = curemail.date, EmailSubject = curemail.Subject, EmailBody = curemail.Body }); } catch (Exception ex) { Console.WriteLine(ex.Source + "||" + ex.Message); } } } client.Disconnect(true); dbmgr.Close(); } }
/// <summary> /// Metodo que descarga los correos del Servicio de correo que pertenecen a la cuenta <paramref name="pCuenta"/>. /// </summary> /// <param name="pCuenta">Cuenta de la cual se descargan los correos.</param> /// <returns>Retorna una lista de correos.</returns> public override IList <CorreoDTO> DescargarCorreos(CuentaDTO pCuenta) { Pop3Client pop = new Pop3Client(); OpenPop.Mime.Message mensaje; List <CorreoDTO> mCorreos = new List <CorreoDTO>(); try { pop.Connect("pop.mail.yahoo.com", 995, true); pop.Authenticate(pCuenta.Direccion, pCuenta.Contraseña); int cantidadMensajes = pop.GetMessageCount(); for (int i = cantidadMensajes; i > 0; i--) { mensaje = pop.GetMessage(i); // obtengo el texto del cuerpo del correo. string cuerpo = ""; OpenPop.Mime.MessagePart texto = mensaje.FindFirstPlainTextVersion(); if (texto != null) { // We found some plaintext! cuerpo = texto.GetBodyAsText(); } else { // Might include a part holding html instead OpenPop.Mime.MessagePart html = mensaje.FindFirstHtmlVersion(); if (html != null) { // We found some html! cuerpo = html.GetBodyAsText(); } } string pTipoCorreo; // Determina si el correo es enviado o recibido comparando la direccion de la cuenta con la direccion // que aparece como direccion remitente. if (mensaje.Headers.From.Address == pCuenta.Direccion) { pTipoCorreo = "Enviado"; } else { pTipoCorreo = "Recibido"; } // Armar el string de cuenta destino con las cuentas destinatarias. string pDestino = ""; foreach (OpenPop.Mime.Header.RfcMailAddress mailAdres in mensaje.Headers.To) { pDestino = pDestino + mailAdres.Address + "; "; } mCorreos.Add(new CorreoDTO() { Fecha = mensaje.Headers.DateSent, TipoCorreo = pTipoCorreo, Texto = cuerpo, CuentaOrigen = mensaje.Headers.From.Address, CuentaDestino = pDestino, Asunto = mensaje.Headers.Subject, Leido = false, ServicioId = mensaje.Headers.MessageId }); } } catch (OpenPop.Pop3.Exceptions.InvalidLoginException exeption) // Excepcion que se lanza cuando hay un problema con los datos del usuario y no se puede realizar el login { throw new ServicioCorreoException("No se pudo actualizar la cuenta " + pCuenta.Direccion + ". Hubo un problema en el acceso a la cuenta. Revise sus datos y vuelva a intentarlo.", exeption); } catch (OpenPop.Pop3.Exceptions.PopServerNotFoundException exeption) // Excepcion que se lanza al no poder conectarse con el servidor { throw new ServicioCorreoException("No se pudo actualizar la cuenta " + pCuenta.Direccion + ". Hubo un error de acceso al servidor. Revise su conexion o intentelo más tarde.", exeption); } catch (Exception exeption) { throw new ServicioCorreoException("No se pudo actualizar la cuenta " + pCuenta.Direccion + ". ", exeption); } return(mCorreos); }
/// <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); } } }
private void TimerElapsed(object sender, ElapsedEventArgs e) { const string hostelastic = "http://172.17.1.88:9200"; string hostName = "172.17.1.41"; int port = 110; bool useSsl = false; string userName = "******"; string password = "******"; using (var client = new Pop3Client()) { client.Connect(hostName, port, useSsl); client.Authenticate(userName, password); for (int i = 4; i < client.Count; i++) { var uID = client.GetMessageUid(i); var message = client.GetMessage(i); var subject = message.Subject; var addrfrom = message.From; // MessageBox.Show(message.TextBody.Trim()); var excerpt = ""; if (message.TextBody == null) { excerpt = message.HtmlBody.Trim(); } else { excerpt = message.TextBody.Trim(); } var cid = ""; var match = Regex.Match(excerpt, "Emmarescid###(.*)###"); cid = match.Groups[1].Value; // Campaign ID excerpt = Regex.Replace(excerpt, @"\r\n?|\n", " "); excerpt = Regex.Replace(excerpt, "Č", "Č"); excerpt = Regex.Replace(excerpt, "‌", ""); /*string pattern0 = "(?<= style)(.*)(?= style)"; * Regex rgx0 = new Regex(pattern0); * excerpt = rgx0.Replace(excerpt, "");*/ string pattern0s = "<script(?:\r|\n|.)+</script>"; Regex rgx0s = new Regex(pattern0s); excerpt = rgx0s.Replace(excerpt, ""); string pattern0 = "<style(?:\r|\n|.)+</style>"; Regex rgx0 = new Regex(pattern0); excerpt = rgx0.Replace(excerpt, ""); string pattern = "<[^<>]+>"; // string pattern = "<[^>]*> "; Regex rgx = new Regex(pattern); excerpt = rgx.Replace(excerpt, ""); string pattern2 = "{[^{}]+}"; Regex rgx2 = new Regex(pattern2); excerpt = rgx2.Replace(excerpt, ""); excerpt = rgx2.Replace(excerpt, ""); string pattern3 = "#.*? "; Regex rgx3 = new Regex(pattern3); excerpt = rgx3.Replace(excerpt, ""); /* string pattern4 = "\\..*? "; * Regex rgx4 = new Regex(pattern4); * excerpt = rgx4.Replace(excerpt, "");*/ excerpt = Regex.Replace(excerpt, "<", " "); excerpt = Regex.Replace(excerpt, ">", " "); excerpt = Regex.Replace(excerpt, "/", " "); // excerpt = Regex.Replace(excerpt, "\\\\<*>", " "); // excerpt = Regex.Replace(excerpt, ">", " "); excerpt = Regex.Replace(excerpt, "\"", "'"); excerpt = Regex.Replace(excerpt, @"\t", " "); excerpt = Regex.Replace(excerpt, @"\r", " "); excerpt = Regex.Replace(excerpt, @"\s+", " "); subject = Regex.Replace(subject, "\"", "'"); subject = Regex.Replace(subject, @"\t", " "); float score = 0.0F; var messageId = message.MessageId; var preview = message.TextBody; var campaignname = "nocampaignname"; var descriptionofcampaign = "nodescriptionofcampaign"; var publisher = "nopublisher"; var fieldofinterests = "fieldofinterests"; var region = "noregion"; var contenttype = "nocontenttype"; var optin = ""; var optout = ""; var affiliatelink = ""; var enddate = message.To.ToString(); string[] enddate1 = enddate.Split(new string[] { "-enddate-" }, StringSplitOptions.None); //[email protected] string[] enddate2 = enddate1.Length > 1 ? enddate1[1].Split(new string[] { "@emmares" }, StringSplitOptions.None) : new string[] { DateTime.Today.AddYears(2).ToString("yyyy-MM-dd") }; //enddate = 2 leti od dneva vpisa enddate = enddate2[0]; //"2019-12-09"; string content = !string.IsNullOrEmpty(message.HtmlBody) ? message.HtmlBody : message.TextBody; //addr "n" <*****@*****.**> -> [email protected] // string addrfrom2 = addrfrom.ToString(); if (addrfrom2.Contains("<")) { string[] addrsplit = addrfrom2.Split('<'); addrfrom2 = addrsplit[1]; addrfrom2 = addrfrom2.Replace(">", ""); } if (cid != "") { WebClient savetodb = new WebClient(); try { var addressuri = "https://emmares.com/SearchAPI/SaveToDB?"; var datacidaddr = "CampaignID=" + cid + "&Sender_Email=" + addrfrom2; //string method = "POST"; savetodb.DownloadString(addressuri + datacidaddr); } catch (Exception ex) { if (!ex.Message.ToLower().Contains("violation")) { } } } // string mailelastic = ""; /*WebClient wc = new WebClient(); * try * { mailelastic = wc.DownloadString(hostelastic + "/blacklist/_search?q=" + addrfrom.ToString() + "&filter_path=hits.hits._source.query.term.email"); } * catch { mailelastic = "Do not use \", (, ), : and other special characters"; }*/ string json = "{\"query\": {\"term\": {\"email\": \"" + addrfrom2 + "\" }}}"; WebClient wc2 = new WebClient(); wc2.Headers.Add("Content-Type", "application/json"); try { mailelastic = wc2.UploadString(hostelastic + "/blacklist/_search?", json); } catch { mailelastic = "Error"; } string mailelastic2 = ""; string jsonw = "{\"query\": {\"term\": {\"email\": \"" + addrfrom2 + "\" }}}"; WebClient wc3 = new WebClient(); wc3.Headers.Add("Content-Type", "application/json"); try { mailelastic2 = wc3.UploadString(hostelastic + "/whitelist/_search?", json); } catch { mailelastic2 = "Error"; } try { var xblacklist = Newtonsoft.Json.JsonConvert.DeserializeObject(mailelastic); var emailclass = new Emailclass(); emailclass = JsonConvert.DeserializeObject <Emailclass>(mailelastic); if (emailclass.Hits.Total != 0) { // MessageBox.Show("ta mail je na blacklisti " + emailclass.Hits.HitsHits[0]?.Source.Email.ToString()); //.Query.Term.Email.ToString()); DeleteMessageByUID(uID); } else { // MessageBox.Show(Regex.Replace(excerpt, @"\r\n?|\n", " ")); try { var xwhitelist = Newtonsoft.Json.JsonConvert.DeserializeObject(mailelastic2); var emailclass2 = new Emailclass(); emailclass2 = JsonConvert.DeserializeObject <Emailclass>(mailelastic2); string todaysdate = DateTime.Today.ToString("yyyy-MM-dd"); var htmlDoc = new HtmlDocument(); htmlDoc.LoadHtml(content); var htmlNodes = htmlDoc.DocumentNode.SelectNodes("//a"); if (htmlNodes != null) { for (int i2 = htmlNodes.Count - 1; i2 >= 0; --i2) { if (htmlNodes[i2].InnerHtml.ToLower().Contains("unsubscribe") || htmlNodes[i2].InnerHtml.ToLower().Contains("opt out") || htmlNodes[i2].InnerHtml.ToLower().Contains("subscription") || htmlNodes[i2].InnerHtml.ToLower().Contains("naročnine") || htmlNodes[i2].InnerHtml.ToLower().Contains("odjavi") || htmlNodes[i2].InnerHtml.ToLower().Contains("subscriber options") || htmlNodes[i2].InnerHtml.ToLower().Contains("uredi profil") || htmlNodes[i2].InnerHtml.ToLower().Contains("manage email preferences") || htmlNodes[i2].InnerHtml.ToLower().Contains("posodobi želje")) { htmlNodes[i2].InnerHtml = " "; } } } using (StringWriter writer = new StringWriter()) { htmlDoc.Save(writer); content = writer.ToString(); } Regex r5 = new Regex(@"(?i)unsubscribe.*?</a>"); content = r5.Replace(content, " "); Regex r6 = new Regex(@"(?i)opt out.*?</a>"); content = r6.Replace(content, " "); Regex r7 = new Regex(@"(?i)subscription.*?</a>"); content = r7.Replace(content, " "); Regex r8 = new Regex(@"(?i)odjavi.*?</a>"); content = r8.Replace(content, " "); Regex r11 = new Regex(@"publish.*[email protected]"); content = r11.Replace(content, ""); Regex r12 = new Regex(@"(?i)uredi profil.*?</a>"); content = r12.Replace(content, " "); Regex r13 = new Regex(@"(?i)posodobi želje .*?</a>"); content = r13.Replace(content, " "); Regex r14 = new Regex(@"(?i)manage email preferences.*?</a>"); content = r14.Replace(content, " "); if (!addrfrom.ToString().Contains("@emmares")) { Regex r9 = new Regex(@"Emmares Emmares"); content = r9.Replace(content, "Reader"); Regex r10 = new Regex(@"Emmares"); content = r10.Replace(content, "Reader"); } if (emailclass2.Hits.Total != 0 && emailclass2.Hits.HitsHits[0].Source?.Publish == "true") { // MessageBox.Show("ta mail je na whitelisti " + emailclass2.Hits.HitsHits[0]?.Source.Email.ToString()); //.Query.Term.Email.ToString()); //upload to elasticsearch if (emailclass2.Hits.HitsHits[0].Source?.Duration != null) { enddate = DateTime.Today.AddDays(Convert.ToDouble(emailclass2.Hits.HitsHits[0].Source?.Duration)).ToString("yyyy-MM-dd"); } //MessageBox.Show("main enddate " + enddate); // MessageBox.Show(emailclass2.Hits.HitsHits[0].Source.Email + " o " + emailclass2.Hits.HitsHits[0].Source.Optin + " p " + emailclass2.Hits.HitsHits[0].Source.Publish); string jsonbody = "{ \"subject\" : \"" + subject + "\", \"addrfrom\" : \"" + addrfrom2 + "\", \"excerpt\" : \"" + excerpt + "\", \"score\" : \"0.0\", \"messageid\" : \"" + messageId + "\", \"preview\" : \"!!!preview!!!\", \"campaignname\" : \"Campaign name\", \"descriptionofcampaign\" : \"Description of campaign\", \"publisher\" : \"publisher1\", \"fieldofinterest\" : \"News\", \"region\" : \"Europe\", \"contenttype\" : \"Newsletter\", \"optin\" : \"" + emailclass2.Hits.HitsHits[0]?.Source.Optin + "\", \"optout\" : \"" + emailclass2.Hits.HitsHits[0]?.Source.Optout + "\", \"affiliatelink\" : \"" + emailclass2.Hits.HitsHits[0]?.Source.Affiliatelink + "\", \"enddate\" : \"" + enddate + "\", \"date\" : \"" + todaysdate + "\" } "; WebClient wc4 = new WebClient(); wc4.Encoding = Encoding.UTF8; wc4.Headers.Add("Content-Type", "application/json"); try { wc4.UploadString(hostelastic + "/emmares_search_test/_doc", jsonbody); //delete from pop DeleteMessageByUID(uID); string potdomaila = "C:/inetpub/wwwroot/App_Data/pages/"; System.IO.File.WriteAllText(potdomaila + messageId + ".html", content, Encoding.UTF8); } catch (Exception ex) { throw new NotImplementedException(); string logerror = "C:/inetpub/wwwroot/App_Data/errors/"; System.IO.File.WriteAllText(logerror + messageId + ".txt", jsonbody, Encoding.UTF8); } } } catch { i++; } } } catch { i++; } } } }
/// <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); } }
public static List <MsgSummary> GetMail(string hostname, int port, string useSsl, string username, string password) { int messageCount = 0; String fromMail = ""; String subject = ""; bool ssl = false; switch (useSsl) { case "none": ssl = false; break; case "SSL": ssl = true; break; case "TLS": ssl = true; break; } List <MsgSummary> allMessages = new List <MsgSummary>(); Pop3Client client = new Pop3Client(); try { client.Connect(hostname, port, ssl); if (client.Connected) { client.Authenticate(username, password); } messageCount = client.GetMessageCount(); if (messageCount > 0) { for (int i = messageCount; i > 0; i--) { if (client.GetMessage(i) != null) { OpenPop.Mime.Message msg = client.GetMessage(i); MsgSummary newSumm = new MsgSummary(); try { if (msg.Headers.From.MailAddress.Address != null && msg.Headers.From.MailAddress.Address != "") { fromMail = msg.Headers.From.MailAddress.Address; } if (msg.Headers.Subject != null && msg.Headers.Subject != "") { subject = msg.Headers.Subject; } List <MsgAtt> att = new List <MsgAtt>(); foreach (OpenPop.Mime.MessagePart attach in msg.FindAllAttachments()) { string file_name_attach = attach.FileName; if (attach.FileName != "(no name)") { FileInfo fi = new FileInfo(Path.Combine(Globals.TempPath, file_name_attach)); int ij = 0; string sName = fi.Name; string sExt = fi.Extension; while (File.Exists(sName)) { sName = fi.Name + ij.ToString() + sExt; ij++; } fi = new FileInfo(Path.Combine(Globals.TempPath, sName)); att.Add(new MsgAtt() { AttFilename = fi }); attach.Save(fi); } } newSumm.MsgFile = att; newSumm.MsgFrom = fromMail; newSumm.MsgSubject = subject; newSumm.MsgStatus = "Ok"; newSumm.MsgId = i; } catch (Exception exAtt) { // Program.AddRTBText(rtbStatus, string.Format("{0:g} ", DateTime.Now) + " Error Retrieving Email message " + i.ToString() + " of " + messageCount.ToString()+ " Error was: " + exAtt.Message + Environment.NewLine, Color.Red); newSumm.MsgStatus = exAtt.Message; } finally { allMessages.Add(newSumm); } } } } } catch (Exception ex) { MsgSummary newSumm = new MsgSummary(); newSumm.MsgStatus = ex.Message; allMessages.Add(newSumm); } finally { try { client.Disconnect(); } catch (Exception ex) { } } return(allMessages); }
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"); } }
private void ReceiveMails() { //取得昨天的日期 string v_yesterday = DateTime.Now.AddDays(-2).ToString("yyyy/MM/dd"); //取得今天的日期 string v_today = DateTime.Now.AddHours(-6).ToString("yyyy/MM/dd"); // Disable buttons while working connectAndRetrieveButton.Enabled = false; //uidlButton.Enabled = false; progressBar.Value = 0; string v_sender, v_mailTo, v_subject, v_attachment; //讀取CRM_SALES_EMAIL 帳號、密碼 //EMP_NO 0, EMP_NAME 1, EMAIL_ADDR 2, LOGIN_ID 3, PASSWORD 4 OleDbDataReader dr2 = GetDr(); //沒有EMAIL清單,就跳出 if (!dr2.HasRows) { return; } try { totalSuccess = 0; while (dr2.Read()) { if (pop3Client.Connected) { pop3Client.Disconnect(); } pop3Client.Connect(popServerTextBox.Text, int.Parse(portTextBox.Text), useSslCheckBox.Checked); pop3Client.Authenticate(dr2[3].ToString(), dr2[4].ToString()); int count = pop3Client.GetMessageCount(); counterLabel.Text = count.ToString(); IDlabel.Text = dr2[3].ToString(); nameLabel.Text = dr2[1].ToString(); messages.Clear(); mailListTB.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); success++; //寄件者 v_sender = message.Headers.From.ToString().Replace("'", ""); if (v_sender.Trim().Equals("")) { v_sender = "no sender"; } if (v_sender.Length > 200) { v_sender = v_sender.Substring(0, 200); } //收件者資料 v_mailTo = ""; foreach (RfcMailAddress to in message.Headers.To) { if (v_mailTo.Trim().Equals("")) { v_mailTo = to.ToString(); } else { v_mailTo += ";" + to.ToString(); } } v_mailTo = v_mailTo.Replace("'", ""); if (v_mailTo.Equals("")) { v_mailTo = "no recevie"; } if (v_mailTo.Length > 100) { v_mailTo = v_mailTo.Substring(0, 100); } //主旨 v_subject = Regex.Replace(message.Headers.Subject, @"<[^>]*>", "NO SUBJECT"); v_subject = v_subject.Replace("'", "").Replace("&", " and "); if (v_subject.Trim().Equals("")) { v_subject = "no subject"; } if (v_subject.Length > 500) { v_subject = v_subject.Substring(0, 500); } //附件資料 v_attachment = ""; List <MessagePart> attachments = message.FindAllAttachments(); foreach (MessagePart attachment in attachments) { if (v_attachment.Equals("")) { v_attachment = attachment.FileName; } else { v_attachment += ";" + attachment.FileName; } } if (v_attachment.Length > 200) { v_attachment = v_attachment.Substring(0, 200); } //v_attachment = v_attachment.Replace("'", ""); bool hadAttachments = attachments.Count > 0; if (hadAttachments == false) { v_attachment = ""; } //接收日 string v_receiveDate = message.Headers.DateSent.ToString("yyyy/MM/dd"); //比對日期,今天的郵件才寫入資料庫 DateTime recevDate = DateTime.ParseExact(v_receiveDate, "yyyy/MM/dd", System.Globalization.CultureInfo.InvariantCulture); DateTime beforeDate = DateTime.ParseExact(v_yesterday, "yyyy/MM/dd", System.Globalization.CultureInfo.InvariantCulture); if (recevDate >= beforeDate) //if (v_recevice_date.Equals(v_today)) { //寫入資料庫 //檢查是否已有資料 if (chk_data_exist(v_sender, v_mailTo, v_subject, v_receiveDate)) { bool v_flag = insertDB(dr2[0].ToString(), dr2[1].ToString(), v_sender, v_mailTo, v_subject, v_attachment, v_receiveDate); //有成功寫入資料庫才紀錄 if (v_flag) { totalSuccess++; mailListTB.Text += dr2[1].ToString() + "," + v_sender + "," + v_subject + "," + v_receiveDate + "\r\n"; } } } counter2Label.Text = success.ToString(); counter3Label.Text = totalSuccess.ToString(); } catch (Exception e) { //工號、姓名、帳號、密碼、郵件編號 HeadersFromAndSubject(dr2[0].ToString(), dr2[1].ToString(), dr2[3].ToString(), dr2[4].ToString(), i); //errorTB.Text += "sn:"+i.ToString()+","+e.Message + "\r\n"; DefaultLogger.Log.LogError( "TestForm: Message fetching failed: " + e.Message + "\r\n" + "Stack trace:\r\n" + e.StackTrace); fail++; System.Threading.Thread.Sleep(100); } progressBar.Value = (int)(((double)(count - i) / count) * 100); counter4Label.Text = fail.ToString(); } //MessageBox.Show(this, "Mail received!\nSuccesses: " + success + "\nFailed: " + fail, "Message fetching done"); //counter3Label.Text = fail.ToString(); } } catch (InvalidLoginException) { errorTB.Text += "POP3 Server Authentication:The server did not accept the user credentials!\r\n"; //MessageBox.Show(this, "The server did not accept the user credentials!", "POP3 Server Authentication"); } catch (PopServerNotFoundException) { errorTB.Text += "POP3 Retrieval。The server could not be found.\r\n"; //MessageBox.Show(this, "The server could not be found", "POP3 Retrieval"); } catch (PopServerLockedException) { errorTB.Text += "POP3 Account Locked。The mailbox is locked. It might be in use or under maintenance. Are you connected elsewhere?\r\n"; //MessageBox.Show(this, "The mailbox is locked. It might be in use or under maintenance. Are you connected elsewhere?", "POP3 Account Locked"); } catch (LoginDelayException) { errorTB.Text += "POP3 Account Login Delay。Login not allowed. Server enforces delay between logins. Have you connected recently?\r\n"; //MessageBox.Show(this, "Login not allowed. Server enforces delay between logins. Have you connected recently?", "POP3 Account Login Delay"); } catch (Exception) { errorTB.Text += "POP3 Retrieval。Error occurred retrieving mail.\r\n "; //MessageBox.Show(this, "Error occurred retrieving mail. " + e.Message, "POP3 Retrieval"); } finally { dr2.Close(); conn.Close(); toolStripStatusLabel1.Text = "掃描已結束:" + DateTime.Now.ToString("hh:mm:ss"); // Enable the buttons again connectAndRetrieveButton.Enabled = true; //uidlButton.Enabled = true; progressBar.Value = 100; } }
private void BkWorkerOnDoWork(object sender, DoWorkEventArgs e) { SetControlText(lblMailAddr, String.Format("{0}", _config.Email)); if (!String.IsNullOrEmpty(_config.MarkUp)) { SetControlText(lblFilter, String.Format("过滤规则:主题中包含“{0}”的邮件。", _config.MarkUp)); } try { if (_bkWorker.CancellationPending) { e.Cancel = true; return; } ConnectPopClient(_config); var count = _pop3Client.Count; var lastTime = MailCore.MF.MessageToMf.GetLastTimeFromMail(_vault); for (int i = count - 1; i >= 0; i--) { if (IsDisposed) { return; } var str = String.Empty; try { //获取邮件成功 var messge = _pop3Client.GetMessage(i); if (messge.Date.DateTime > lastTime) { switch (SaveMessages(messge)) { case -1: str = String.Format("正在获取邮件...({0} of {1}) 保存邮件失败.", count - i, count); break; case 0: str = String.Format("正在获取邮件...({0} of {1}) 获取成功.", count - i, count); break; case 1: str = String.Format("正在获取邮件...({0} of {1}) 主题不符合规则.", count - i, count); break; } } else { i = 1; break; } } catch (Exception ex) { str = String.Format("正在获取邮件...({0} of {1}) 获取失败.", count - i, count); } SetControlText(lblStatus, str); _bkWorker.ReportProgress((int)(((double)(count - i) / count) * 100)); } _result = string.Format("任务完成!"); } catch (Exception ex) { _result = ex.Message; } _bkWorker.ReportProgress(100); }
//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"); } }
//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) { } }
/// <summary> /// Récupère les nouveaux Messaegs du serveur de Mails POP3 dont les informations de /// connextion sont indiqués dans le paramètre /// </summary> /// <param name="parametre">Parametres de connexion au serveur de mails POP3</param> /// <returns>Le Data du Result contient un liste de MailMessageEx</returns> public CResultAErreur RetrieveMails(CCompteMail compteMail) { CResultAErreur result = CResultAErreur.True; if (compteMail == null) { result.EmpileErreur("Erreur dans CRecepteurMail: compteMail est nul"); } m_compteMail = compteMail; m_compteMail.BeginEdit(); m_compteMail.DateDernierReleve = DateTime.Now; CParametreCompteMail parametre = compteMail.ParametreCompteMail; if (parametre == null) { result.EmpileErreur("Erreur dans CRecepteurMail: Le ¨Parametre de compte est nul"); return(result); } using (Pop3Client client = new Pop3Client()) { try { client.Connect(parametre.PopServer, parametre.PopPort, parametre.UseSsl); // Authenticate ourselves towards the server client.Authenticate(parametre.User, parametre.Password); // Get the number of messages in the inbox int messageCount = client.GetMessageCount(); // Messages are numbered in the interval: [1, messageCount] // Ergo: message numbers are 1-based. for (int i = 1; i <= messageCount; i++) { MessageHeader messageHead = client.GetMessageHeaders(i); Message messageRecu = null; CTracabiliteMail traceMail = new CTracabiliteMail(m_compteMail.ContexteDonnee); CFiltreData filtreIfExist = new CFiltreData( CTracabiliteMail.c_champMessageUid + " = @1 and " + CCompteMail.c_champId + " = @2 ", messageHead.MessageId, compteMail.Id); if (!traceMail.ReadIfExists(filtreIfExist)) { try { C2iMail mail = new C2iMail(compteMail.ContexteDonnee); mail.CreateNewInCurrentContexte(); mail.CompteMail = m_compteMail; if (parametre.HeaderOnly) { mail.FillFromHeader(messageHead); } else { messageRecu = client.GetMessage(i); mail.FillFromMessage(messageRecu); } } catch (Exception ex) { result.EmpileErreur(ex.Message); } } if (parametre.SupprimerDuServeur) { if (parametre.DelaiSuppression <= 0) { client.DeleteMessage(i); } else { DateTime dateMessage = messageHead.DateSent; TimeSpan dureeDeVie = DateTime.Now - dateMessage; if (dureeDeVie.Days >= parametre.DelaiSuppression) { client.DeleteMessage(i); } } } } } catch (Exception exception) { result.EmpileErreur(exception.Message); } finally { client.Disconnect(); } } if (!result) { m_compteMail.LastErreur = result.MessageErreur; } else { m_compteMail.LastErreur = I.T("Mails succesfully retrived|10000"); } result += m_compteMail.CommitEdit(); return(result); }