public static List<Message> FetchAllMessages(string hostname, int port, bool useSsl, string username, string password) { // The client disconnects from the server when being disposed using (OpenPop.Pop3.Pop3Client client = new OpenPop.Pop3.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); // 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)); //GetDataToSave(client.GetMessage(i)); if (System.Configuration.ConfigurationSettings.AppSettings["pop_delete_after_download"] == "true") { client.DeleteMessage(i); } if (i == 2) { break; }; } // Now return the fetched messages return allMessages; } }
public void DeleteMail(int index) { try { client.DeleteMessage(index); } catch (Exception ex) { string messageLog = "Can't delete email have Subject \"" + GetHeaderSubject() + "\""; messageLog = messageLog + "\n" + ExceptionHandling.ExceptionHelper.GetDetailMessage(ex); } }
private static void CleanUpInbox() { OpenPop.Pop3.Pop3Client p3 = new OpenPop.Pop3.Pop3Client(); int iPort = 110; iPort = 995; bool bSSL = false; bSSL = true; string sPopHost = Saved.Code.Common.GetBMSConfigurationKeyValue("outlookhost"); string sPopUser = Saved.Code.Common.GetBMSConfigurationKeyValue("smtppopuser"); string sPopPass = Saved.Code.Common.GetBMSConfigurationKeyValue("smtppoppassword"); p3.Connect(sPopHost, iPort, bSSL, 7000, 7000, null); p3.Authenticate(sPopUser, sPopPass); int iCount = p3.GetMessageCount(); int i = 0; for (i = iCount; i > 0; i--) { try { MessageHeader h = p3.GetMessageHeaders(i); Message m = p3.GetMessage(i); OpenPop.Mime.MessagePart plainText = m.FindFirstPlainTextVersion(); OpenPop.Mime.MessagePart htmlPart = m.FindFirstHtmlVersion(); string body = ""; string myto = m.Headers.Subject; string mysentto = ""; if (myto != null) { string[] vTo = myto.Split(new string[] { "-" }, StringSplitOptions.None); if (vTo.Length > 1) { mysentto = vTo[1].Trim(); } } if (plainText != null) { body += plainText.GetBodyAsText(); } if (htmlPart != null) { body += htmlPart.GetBodyAsText(); } bool fTotaled = false; if (body.Contains("be delivered to one")) { fTotaled = true; } else if (body.Contains("hop count exceeded")) { fTotaled = true; } else if (body.Contains("A communication failure occurred")) { fTotaled = true; } else if (body.Contains("The email address you entered couldn't be found")) { fTotaled = true; } else if (body.Contains("The domain you attempted to contact")) { fTotaled = true; } else if (body.Contains("I'm afraid I wasn't able to deliver the following message")) { fTotaled = true; } else if (body.Contains("cannot be delivered")) { fTotaled = true; } else if (body.Contains("I was unable to deliver your message")) { fTotaled = true; } else if (body.Contains("Your message wasn't delivered")) { fTotaled = true; } else if (body.Contains("rejected your message to the following")) { fTotaled = true; } else if (body.Contains("Delivery to the following recipient failed permanently")) { fTotaled = true; } else if (body.Contains("This is a delivery failure notification message ")) { fTotaled = true; } else if (body.Contains("Delivery has failed to these recipients or groups")) { fTotaled = true; } else if (body.Contains("There was a temporary problem delivering your message ")) { fTotaled = true; } else if (body.Contains("The following addresses had permanent fatal errors")) { fTotaled = true; } else if (body.Contains("the receiving email server outside Office 365 reported ") || body.Contains("couldn't be delivered")) { fTotaled = true; } if (fTotaled) { string sql = "update Leads set Advertised=getdate() where email='" + mysentto + "'"; Saved.Code.Common.gData.Exec(sql); p3.DeleteMessage(i); } } catch (Exception) { } } p3.Disconnect(); }
static void Pop3Test() { OpenPop.Pop3.Pop3Client mclient = new OpenPop.Pop3.Pop3Client(); mclient.Connect("mail.cute.edu.tw", 110, false); mclient.Authenticate("weather", "0988163835"); int cnt = mclient.GetMessageCount(); Console.WriteLine("Message cnt:" + cnt); string bodytext; for (int i = 1; i <= cnt; i++) { bodytext = ""; Message msg = mclient.GetMessage(i); Console.WriteLine("from:" + msg.Headers.From.MailAddress.Address); Console.WriteLine("subject:" + msg.Headers.Subject); if (!msg.MessagePart.IsText) { MessagePart msgpart = msg.FindFirstPlainTextVersion(); if (msgpart != null && msgpart.IsText) { Console.WriteLine("body:" + msgpart.GetBodyAsText()); bodytext = msgpart.GetBodyAsText(); } } else { Console.WriteLine("body:" + msg.MessagePart.GetBodyAsText()); bodytext = msg.MessagePart.GetBodyAsText(); } if (msg.Headers.Subject.Contains("大雨") || msg.Headers.Subject.Contains("強風") || msg.Headers.Subject.Contains("地震")) { System.Net.Mail.SmtpClient c = new SmtpClient("mail.cute.edu.tw", 25); c.DeliveryMethod = SmtpDeliveryMethod.Network; c.Credentials = new System.Net.NetworkCredential("weather", "0988163835"); MailMessage m_mesg = new MailMessage(new MailAddress("*****@*****.**"), new MailAddress("*****@*****.**")); m_mesg.Body = bodytext; m_mesg.Subject = msg.Headers.Subject.Replace("\n", ""); m_mesg.IsBodyHtml = true; if (bodytext != "") c.Send(m_mesg); } } for (int i = 1; i <= cnt; i++) mclient.DeleteMessage(i); mclient.Dispose(); }
// // =========================================================================================== // public void bounceProcess(Contensive.BaseClasses.CPBaseClass cp) { try { CPCSBaseClass CS = cp.CSNew(); string MessageText; string[] FilterLines; string[] FilterText = Array.Empty <string>(); int[] FilterType = Array.Empty <int>(); int LinePtr; string[] LineSplit; int FilterLineCnt = 0; string Filter; int BounceType; string EmailAddress; string PopServer; int popPort; string POPServerUsername; string POPServerPassword; int EmailBounceProcessAction; bool AllowEmailBounceProcessing; string bounceLogPathPage; string ActionTaken; string FilterFilename; string Filename = ""; DateTime rightNowDate = DateTime.Now.Date; string logDatePart = rightNowDate.Year + rightNowDate.Month.ToString().PadLeft(2) + rightNowDate.Day.ToString().PadLeft(2); string amazonMsg = "An error occurred while trying to deliver the mail to the following recipients:" + "\r\n"; // AllowEmailBounceProcessing = cp.Site.GetBoolean("AllowEmailBounceProcessing", false); if (AllowEmailBounceProcessing) { PopServer = cp.Site.GetText("PopServer", ""); popPort = cp.Site.GetInteger("popServerPort", 110); if (popPort <= 0) { popPort = 110; } POPServerUsername = cp.Site.GetText("POPServerUsername", ""); POPServerPassword = cp.Site.GetText("POPServerPassword", ""); if ((PopServer == "") | (POPServerUsername == "") | (POPServerPassword == "")) { cp.Utils.AppendLog("AllowEmailBounceProcessing true but server, username or password is blank"); } else { bounceLogPathPage = @"BounceLog\" + logDatePart + @"\trace.txt"; FilterFilename = @"\config\EmailBounceFilters.txt"; EmailBounceProcessAction = cp.Site.GetInteger("EmailBounceProcessAction", 0); // // Read in the filter file // if (true) { string copy; copy = cp.CdnFiles.Read(FilterFilename); if (copy == "") { cp.Utils.AppendLog(@"Bounce processing filters file \config\EmailBounceFilters.txt is empty"); } else { copy = copy.Replace("\r\n", "\r"); copy = copy.Replace("\n", "\r"); FilterLines = copy.Split('\r'); FilterLineCnt = FilterLines.Length; FilterText = new string[FilterLineCnt + 100 + 1]; FilterType = new int[FilterLineCnt + 100 + 1]; // // // for (LinePtr = 0; LinePtr <= FilterLineCnt - 1; LinePtr++) { if (FilterLines[LinePtr] != "") { LineSplit = FilterLines[LinePtr].Split(','); FilterText[LinePtr] = LineSplit[0]; if (LineSplit.Length > 0) { FilterType[LinePtr] = cp.Utils.EncodeInteger(LineSplit[1]); } } } // // add amazon // FilterText[FilterLineCnt] = amazonMsg; FilterType[FilterLineCnt] = 2; FilterLineCnt += 1; } } // // Retrieve the emails // int MessageCnt; string headerList; OpenPop.Mime.Message msg; using (OpenPop.Pop3.Pop3Client pop = new OpenPop.Pop3.Pop3Client()) { try { pop.Connect(PopServer, popPort, true); pop.Authenticate(POPServerUsername, POPServerPassword); MessageCnt = pop.GetMessageCount(); // cp.CdnFiles.Append(bounceLogPathPage, "\r\n" + "New bounce emails, cnt=" + MessageCnt); // for (int msgPtr = 1; msgPtr <= MessageCnt; msgPtr++) { msg = pop.GetMessage(msgPtr); headerList = ""; EmailAddress = ""; headerList = ""; MessageText = ""; if (!msg.Headers.From.HasValidMailAddress) { // cp.CdnFiles.Append(bounceLogPathPage, "\n\r" + "email" + msgPtr + "-" + "email address not found"); } else { EmailAddress = msg.Headers.From.Address; foreach (string key in msg.Headers.UnknownHeaders.AllKeys) { string keyValue = msg.Headers.UnknownHeaders[key]; headerList += "\r\n" + key + "=" + keyValue; } OpenPop.Mime.MessagePart msgBody; msgBody = msg.FindFirstPlainTextVersion(); if ((msgBody == null)) { msgBody = msg.FindFirstHtmlVersion(); } MessageText = ""; if (!(msgBody == null)) { MessageText = msgBody.GetBodyAsText(); } if (string.IsNullOrEmpty(MessageText)) { // cp.CdnFiles.Append(bounceLogPathPage, "\n\r" + "email" + msgPtr + "-" + "email has blank body"); } else { // // Process them as they come in // if ((EmailAddress == "*****@*****.**")) { if ((MessageText.IndexOf(amazonMsg) > -1)) { EmailAddress = MessageText.Replace(amazonMsg, ""); } } ActionTaken = "no action"; if (EmailAddress == "") { // cp.CdnFiles.Append(bounceLogPathPage, "\n\r" + "email" + msgPtr + "-" + "email address was blank"); // ActionTaken = "deleted with no action, email address could not be determined, email content saved [" + Filename + "]"; } else if (FilterLineCnt == 0) { // cp.CdnFiles.Append(bounceLogPathPage, "\n\r" + "email" + msgPtr + "-" + "email filter file was not found (" + FilterFilename + ")"); // ActionTaken = "[" + EmailAddress + "], deleted with no action, no Filter File [" + FilterFilename + "]"; } else { // Copy = strDecodeMime(MessageText, MessageHeaders) for (LinePtr = 0; LinePtr <= FilterLineCnt - 1; LinePtr++) { Filter = FilterText[LinePtr].Trim(); if (Filter != "") { if (MessageText.IndexOf(Filter) >= 0) { BounceType = FilterType[LinePtr]; switch (BounceType) { case 0: { // ActionTaken = "[" + EmailAddress + "], deleted with no action, Filter [" + Filter + "] is not a bounce"; break; } case 1: { // // soft bounce - may recover // ActionTaken = "[" + EmailAddress + "], deleted with no action, Filter [" + Filter + "] is soft error, may recover"; break; } case 2: { // // hard bounce - take action on the member email // // // // // EmailBounceProcessAction = 1; // // // switch (EmailBounceProcessAction) { case 1: { // // clear allowgroupemail // ActionTaken = "[" + EmailAddress + "], clear allowBulkEmail action, Filter [" + Filter + "] is hard error"; CS.Open("people", "email=" + cp.Db.EncodeSQLText(EmailAddress), "", true, "ID,Name,OrganizationID,allowbulkemail"); if (!(CS.OK())) { ActionTaken += ", NO RECORD FOUND"; } else { ActionTaken += ", clearing allowGroupEmail for records ["; while (CS.OK()) { ActionTaken += "," + CS.GetInteger("id").ToString(); CS.SetField("allowbulkemail", 0.ToString()); CS.GoNext(); } ActionTaken += "]"; } CS.Close(); break; } case 2: { // // clear email // ActionTaken = "[" + EmailAddress + "], clear email address action, Filter [" + Filter + "] is hard error"; CS.Open("people", "email=" + cp.Db.EncodeSQLText(EmailAddress), "", true, "ID,Name,OrganizationID,email"); if (!CS.OK()) { ActionTaken += ", NO RECORD FOUND"; } else { ActionTaken += ", clear email address for records ["; while (CS.OK()) { CS.SetField("email", ""); CS.GoNext(); } ActionTaken += "]"; } CS.Close(); break; } case 3: { // // Delete Member // ActionTaken = "[" + EmailAddress + "], delete member, Filter [" + Filter + "] is hard error"; CS.Open("people", "email=" + cp.Db.EncodeSQLText(EmailAddress), "", true, "ID,Name,OrganizationID"); if (!CS.OK()) { ActionTaken += ", NO RECORD FOUND"; } else { ActionTaken += ", delete people records ["; while (CS.OK()) { CS.Delete(); CS.GoNext(); } ActionTaken += "]"; } CS.Close(); break; } default: { // // Unknown Process Action // ActionTaken = "[" + EmailAddress + "], deleted with no action, Filter [" + Filter + "] is hard error, but Process Action is unknown [" + EmailBounceProcessAction + "]"; break; } } break; } } // cp.CdnFiles.Append(bounceLogPathPage, "\n\r" + "email" + msgPtr + "-" + ActionTaken); // break; } } } } } } // // save bounced email // cp.CdnFiles.Save(@"BounceLog\" + logDatePart + @"\email-" + msgPtr + ".txt", EmailAddress + "\n\r" + headerList + "\n\r" + MessageText); // // delete the message // pop.DeleteMessage(msgPtr); } } catch (Exception ex) { cp.Site.ErrorReport(ex, "Bounce Processing exception"); } finally { } } } } } catch (Exception ex) { cp.Site.ErrorReport(ex); } }
static void WeatherMailJob() { OpenPop.Pop3.Pop3Client mclient = new OpenPop.Pop3.Pop3Client(); mclient.Connect("mail.cute.edu.tw", 110, false); mclient.Authenticate("weather", "0988163835"); int cnt = mclient.GetMessageCount(); Console.WriteLine("Message cnt:" + cnt); string bodytext; for (int i = 1; i <= cnt; i++) { try { bodytext = ""; Message msg = mclient.GetMessage(i); string from = msg.Headers.From.MailAddress.Address; Console.WriteLine("from:" + from); Console.WriteLine("subject:" + msg.Headers.Subject); if (from != "*****@*****.**" && from != "*****@*****.**" && from != "*****@*****.**") continue; // string b = msg.MessagePart.GetBodyAsText(); // string htmlString = @"<p>I'm HTML!</p>"; // b= Regex.Replace(b, @"(<(.|\n)*?>| )", ""); // Console.WriteLine(Program.StripHTML( b)); if (!msg.MessagePart.IsText) { MessagePart msgpart = msg.FindFirstPlainTextVersion(); if (msgpart != null && msgpart.IsText) { // Console.WriteLine("body:" + msgpart.GetBodyAsText()); bodytext = msgpart.GetBodyAsText(); } } else { bodytext = msg.MessagePart.GetBodyAsText(); } string txtbodytext = StripHTML(bodytext); txtbodytext = txtbodytext.Replace("\r", "<br>"); Console.WriteLine("body:" + txtbodytext); // txtbodytext = txtbodytext.Replace("\r", "<br>"); if (LogToDB(msg, txtbodytext) || from == "*****@*****.**" || from == "*****@*****.**") { if (from == "*****@*****.**" || from == "*****@*****.**" || msg.Headers.Subject.Contains("颱風")) { #if DEBUG txtbodytext = "<img src=\"http://192.192.161.4/sshmc/logo.png\"><p>致 貴客戶,依中央氣象局發布資料,提醒您以下防災預警資訊:<br>" + txtbodytext; SendMailToAllUser(msg.Headers.Subject.Replace("\n", ""), txtbodytext); #else SendMailToAllUser(msg.Headers.Subject.Replace("\n", ""), bodytext); #endif } else { txtbodytext = "<img src=\"http://192.192.161.4/sshmc/logo.png\"><p>致 貴客戶,依中央氣象局發布資料,提醒您以下防災預警資訊:<br>" + txtbodytext; SendMailToAllUser(msg.Headers.Subject.Replace("\n", ""), txtbodytext); } } } catch (Exception ex) { Console.WriteLine(ex.Message); } } #if !DEBUG for (int i = 1; i <= cnt; i++) mclient.DeleteMessage(i); #endif mclient.Dispose(); // Console.ReadKey(); }