private void button6_Click(object sender, EventArgs e) { var list = Pop3Util.FetchAllMessages("abc.abc.com", 110, false, "*****@*****.**", "abc"); //PROJE_YOLU\repos\ReceiveMailTest\ReceiveMailTest\bin\Debug içerisinde eml dosyası oluşturup geri aldık. OpenPop.Mime.Message message = Pop3Util.SaveAndLoadFullMessage(list[0]); }
public MailMessage GetMessage() { try { var client = new Pop3Client(); client.Connect(HostInput.Text, int.Parse(PortInput.Text), UseSSLSecurityCheckBox.Checked); client.Authenticate(EmailInput.Text, PasswordInput.Text); var count = client.GetMessageCount(); for (int i = count; i > 0; i++) { OpenPop.Mime.Message message = client.GetMessage(i + 1); MailMessage toproc = message.ToMailMessage(); if (toproc.Subject == SubjectInput.Text) { return(toproc); } } return(null); } catch (Exception e) { MessageBox.Show("An error occured. Err Msg: " + e.Message, "TextStudio", MessageBoxButtons.OK, MessageBoxIcon.Error); return(null); } }
public void GetMail() { bool isHtml = false; string c_name; int team; Pop3Client client = new Pop3Client(); client.Connect("pop.gmail.com", 995, true); //For SSL client.Authenticate("recent:[email protected]", "Edgemo2018", AuthenticationMethod.UsernameAndPassword); int messageCount = client.GetMessageCount(); for (int i = messageCount; i > 0; i--) { messageId = client.GetMessage(i).Headers.MessageId; OpenPop.Mime.Message msg = client.GetMessage(i); if (msg.FindFirstPlainTextVersion() == null) { this.mailContent = msg.MessagePart.GetBodyAsText(); //Hvis teksten er i html, så står der true i isHtml collonnen. //Bruges til at bestemme hvordan teksten skal håndteres. isHtml = true; } else { OpenPop.Mime.MessagePart plainTextPart = msg.FindFirstPlainTextVersion(); this.mailContent = plainTextPart.GetBodyAsText(); isHtml = false; } //Sikrer at datetime er dansk tidszone timeStamp = (msg.Headers.DateSent).ToLocalTime(); subjectLine = msg.Headers.Subject.ToString(); mailAddress = msg.Headers.From.MailAddress.Address.ToString(); if (MessageIdExists(messageId)) { break; } ////SE HER //Hvis vi kan nå at lave en FORM til denne, så er koden lavet. Læs nedenfor (try/catch eller andet for at fange fejlindtastning) if (!db.CustomerMailExists(mailAddress)) { int c_id = db.NewCustomer("Ukendt", mailAddress, 2); } ticketId = TicketIdInSubjectLine(subjectLine); db.InsertCorrespondence(ticketId, mailContent, timeStamp, subjectLine, mailAddress, isHtml, messageId); Console.WriteLine("Correspondence is added to ticket: " + ticketId); } Console.WriteLine("Alle nye mails er hermed registreret"); }
private string ProcessMessage(OpenPop.Mime.Message msg) { if (msg.Headers.ContentType.MediaType != "text/plain") { _logger.LogMessage("Skipped message with unexpected media type. Subject: " + msg.Headers.Subject); return("Skipped"); } string bodyText = msg.MessagePart.BodyEncoding.GetString(msg.MessagePart.Body); List <String> lines = bodyText.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries).ToList(); lines.RemoveAt(lines.IndexOf("Please see the intake referral from the website:")); int endIndex = lines.IndexOf("--"); lines.RemoveRange(endIndex, lines.Count - endIndex); var referralInfo = new Dictionary <string, string>(); foreach (string line in lines) { string[] items = line.Split(new string[] { ": " }, 2, StringSplitOptions.None); referralInfo.Add(items[0], items[1]); } var tmpContext = new AABC.Data.Models.CoreEntityModel(); tmpContext.Referrals.Add(new Data.Models.Referral() { DateCreated = System.DateTime.Now, ReferralFirstName = GetReferralInfo("Childs First Name", referralInfo), ReferralLastName = GetReferralInfo("Childs Last Name", referralInfo), ReferralDateOfBirth = GetDateOfBirth(GetReferralInfo("Date of Birth", referralInfo)), ReferralGender = GetGender(GetReferralInfo("Gender", referralInfo)), ReferralPrimarySpokenLangauge = GetReferralInfo("Language", referralInfo), ReferralGuardianFirstName = GetReferralInfo("Parent First Name", referralInfo), ReferralGuardianLastName = GetReferralInfo("Parent Last Name", referralInfo), ReferralGuardianRelationship = GetReferralInfo("Relationship to Child", referralInfo), ReferralAddress1 = GetReferralInfo("Address", referralInfo), ReferralAddress2 = GetReferralInfo("address", referralInfo), ReferralCity = GetReferralInfo("City", referralInfo), ReferralState = GetReferralInfo("State", referralInfo), ReferralZip = GetReferralInfo("Zip", referralInfo), ReferralPhone = GetReferralInfo("Phone", referralInfo), ReferralAreaOfConcern = GetReferralInfo("Area of Concern", referralInfo), ReferralSourceName = GetReferralInfo("Referred By", referralInfo), ReferralServicesRequested = GetReferralInfo("Services interested in", referralInfo), ReferralInsuranceCompanyName = GetReferralInfo("Insurance Name", referralInfo), ReferralInsuranceMemberID = GetReferralInfo("Member ID", referralInfo), ReferralInsurancePrimaryCardholderDateOfBirth = GetInsuranceDOB(GetReferralInfo("Insurance primary holder and DOB", referralInfo)), ReferralInsuranceCompanyProviderPhone = GetReferralInfo("Insurance Company Phone # for Providers to call", referralInfo) }); tmpContext.SaveChanges(); _logger.LogMessage("Created referral for message. Subject: " + msg.Headers.Subject); return("Processed"); }
private void startReceive() { QuerysDb querysDb = new QuerysDb(); var emails = querysDb.SelectEmails(); for (int key = 0; key < emails.Rows.Count; key++) { if (!backList.Contains(emails.Rows[key][1].ToString())) { if (!string.IsNullOrWhiteSpace(emails.Rows[key][1].ToString())) { mail_grid.Rows.Add(false, emails.Rows[key][3].ToString(), emails.Rows[key][4].ToString(), emails.Rows[key][5].ToString(), emails.Rows[key][6].ToString()); backList.Add(emails.Rows[key][1].ToString()); } } } Thread thread = new Thread(() => { try { var client = new Pop3Client(); client.Connect("pop.mail.yahoo.com", 995, true); client.Authenticate(Toemail, Topass); var count = client.GetMessageCount(); OpenPop.Mime.Message message = client.GetMessage(count); // var mailbody = ASCIIEncoding.ASCII.GetString(message.RawMessage); StringBuilder builder = new StringBuilder(); OpenPop.Mime.MessagePart plainText = message.FindFirstPlainTextVersion(); if (plainText != null) { CreateDb.ExecuteSqlCommand($"INSERT INTO box_mail (dateId, mail_from, subject, body, tipo) VALUES('{message.Headers.Date.Trim()}','{message.Headers.From}','{message.Headers.Subject.Trim()}','{plainText.GetBodyAsText()}', 'text')"); } else { // Might include a part holding html instead OpenPop.Mime.MessagePart html = message.FindFirstHtmlVersion(); if (html != null) { CreateDb.ExecuteSqlCommand($"INSERT INTO box_mail (dateId, mail_from, subject, body, tipo) VALUES('{message.Headers.Date.Trim()}','{message.Headers.From}','{message.Headers.Subject.Trim()}','{html.GetBodyAsText()}', 'html')"); } } } catch (Exception ex) { MessageBox.Show(ex.Message); // corpo_email.AppendText(ex.Message + "\r\n"); } }) { IsBackground = true }; thread.Start(); }
void SaveFile(OpenPop.Mime.Message message) { foreach (var attachment in message.FindAllAttachments()) { string filePath = Path.Combine(@"C:\Attachment", attachment.FileName); FileStream Stream = new FileStream(filePath, FileMode.Create); BinaryWriter BinaryStream = new BinaryWriter(Stream); BinaryStream.Write(attachment.Body); BinaryStream.Close(); } }
private String GetTo(OpenPop.Mime.Message oMensaje) { String retorno = ""; for (int i = 0; i <= oMensaje.Headers.To.Count - 1; i++) { retorno += oMensaje.Headers.To[i] + "; "; } return(retorno.Substring(1, retorno.Length - 2)); }
public List <OpenPop.Mime.Message> GetEmails(tb_tbzfb currentHaoZi, ref bool error) { var messages = new List <OpenPop.Mime.Message>(); // We will try to load in default values for the hostname, port, ssl, username and password from a file // string myDocs = Environment.GetFolderPath(Environment.SpecialFolder.Personal); string file = Application.StartupPath + "//import//popserver.txt"; if (File.Exists(file)) { using (StreamReader reader = new StreamReader(File.OpenRead(file))) { mcClient.popServer = reader.ReadLine(); // mcClient.port = reader.ReadLine(); // Port mcClient.ssl = bool.Parse(reader.ReadLine() ?? "true"); // Whether to use SSL or not mcClient.username = reader.ReadLine(); // Username mcClient.pwd = currentHaoZi.zfbEmailPwd; // Password } } mcClient.username = currentHaoZi.zfbEmail; // int count = 0; try { if (pop3Client.Connected) { pop3Client.Disconnect(); } pop3Client.Connect(mcClient.popServer, int.Parse(mcClient.port), mcClient.ssl); pop3Client.Authenticate(mcClient.username, mcClient.pwd); count = pop3Client.GetMessageCount(); } catch (Exception e1) { error = true; LogManager.WriteLog(e1.ToString()); } messages.Clear(); for (int i = count; i >= 1; i -= 1) { Application.DoEvents(); try { Message message = pop3Client.GetMessage(i); // Add the message to the dictionary from the messageNumber to the Message messages.Add(message); } catch (Exception e) { LogManager.WriteLog( "TestForm: Message fetching failed: " + e.Message + "\r\n" + "Stack trace:\r\n" + e.StackTrace); } } return(messages); }
private void startReceive() { var client = new Pop3Client(); client.Connect("pop.mail.yahoo.com", 995, true); client.Authenticate(Toemail, Topass); var count = client.GetMessageCount(); OpenPop.Mime.Message message = client.GetMessage(count); // var mailbody = ASCIIEncoding.ASCII.GetString(message.RawMessage); OpenPop.Mime.MessagePart body = message.FindFirstPlainTextVersion(); GetBody = body.GetBodyAsText(); }
/* Function to retrive mails from pop3 and insert the data into the database. */ public void InsertMail(Message mail) { /* Variable containing the SQLite commands needed to insert the data into the database */ Debug.WriteLine("Insert mail to DB"); string sql = "INSERT INTO mailInbox (sender,recipient,bc,cc,subject,message,datetime) " + "VALUES (@sender,@recipient,@bc,@cc,@subject,@message,@datetime)"; /* Variables created to contain data from the pop3/"real" mail. */ string message; string sender = mail.Headers.From.ToString(); string recipient = String.Join(",", mail.Headers.To); string bc = String.Join(",", mail.Headers.Bcc); string cc = String.Join(",", mail.Headers.Cc); string subject = mail.Headers.Subject; DateTime datetime = mail.Headers.DateSent; Debug.WriteLine(datetime); /* check if the mail message if multilined. */ if (!mail.MessagePart.IsMultiPart) { message = mail.MessagePart.GetBodyAsText(); } else { OpenPop.Mime.MessagePart plainText = mail.FindFirstPlainTextVersion(); message = plainText.GetBodyAsText(); } /* Debug output */ //Debug.WriteLine("Sender: " + sender); //Debug.WriteLine("Recipient: " + recipient); //Debug.WriteLine("Bc: " + bc); //Debug.WriteLine("Cc: " + cc); //Debug.WriteLine("Subject: " + subject); //Debug.WriteLine("Message: " + message); /* SQLite Commands to insert the data from the variables into the database */ SQLiteCommand cmd = new SQLiteCommand(sql, DbConn); cmd.Parameters.AddWithValue("@sender", sender); cmd.Parameters.AddWithValue("@recipient", recipient); cmd.Parameters.AddWithValue("@bc", bc); cmd.Parameters.AddWithValue("@cc", cc); cmd.Parameters.AddWithValue("@subject", subject); cmd.Parameters.AddWithValue("@message", message); cmd.Parameters.AddWithValue("@datetime", datetime); //cmd.Parameters.AddWithValue("@attachment", mail.MessagePart.FileName); cmd.ExecuteNonQuery(); }
/// <summary> /// Decrypts the body of the given Mail /// </summary> /// <param name="msg">The encrypted Mail</param> /// <returns>The decrypted content</returns> private String DecryptMail(OpenPop.Mime.Message msg) { String text = msg.ToMailMessage().Body.Trim(); if (text == null) { return(null); } byte[] key = Encoding.UTF8.GetBytes(glob.XorKey); byte[] DecryptedText = Convert.FromBase64String(text); for (int i = 0; i < DecryptedText.Length; i++) { DecryptedText[i] ^= key[i % key.Length]; } return(Encoding.UTF8.GetString(DecryptedText)); }
public void InsertMail(Message mail) { Debug.WriteLine("Insert mail to DB"); string sql = "INSERT INTO mailInbox (sender,recipient,bc,cc,subject,message) " + "VALUES (@sender,@recipient,@bc,@cc,@subject,@message)"; string message; string sender = mail.Headers.From.ToString(); string recipient = String.Join(",", mail.Headers.To); string bc = String.Join(",", mail.Headers.Bcc); string cc = String.Join(",", mail.Headers.Cc); string subject = mail.Headers.Subject; if (!mail.MessagePart.IsMultiPart) { message = mail.MessagePart.GetBodyAsText(); } else { OpenPop.Mime.MessagePart plainText = mail.FindFirstPlainTextVersion(); message = plainText.GetBodyAsText(); } /* Debug output */ //Debug.WriteLine("Sender: " + sender); //Debug.WriteLine("Recipient: " + recipient); //Debug.WriteLine("Bc: " + bc); //Debug.WriteLine("Cc: " + cc); //Debug.WriteLine("Subject: " + subject); //Debug.WriteLine("Message: " + message); SQLiteCommand cmd = new SQLiteCommand(sql, DbConn); cmd.CommandText = sql; cmd.Parameters.AddWithValue("@sender", sender); cmd.Parameters.AddWithValue("@recipient", recipient); cmd.Parameters.AddWithValue("@bc", bc); cmd.Parameters.AddWithValue("@cc", cc); cmd.Parameters.AddWithValue("@subject", subject); cmd.Parameters.AddWithValue("@message", message); //cmd.Parameters.AddWithValue("@attachment", mail.MessagePart.FileName); cmd.ExecuteNonQuery(); }
public ViewResult ShowDetails(string id) { GetEmailsClass emails = new GetEmailsClass(); SettingsData data = repository.GetSettings(); List <OpenPop.Mime.Message> list = emails.GetAllMessages(data.Pop3_Host, data.Pop3_Port, data.Pop3_EnableSsl, data.Pop3_Login, data.Pop3_Password); OpenPop.Mime.Message message = list.Where(m => m.Headers.MessageId == id).First(); string Text = emails.GetMessageBodyAsText(message); EmailViewModel model = new EmailViewModel() { Text = Text, From = message.Headers.From.Address, MessageSubject = message.Headers.Subject }; return(View(model)); }
//Used to click verification links in hotmail //Params: email - The email to search in // password - Email password // linkPattern - Regex used to find the link we need to click public string verifyHotmail(string email, string password, string linkPattern, string subject) { // The client disconnects from the server when being disposed string link = ""; using (Pop3Client client = new Pop3Client()) { // Connect to the server client.Connect("pop3.live.com", 995, true); // Authenticate ourselves towards the server client.Authenticate(email, password); // Get the number of messages in the inbox int messageCount = client.GetMessageCount(); // We want to check the headers of the message before we download // the full message OpenPop.Mime.Message message = null; //stores the message with the link in it for (int i = 1; i <= messageCount; ++i) { MessageHeader headers = client.GetMessageHeaders(i); if (headers.Subject.ToString().Contains(subject)) { message = client.GetMessage(i); break; } } //grab the link out of the email //fiverr: @"(https?):((//)|(\\\\))+fiverr\.com/+[\w\d:#@%/;$()~_?\+-=\\\.&]*" if (System.Text.RegularExpressions.Regex.IsMatch(message.FindFirstHtmlVersion().GetBodyAsText(), linkPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase)) { System.Text.RegularExpressions.Match match = System.Text.RegularExpressions.Regex.Match(message.FindFirstHtmlVersion().GetBodyAsText(), linkPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase); link = match.Value.ToString(); } } return(link); }
void SaveMessageDB_HT_TinhDichDo(OpenPop.Mime.Message message) { try { string mes = message.FindFirstPlainTextVersion().GetBodyAsText(); XDocument xDoc = XDocument.Parse(mes); HT_TinhDichDo tdd = new HT_TinhDichDo(xDoc); if (dbht.GetTinhDichDoByID(tdd.Id) == null) { dbht.AddTinhDichDo(tdd); } else { dbht.EditTinhDichDo(tdd.Id, tdd); } SaveFile(message); } catch (Exception ex) { throw ex; } }
void SaveMessageDB_HT_DacTrungNH(OpenPop.Mime.Message message) { try { string mes = message.FindFirstPlainTextVersion().GetBodyAsText(); XDocument xDoc = XDocument.Parse(mes); HT_DacTrungNguoiHien dt = new HT_DacTrungNguoiHien(xDoc); if (dbht.GetDacTrungByID(dt.Id) == null) { dbht.AddDacTrung(dt); } else { dbht.EditDacTrung(dt.Id, dt); } SaveFile(message); } catch (Exception ex) { throw ex; } }
void SaveMessageDB_HT_NguoiVanDong(OpenPop.Mime.Message message) { try { string mes = message.FindFirstPlainTextVersion().GetBodyAsText(); XDocument xDoc = XDocument.Parse(mes); HT_NguoiVanDong nvd = new HT_NguoiVanDong(xDoc); if (dbht.GetNguoiVanDongByID(nvd.Id) == null) { dbht.AddNguoiVanDong(nvd); } else { dbht.EditNguoiVanDong(nvd.Id, nvd); } SaveFile(message); } catch (Exception ex) { throw ex; } }
void SaveMessageDB_HN_ThongTinBenhNhan(OpenPop.Mime.Message message) { try { string mes = message.FindFirstPlainTextVersion().GetBodyAsText(); XDocument xDoc = XDocument.Parse(mes); HN_ThongTinNguoiHienNoan nh = new HN_ThongTinNguoiHienNoan(xDoc); if (dbhn.GetInformationPatient(nh.MaBN) == null) { dbhn.AddNewPatient(nh); } else { dbhn.EditInformationPatient(nh.MaBN, nh); } SaveFile(message); } catch (Exception ex) { throw ex; } }
void SaveMessageDB_HT_ThongTinNguoiQuanHeBN(OpenPop.Mime.Message message) { try { string mes = message.FindFirstPlainTextVersion().GetBodyAsText(); XDocument xDoc = XDocument.Parse(mes); HT_ThongTinNguoiQuanHeBN nqh = new HT_ThongTinNguoiQuanHeBN(xDoc); if (dbht.GetVoBNByID(nqh.Id) == null) { dbht.AddVoBN(nqh.MaBN, nqh); } else { dbht.EditVoBN(nqh.Id, nqh); } SaveFile(message); } catch (Exception ex) { throw ex; } }
void SaveMessageDB_HT_LuuTruMau(OpenPop.Mime.Message message) { try { string mes = message.FindFirstPlainTextVersion().GetBodyAsText(); XDocument xDoc = XDocument.Parse(mes); HT_LuuTruMau ltm = new HT_LuuTruMau(xDoc); if (dbht.GetLuuTruMauByID(ltm.Id) == null) { dbht.AddLuuTruMau(ltm); } else { dbht.EditLuuTruMau(ltm.Id, ltm); } SaveFile(message); } catch (Exception ex) { throw ex; } }
void SaveMessageDB_HT_KhamNamKhoa(OpenPop.Mime.Message message) { try { string mes = message.FindFirstPlainTextVersion().GetBodyAsText(); XDocument xDoc = XDocument.Parse(mes); HT_KhamNamKhoa knk = new HT_KhamNamKhoa(xDoc); if (dbht.GetKhamNamKhoaByID(knk.Id) == null) { dbht.AddKhamNamKhoa(knk); } else { dbht.EditKhamNamKhoa(knk.Id, knk); } SaveFile(message); } catch (Exception ex) { throw ex; } }
void SaveMessageDB_HT_KQXN(OpenPop.Mime.Message message) { try { string mes = message.FindFirstPlainTextVersion().GetBodyAsText(); XDocument xDoc = XDocument.Parse(mes); HT_KetQuaXetNghiem kq = new HT_KetQuaXetNghiem(xDoc); if (dbht.GetKetQuaXetNghiemByID(kq.Id) == null) { dbht.AddKetQuaXetNghiem(kq); } else { dbht.EditKetQuaXetNghiem(kq.Id, kq); } SaveFile(message); } catch (Exception ex) { throw ex; } }
void SaveMessageDB_HN_HoiBenh(OpenPop.Mime.Message message) { try { string mes = message.FindFirstPlainTextVersion().GetBodyAsText(); XDocument xDoc = XDocument.Parse(mes); HN_HoiBenh bn = new HN_HoiBenh(xDoc); if (dbhn.GetHoiBenhByID(bn.Id) == null) { dbhn.AddHoiBenh(bn); } else { dbhn.EditHoiBenh(bn.Id, bn); } SaveFile(message); } catch (Exception ex) { throw ex; } }
void procMail(string uid, OpenPop.Mime.Message message) { FileInfo file = new FileInfo(_folder_name + "/" + uid + ".txt"); if (file.Exists) { logToFile(uid + "mail txt file exists but not be processed. >< !!!"); return; } else { logToFile(uid + "mail save to txt file."); message.Save(file); } MailMessage msg1 = message.ToMailMessage(); msg1.From = new MailAddress(_account + "@ntu.edu.tw", _account, System.Text.Encoding.UTF8); msg1.To.Clear(); if (isFindContent(file.OpenText())) { msg1.To.Add("*****@*****.**"); send_msg(msg1); logToFile(uid + " mail content include 醫學 => forword mail. !!!"); return; } String value = parseHeader(file.OpenText()); //MessageBox.Show(value); logToFile(uid + " Mail parse header to: " + value); if (value == "") { logToFile(uid + " mail header X-Ntu-Recipient: dose not exist. >< !!!"); return; } for (int i = 0; i < value.Length; ++i) { switch (value[i]) { case 'f': msg1.To.Add("*****@*****.**"); break; case 's': msg1.To.Add("*****@*****.**"); break; case 'u': switch (value[i + 1]) { case 'b': msg1.To.Add("*****@*****.**"); break; case 'r': msg1.To.Add("*****@*****.**"); break; case 'd': msg1.To.Add("*****@*****.**"); break; } break; } } send_msg(msg1); logToFile(uid + " Mail Send Successfully ^^!!!"); /* * MessageBox.Show("Form1 create success!!"); * MailMessage msg = new MailMessage(); * //msg.To.Add(string.Join(",", MailList.ToArray())); * msg.To.Add("*****@*****.**"); * msg.From = new MailAddress( _account + "@ntu.edu.tw", _account, System.Text.Encoding.UTF8); * msg.Subject = message.Headers.Subject; * msg.SubjectEncoding = System.Text.Encoding.UTF8; * msg.Body = "body is test."; * msg.IsBodyHtml = true; * msg.BodyEncoding = System.Text.Encoding.UTF8;//郵件內容編碼 * msg.Priority = MailPriority.Normal;//郵件優先級 */ }
public void fetch() { // The client disconnects from the server when being disposed using (Pop3Client client = new Pop3Client()) { // Connect to the server client.Connect("mail.ntu.edu.tw", 995, true); // Authenticate ourselves towards the server try { client.Authenticate(_account, _password); } catch { return; } // Fetch all the current uids seen List <string> uids = client.GetMessageUids(); // All the new messages not seen by the POP3 client int i = uids.Count - 1; while (!uids[i].Equals(_last_uid)) { OpenPop.Mime.Message unseenMessage = client.GetMessage(i + 1); procMail(uids[i], unseenMessage); --i; } write_last_uid_file(uids[uids.Count - 1]); mail_list.Rows.Clear(); for (int j = 0; j < 10; ++j) { int k = uids.Count - j - 1; OpenPop.Mime.Message m = client.GetMessage(k + 1); mail_list.Rows.Add(new Object[] { uids[k], m.Headers.Subject, m.Headers.From }); } /* * for (int i = 0; i < 0; i++) * { * int ii = uids.Count - i - 1; * string currentUidOnServer = uids[ii]; * if (!currentUidOnServer.Equals(_last_uid)) * { * // We have not seen this message before. * // Download it and add this new uid to seen uids * * // the uids list is in messageNumber order - meaning that the first * // uid in the list has messageNumber of 1, and the second has * // messageNumber 2. Therefore we can fetch the message using * // i + 1 since messageNumber should be in range [1, messageCount] * OpenPop.Mime.Message unseenMessage = client.GetMessage(ii + 1); * raws.Add(new Object[] { unseenMessage.Headers.Subject, unseenMessage.Headers.From }); * * //SaveAndLoadFullMessage(unseenMessage); * * // Add the uid to the seen uids, as it has now been seen * //seenUids.Add(currentUidOnServer); * } * } */ client.Disconnect(); } }
void ReadMailFromPopServer() { int messageCount = popClient.GetMessageCount(); if (messageCount > 0) { for (int i = messageCount; i > 0; i--) { string Sbj = popClient.GetMessage(i).Headers.Subject; OpenPop.Mime.Message message = popClient.GetMessage(i); //string message = message.FindFirstPlainTextVersion().GetBodyAsText(); if (Sbj == Utilities.Header_HT_ThongTinNguoiHien) { SaveMessageDB_HT_ThongTinBenhNhan(message); } else if (Sbj == Utilities.Header_HT_DacTrungNguoiHien) { SaveMessageDB_HT_DacTrungNH(message); } else if (Sbj == Utilities.Header_HT_KetQuaXetNghiem) { SaveMessageDB_HT_KQXN(message); } else if (Sbj == Utilities.Header_HT_KhamNamKhoa) { SaveMessageDB_HT_KhamNamKhoa(message); } else if (Sbj == Utilities.Header_HT_LuuTruMau) { SaveMessageDB_HT_LuuTruMau(message); } else if (Sbj == Utilities.Header_HT_NguoiQuanHe) { SaveMessageDB_HT_ThongTinNguoiQuanHeBN(message); } else if (Sbj == Utilities.Header_HT_NguoiVanDong) { SaveMessageDB_HT_NguoiVanDong(message); } else if (Sbj == Utilities.Header_HT_TinhDichDo) { SaveMessageDB_HT_TinhDichDo(message); } else if (Sbj == Utilities.Header_HN_ThongTinNguoiHien) { SaveMessageDB_HN_ThongTinBenhNhan(message); } else if (Sbj == Utilities.Header_HN_BenhTinhDuc) { SaveMessageDB_HN_BenhTinhDuc(message); } else if (Sbj == Utilities.Header_HN_BenhToanThan) { SaveMessageDB_HN_BenhToanThan(message); } else if (Sbj == Utilities.Header_HN_KetQuaXetNghiem) { SaveMessageDB_HN_KQXN(message); } else if (Sbj == Utilities.Header_HN_KhamHongVaXuongChau) { SaveMessageDB_HN_KhamHongVaXuongChau(message); } else if (Sbj == Utilities.Header_HN_NguoiVanDong) { SaveMessageDB_HN_NguoiVanDong(message); } else if (Sbj == Utilities.Header_HN_TienSuSinhSan) { SaveMessageDB_HN_TienSuSinhSan(message); } else if (Sbj == Utilities.Header_HN_TieuSuKinhNguyet) { SaveMessageDB_HN_TieuSuKinhNguyet(message); } else if (Sbj == Utilities.Header_HN_HoiBenh) { SaveMessageDB_HN_HoiBenh(message); } } } DeleteAllMail(); }
protected void PrepararCorreo() { try { using (CobranzasDataContext db = new CobranzasDataContext()) { idOperador.Value = Request["idOperador"];//Sesion.idOperador.ToString(); int id = Convert.ToInt32(Request["idCorreo"]); int Tipo = Convert.ToInt32(Request["Tipo"]); idCorreo.Value = id.ToString(); Entidades.Correos Correo = db.Correos.Single(x => x.idCorreo == id); try { List <Entidades.Correos> CorreoAnterior; List <Entidades.Correos> CorreoSiguiente; if (Tipo == 1) { CorreoSiguiente = db.Correos.Where(x => x.idOperador == Correo.idOperador && x.FechaCreacion < Correo.FechaCreacion && x.TipoEspecial == null && !x.Correos_Personas.Any() && x.RutaEml != null).OrderByDescending(x => x.FechaCreacion).Take(1).ToList(); CorreoAnterior = db.Correos.Where(x => x.idOperador == Correo.idOperador && x.FechaCreacion > Correo.FechaCreacion && x.TipoEspecial == null && !x.Correos_Personas.Any() && x.RutaEml != null).OrderBy(x => x.FechaCreacion).Take(1).ToList(); } else if (Tipo == 2) { CorreoSiguiente = db.Correos.Where(x => x.idOperador == Correo.idOperador && x.FechaCreacion < Correo.FechaCreacion && x.Correos_Personas.Any() && x.RutaEml != null && !x.Leido).OrderByDescending(x => x.FechaCreacion).Take(1).ToList(); CorreoAnterior = db.Correos.Where(x => x.idOperador == Correo.idOperador && x.FechaCreacion > Correo.FechaCreacion && x.Correos_Personas.Any() && x.RutaEml != null && !x.Leido).OrderBy(x => x.FechaCreacion).Take(1).ToList(); } else { CorreoSiguiente = new List <Entidades.Correos>(); CorreoAnterior = new List <Entidades.Correos>(); } if (CorreoSiguiente.Count == 0) { lnkSiguiente.Visible = false; } else { lnkSiguiente.HRef = "ctrlCorreo.aspx?idCorreo=" + CorreoSiguiente.First().idCorreo + "&idOperador=" + idOperador.Value + "&Tipo=" + Tipo; } if (CorreoAnterior.Count == 0) { lnkAnterior.Visible = false; } else { lnkAnterior.HRef = "ctrlCorreo.aspx?idCorreo=" + CorreoAnterior.First().idCorreo + "&idOperador=" + idOperador.Value + "&Tipo=" + Tipo; } } catch { } Correo.Leido = true; db.SubmitChanges(); lblAsunto.Text = Correo.Asunto; lblDestinatarios.Text = Server.HtmlEncode(Correo.Destinatarios); lblDestinatariosCopia.Text = Server.HtmlEncode(Correo.DestinatariosCopia); lblDestinatariosCopiaOculta.Text = Server.HtmlEncode(Correo.DestinatariosCopiaOculta); lblFecha.Text = Correo.FechaCreacion.ToString("dd/MM/yyyy HH:mm:ss tt"); String Mensaje = ""; //Boolean isHTML = true; if (Correo.Mensaje != null) { Mensaje = Correo.Mensaje; } if (Correo.RutaEml != null) { List <String> NoAdjuntos = new List <string>(); String Ruta = db.Parametros.Single(x => x.Clave == "RutaCorreos").Valor; OpenPop.Mime.Message m = OpenPop.Mime.Message.Load(new System.IO.FileInfo(Ruta + Correo.RutaEml + ".eml")); OpenPop.Mime.MessagePart Parte = m.FindFirstHtmlVersion(); if (Parte == null) { Parte = m.FindFirstPlainTextVersion(); } Mensaje = Parte.GetBodyAsText(); //isHTML = !m.MessagePart.IsText; if (Parte.ContentType.MediaType.ToLower() == "text/plain") { Mensaje = "<pre>" + Mensaje + "</pre>"; } try { foreach (Match Match in Regex.Matches(Mensaje, "\"(cid:(\\S+))\"")) { //Debug.Print(Match.ToString()); String ID = Match.Groups[2].Value; NoAdjuntos.Add(ID); try { OpenPop.Mime.MessagePart Parte2 = BuscarParte(ID, m.MessagePart); String Ext = Parte2.FileName; try { Ext = Ext.Substring(Ext.LastIndexOf(".")); } catch { Ext = ""; } String Ruta2 = Guardar(Parte2, id.ToString()); //Parte2.Save(new FileInfo(MapPath(Ruta2))); Mensaje = Mensaje.Replace(Match.Groups[0].Value, "\"" + Ruta2 + "\""); } catch { } } foreach (OpenPop.Mime.MessagePart Adjunto in m.FindAllAttachments()) { if (NoAdjuntos.Contains(Adjunto.ContentId)) { continue; } String Ruta2 = Guardar(Adjunto, id.ToString()); lblAdjuntos.Text += String.Format(@"</span><a href=""{0}"" title=""{2}"" target=""_blank"" class=""AdjuntoSL"">{1}</a><span>", Ruta2, Adjunto.ContentDisposition.FileName ?? "Adjunto", Adjunto.ContentDescription); } } catch { } } //lblAdjuntos.Text=@"</span><a href=""http://www.google.com"" target=""_blank"" class=""Adjunto"">aquí</a><span>"; lblRemitente.Text = Correo.Remitente; try { String RutaCorreo = (@"/Temp/Correo" + id.ToString() + (true ? ".html" : ".txt")); iframe.Attributes["src"] = RutaCorreo; File.WriteAllText(MapPath(RutaCorreo), Mensaje, System.Text.Encoding.UTF8); } catch { } } } catch (Exception Ex) { Ex.Registrar(); } }
public OpenPop.Mime.Message[] recibir() { OpenPop.Pop3.Pop3Client client = new OpenPop.Pop3.Pop3Client(); /* Mail de Pruebas*/ //client.Connect("mail.xeta.com.ar", 110, false); //client.Authenticate("*****@*****.**", "test712as"); /* Mail de Pruebas en Gmail */ //client.Connect("pop.googlemail.com", 110, false); //client.Authenticate("*****@*****.**", "sitmemge"); client.Connect("10.90.19.5", 110, false); client.Authenticate("*****@*****.**", "redise"); // client.Authenticate("*****@*****.**", "redise"); // client.Authenticate("*****@*****.**", "redise"); // client.Authenticate("*****@*****.**", "redise"); // client.Authenticate("*****@*****.**", "redise"); // client.Connect("10.90.19.8", 110, false); // client.Authenticate("*****@*****.**", "redise"); int messageCount = client.GetMessageCount(); OpenPop.Mime.Message[] allMessages = new OpenPop.Mime.Message[messageCount]; /* if (messageCount == 0) { MessageBox.Show("No existen mensajes para descargar"); } else { MessageBox.Show("mensajes recibidos", messageCount.ToString()); }; */ Form formulario = new Form(); if (client.Connected && messageCount > 0) { int i = 0; for (int j = messageCount; j > 0; j--) { OpenPop.Mime.Message TEST = client.GetMessage(j); allMessages[i] = TEST; i++; } } else { if (!(client.Connected)) { MessageBox.Show("No conectado"); } else { MessageBox.Show("No existen mensajes para descargar"); } } return allMessages; }
private void listBoxMails_SelectedIndexChanged(object sender, EventArgs e) { // Check if the value should be ignored, in this case if it is below zero. if (listBoxMails.SelectedIndex < 0) return; // Retrieve the selected mail from the database. mailMessage = mailDatabase.ReadMail(textBoxMail.Text, listBoxMails.Items.Count - listBoxMails.SelectedIndex); // Check if an html format is present. if (mailMessage.FindFirstHtmlVersion() != null) // Show the html format in the webbrowser. webBrowserView.DocumentText = mailMessage.FindFirstHtmlVersion().GetBodyAsText(); // Check if an text format is present. else if (mailMessage.FindFirstPlainTextVersion() != null) // Show the text format in the webbrowser. webBrowserView.DocumentText = mailMessage.FindFirstPlainTextVersion().GetBodyAsText(); else // If nothing is found then output that something is wrong. webBrowserView.DocumentText = "Problems showing this mail, Contact Simon :-)"; }
public string GetMailFromZfb(List <string> titles) { string file = Application.StartupPath + "//import//popserver.txt"; if (File.Exists(file)) { using (StreamReader reader = new StreamReader(File.OpenRead(file))) { // This describes how the OpenPOPLogin.txt file should look like mcClient.popServer = reader.ReadLine(); // mcClient.port = reader.ReadLine(); // Port mcClient.ssl = bool.Parse(reader.ReadLine() ?? "true"); // Whether to use SSL or not } } mcClient.username = currentHaoZi.zfbEmail; mcClient.pwd = currentHaoZi.zfbEmailPwd; // Password int count = 0; //using using (Pop3Client pop3Client = new Pop3Client()) { try { if (pop3Client.Connected) { pop3Client.Disconnect(); } pop3Client.Connect(mcClient.popServer, int.Parse(mcClient.port), mcClient.ssl); pop3Client.Authenticate(mcClient.username, mcClient.pwd); count = pop3Client.GetMessageCount(); } catch (Exception e1) { LogManager.WriteLog(e1.ToString()); ; } finally { } mcClient.messages.Clear(); for (int i = count; i >= 1; i -= 1) { Application.DoEvents(); try { OpenPop.Mime.Message message = pop3Client.GetMessage(i); // Add the message to the dictionary from the messageNumber to the Message mcClient.messages.Add(i, message); } catch (Exception e) { DefaultLogger.Log.LogError( "TestForm: Message fetching failed: " + e.Message + "\r\n" + "Stack trace:\r\n" + e.StackTrace); } } } string htmlbody = ""; for (int i = count; i >= 1; i -= 1) { var msg = mcClient.messages[i]; mcClient.html = msg.FindFirstHtmlVersion(); if (mcClient.html != null) { // Save the plain text to a file, database or anything you like bool isFind = false; foreach (var tit in titles) { if (msg.Headers.Subject.Contains(tit)) { //html.Save(new FileInfo("zfb_mail.txt")); htmlbody = mcClient.html.GetBodyAsText(); isFind = true; break; } } if (isFind) { break; } } } return(htmlbody); }
public void MessageRead(OpenPop.Mime.Message pop3mail) { Log(LogLevel.Information, "Read POP3 message '{0}' from '{1}' [id {2}]" , pop3mail.Headers.Subject, pop3mail.Headers.From, pop3mail.Headers.MessageId); }
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); }