protected void DeleteClick(string msgID, string msgMessageID) { string PathTemplate; PathTemplate = Path.Combine(ConfigSettings.DataStoragePath, String.Format("webmail{1}{0}{1}mails", UC.UserId, Path.DirectorySeparatorChar)); string NameOfFile = PathTemplate + Path.DirectorySeparatorChar + msgMessageID + ".tmsg"; if (File.Exists(NameOfFile)) { Message msg = new Message(); FileStream newfile = new FileStream(NameOfFile, FileMode.Open); BinaryFormatter bf = new BinaryFormatter(); msg = (Message)bf.Deserialize(newfile); newfile.Close(); foreach (MessageAttach ma in msg.Attachment) { string attpath; attpath = Path.Combine(ConfigSettings.DataStoragePath, String.Format("webmail{2}{0}{2}{1}", UC.UserId, ma.Filename, Path.DirectorySeparatorChar)); if (File.Exists(attpath)) { File.Delete(attpath); } } File.Delete(NameOfFile); } DataRow dtpop3 = DatabaseConnection.CreateDataset("SELECT MAILSERVER,MAILUSER,MAILPASSWORD FROM ACCOUNT WHERE UID=" + UC.UserId).Tables[0].Rows[0]; string pop3 = dtpop3[0].ToString(); bool secure = false; if (pop3.StartsWith("!")) { pop3 = pop3.Substring(1); secure = true; } using (Pop3Client email = new Pop3Client(dtpop3[1].ToString(), dtpop3[2].ToString(), pop3, secure)) { email.OpenInbox(); email.NextEmail(Convert.ToInt32(msgID)); bool result = email.DeleteEmail(); if (!result) { lblError.Text = Root.rm.GetString("Mailtxt26"); } email.Quit(); email.CloseConnection(); FillMsgIn(true, false); dgmessages.Visible = false; } }
public void run() { try { Pop3Client client = new Pop3Client("callback", "certify588", "proxy.rlanders.com"); client.OpenInbox(); while (client.NextEmail()) { Console.WriteLine("Original Body: " + client.Body); string htmlless = stripHTML(client.Body); Console.WriteLine("HTMLless Body: " + client.Body); ArrayList numbers = client.HarvestPhoneNumbers("call 2"); /*if (numbers.Count > 0) * { * Console.WriteLine("Phone Numbers Harvested: "); * for (int i = 0; i < numbers.Count; i++) * { * Console.WriteLine("\tNo. " + i.ToString() + ": " + numbers[i]); * } * }*/ } Console.WriteLine("testing email carrier: [email protected][email protected]=whatever.wav"); string test = "[email protected][email protected]=whatever.wav"; while (test.Length > 0) { string attach = test.Substring(test.LastIndexOf("=") + 1); test = test.Remove(test.LastIndexOf("=")); Console.WriteLine("attach: " + attach); string to = test.Substring(test.LastIndexOf("~") + 1); test = test.Remove(test.LastIndexOf("~")); Console.WriteLine("send above to: " + to); } client.CloseConnection(); } catch (Pop3LoginException ex) { Console.WriteLine("Error logging in"); } emailme(); }
protected void Page_Load(object sender, EventArgs e) { if (!Login()) { ClientScript.RegisterStartupScript(this.GetType(), "", "<script>opener.location.href=opener.location.href;self.close();</script>"); } else { string pop3 = Request["pop3"]; string addr = Request["addr"]; string pass = Request["pass"]; bool secure = false; if (pop3.StartsWith("!")) { pop3 = pop3.Substring(1); secure = true; } try { using (Pop3Client email = new Pop3Client(addr, pass, pop3, secure)) { email.OpenInbox(); long x = email.MessageCount; email.CloseConnection(); Address.Text = Root.rm.GetString("Mailtxt20"); } } catch (Pop3PasswordException) { Address.Text = Root.rm.GetString("Mailtxt16"); } catch (Pop3LoginException) { Address.Text = Root.rm.GetString("Mailtxt17"); } catch (Pop3ConnectException) { Address.Text = Root.rm.GetString("Mailtxt16"); } catch { Address.Text = Root.rm.GetString("Mailtxt16"); } } }
private void получитьToolStripMenuItem_Click(object sender, EventArgs e) { List <Config.Server> list = _config.GetPop3(); foreach (Config.Server srv in list) { try { Pop3Client email = new Pop3Client(srv.User, srv.Password, srv.Address); email.OpenInbox(); while (email.NextEmail()) { _inbox.Add(new Letter() { Subject = email.Subject, From = email.From, To = email.To }); email.DeleteEmail(); } email.CloseConnection(); } catch (Pop3LoginException) { string msg = "Сервер " + srv.Address + " не доступен"; MessageBox.Show(msg); } catch (Pop3ConnectException) { string msg = "Сервер " + srv.Address + " не доступен"; MessageBox.Show(msg); } } UpdateInbox(); }
/// <summary> /// Execute() implementation /// </summary> /// <param name='testConfig'>The Xml fragment containing the configuration for this test step</param> /// <param name='context'>The context for the test, this holds state that is passed beteen tests</param> public void Execute(XmlNode testConfig, Context context) { int delayBeforeCheck = context.ReadConfigAsInt32(testConfig, "DelayBeforeCheck", true); string server = context.ReadConfigAsString(testConfig, "Server"); string user = context.ReadConfigAsString(testConfig, "User"); string password = context.ReadConfigAsString(testConfig, "Password"); string from = null; bool showBody = false; string subject = null; int attachments = -1; bool found = false; if (testConfig.SelectSingleNode("ShowBody") != null) { showBody = context.ReadConfigAsBool(testConfig, "ShowBody"); } if (testConfig.SelectSingleNode("From") != null) { from = context.ReadConfigAsString(testConfig, "From"); } if (testConfig.SelectSingleNode("Subject") != null) { subject = context.ReadConfigAsString(testConfig, "Subject"); } if (testConfig.SelectSingleNode("Attachments") != null) { attachments = context.ReadConfigAsInt32(testConfig, "Attachments"); } if (delayBeforeCheck > 0) { context.LogInfo("Waiting for {0} seconds before checking the mail.", delayBeforeCheck); System.Threading.Thread.Sleep(delayBeforeCheck * 1000); } var email = new Pop3Client(user, password, server); email.OpenInbox(); try { while (email.NextEmail()) { if (email.To == user && (email.From == from || from == null) && (email.Subject == subject || subject == null)) { if (attachments > 0 && email.IsMultipart) { int a = 0; IEnumerator enumerator = email.MultipartEnumerator; while (enumerator.MoveNext()) { var multipart = (Pop3Component) enumerator.Current; if (multipart.IsBody) { if (showBody) { context.LogData("Multipart body", multipart.Data); } } else { context.LogData("Attachment name", multipart.Name); a++; } } if (attachments == a) { found = true; break; } } else { if (showBody) { context.LogData("Single body", email.Body); } found = true; break; } } } if (!found) { throw new Exception("Failed to find email message"); } else { email.DeleteEmail(); } } finally { email.CloseConnection(); } }
private long AddMsgToCache() { try { long position = 0; long filledTo = 0; long newFilledTo = 0; long msgLoop = 0; DataRow dtPop3 = DatabaseConnection.CreateDataset("SELECT MAILSERVER,MAILUSER,MAILPASSWORD FROM ACCOUNT WHERE UID=" + UC.UserId).Tables[0].Rows[0]; if (dtPop3[1].ToString().Length > 0 && dtPop3[2].ToString().Length > 0 && dtPop3[0].ToString().Length > 0) { string pop3 = dtPop3[0].ToString(); bool secure = false; if (pop3.StartsWith("!")) { pop3 = pop3.Substring(1); secure = true; } using (Pop3Client email = new Pop3Client(dtPop3[1].ToString(), dtPop3[2].ToString(), pop3, secure)) { email.OpenInbox(); Message[] msgs = new Message[email.MessageCount]; if (msgs.Length > 0) { long newPos = 0; try { position = ((MessageCache)Session[UC.UserName]).LastPosition; filledTo = ((MessageCache)Session[UC.UserName]).FilledTo; msgs = ((MessageCache)Session[UC.UserName]).Messages; newPos = position - UC.PagingSize; if ((newPos) > 0) { email.PositionID = newPos; msgLoop = filledTo + UC.PagingSize; } else { email.PositionID = 0; newPos = 0; msgLoop = msgs.Length - 1; } } catch { email.PositionID = 0; newPos = 0; msgLoop = msgs.Length - 1; } newFilledTo = msgLoop; Trace.Warn("position paging", position.ToString() + " " + UC.PagingSize.ToString()); while (email.NextEmail(true) && msgLoop > filledTo && msgLoop >= 0) // solo top { Message msg = new Message(); try { msg.From = (email.From.Length > 0) ? email.From : " "; } catch { msg.From = " "; } try { msg.To = (email.To.Length > 0) ? email.To : " "; } catch { msg.To = " "; } try { msg.Subject = (email.Subject.Length > 0) ? email.Subject : " "; } catch { msg.Subject = " "; } try { msg.Size = email.Size; } catch { msg.Size = 0; } try { msg.MessageID = (email.MessageID != null) ? Regex.Replace(email.MessageID.Trim('<', '>'), @"[^a-zA-Z0-9_]", "_") : ""; } catch { msg.MessageID = String.Empty; } msg.MsgID = email.PositionID; msg.MsgSerial = email.GetSerial; try { msg.MsgDate = UC.LTZ.ToLocalTime(email.Date); } catch { msg.MsgDate = DateTime.Now; } msgs[msgLoop--] = msg; } MessageCache MCache = new MessageCache(msgs, email.LastSerial); MCache.LastPosition = position - UC.PagingSize; MCache.FilledTo = newFilledTo; Session.Remove(UC.UserName); Session.Add(UC.UserName, MCache); } else { lblError.Text = "<br><center>" + Root.rm.GetString("WebMLtxt12") + "</center>"; } email.CloseConnection(); } } else { Context.Items.Add("warning", Root.rm.GetString("WebMLtxt8")); } return(msgLoop + 1); } catch (Pop3PasswordException) { Context.Items.Add("warning", Root.rm.GetString("Mailtxt16")); return(0); } catch (Pop3LoginException) { Context.Items.Add("warning", Root.rm.GetString("Mailtxt17")); return(0); } catch (Pop3ConnectException) { Context.Items.Add("warning", Root.rm.GetString("Mailtxt16")); return(0); } }
private void FillMsgIn(bool force, bool firstLoad) { try { long msgLoop = 0; DataRow dtpop3 = DatabaseConnection.CreateDataset("SELECT MAILSERVER,MAILUSER,MAILPASSWORD FROM ACCOUNT WHERE UID=" + UC.UserId).Tables[0].Rows[0]; if (dtpop3[1].ToString().Length > 0 && dtpop3[2].ToString().Length > 0 && dtpop3[0].ToString().Length > 0) { string pop3 = dtpop3[0].ToString(); bool secure = false; if (pop3.StartsWith("!")) { pop3 = pop3.Substring(1); secure = true; } using (Pop3Client email = new Pop3Client(dtpop3[1].ToString(), dtpop3[2].ToString(), pop3, secure)) { email.OpenInbox(); Message[] msgs = new Message[email.MessageCount]; if (msgs.Length > 0) { if ((Session[UC.UserName] == null || ((Session[UC.UserName] is MessageCache) && email.IsNewMessages(((MessageCache)Session[UC.UserName]).LastSerial))) || force) { msgLoop = msgs.Length - 1; long posid = 1; if (msgs.Length > UC.PagingSize) { email.PositionID = msgs.Length - UC.PagingSize; posid = msgs.Length - UC.PagingSize; msgLoop = msgs.Length - email.PositionID - 1; if (msgLoop < 0) { msgLoop = 0; } } else { email.PositionID = 0; msgLoop = 0; } long filledTo = msgLoop; while (email.NextEmail(true)) // solo top { Message msg = new Message(); try { msg.From = (email.From.Length > 0) ? email.From : " "; } catch { msg.From = " "; } try { msg.To = (email.To.Length > 0) ? email.To : " "; } catch { msg.To = " "; } try { msg.Subject = (email.Subject.Length > 0) ? email.Subject : " "; } catch { msg.Subject = " "; } try { msg.Size = email.Size; } catch { msg.Size = 0; } try { msg.MessageID = (email.MessageID != null) ? Regex.Replace(email.MessageID.Trim('<', '>'), @"[^a-zA-Z0-9_]", "_") : ""; } catch { msg.MessageID = String.Empty; } msg.MsgID = email.PositionID; msg.MsgSerial = email.GetSerial; try { msg.MsgDate = UC.LTZ.ToLocalTime(email.Date); } catch { msg.MsgDate = new DateTime(1980, 1, 1); } if (msgs.Length > UC.PagingSize) { msgs[msgLoop--] = msg; } else { msgs[msgLoop++] = msg; } } MessageCache MCache = new MessageCache(msgs, email.LastSerial); MCache.LastPosition = posid; MCache.FilledTo = filledTo; if (msgs.Length < UC.PagingSize) { Array.Reverse(msgs); } Session.Add(UC.UserName, MCache); } else { msgs = ((MessageCache)Session[UC.UserName]).Messages; msgLoop = ((MessageCache)Session[UC.UserName]).LastPosition; } } else { lblError.Text = "<br><center>" + Root.rm.GetString("WebMLtxt12") + "</center>"; } email.CloseConnection(); if (msgs.Length > 0) { if (msgs.Length > UC.PagingSize) { if (firstLoad) { msgLoop = -1; } Message[] msgs2 = new Message[UC.PagingSize]; Array.Copy(msgs, msgLoop + 1, msgs2, 0, UC.PagingSize); tblpaging.Visible = true; MessPageID.Text = "0"; PreviousMessPage.Enabled = false; NextMessPage.Enabled = true; Repeatermsg.DataSource = msgs2; Repeatermsg.DataBind(); } else { tblpaging.Visible = false; Repeatermsg.DataSource = msgs; Repeatermsg.DataBind(); } Lblmsginfo.Text = "<b>" + dtpop3[1].ToString() + "</b> " + String.Format(Root.rm.GetString("Mailtxt8"), msgs.Length.ToString(), Convert.ToString(email.TotalBytes / 1024)); if (msgs.Length == 0) { dgmessages.Visible = false; } messages.Visible = true; } } } else { lblError.Text = "<br><br><center><div style=\"color:red;font-size:12px;width:600px;\">" + Root.rm.GetString("WebMLtxt8") + "</div></center>"; } } catch (Pop3PasswordException) { Context.Items.Add("warning", Root.rm.GetString("Mailtxt16")); } catch (Pop3LoginException) { Context.Items.Add("warning", Root.rm.GetString("Mailtxt17")); } catch (Pop3ConnectException) { Context.Items.Add("warning", Root.rm.GetString("Mailtxt16")); } this.dgmessages.Visible = false; Repeatermsg.Visible = true; }
private void dgmessages_ItemCommand(object source, DataGridCommandEventArgs e) { switch (e.CommandName) { case "CreateActivity": ActivityInsert ai = new ActivityInsert(); string mailbody = HttpUtility.HtmlDecode(Pop3Utils.trimhtml(((Label)e.Item.FindControl("mailbody")).Text)); string mailsubject = HttpUtility.HtmlDecode(Pop3Utils.trimhtml(((Label)e.Item.FindControl("mailsubject")).Text)); TextBox MailAddressToID = (TextBox)e.Item.FindControl("MailAddressToID"); RadioButtonList CrossWith = (RadioButtonList)e.Item.FindControl("CrossWith"); if (MailAddressToID.Text.Length > 0) { string A = String.Empty; string C = String.Empty; string L = String.Empty; switch (CrossWith.SelectedValue) { case "0": A = MailAddressToID.Text; C = String.Empty; L = String.Empty; break; case "1": C = MailAddressToID.Text; A = String.Empty; L = String.Empty; break; case "2": L = MailAddressToID.Text; A = String.Empty; C = String.Empty; break; } if (A.Length > 0 || C.Length > 0 || L.Length > 0) { CheckBox SaveEml = (CheckBox)e.Item.FindControl("SaveEml"); long docid = 0; if (SaveEml.Checked) { DataRow dtpop3 = DatabaseConnection.CreateDataset("SELECT MAILSERVER,MAILUSER,MAILPASSWORD FROM ACCOUNT WHERE UID=" + UC.UserId).Tables[0].Rows[0]; string pop3 = dtpop3[0].ToString(); bool secure = false; if (pop3.StartsWith("!")) { pop3 = pop3.Substring(1); secure = true; } using (Pop3Client email = new Pop3Client(dtpop3[1].ToString(), dtpop3[2].ToString(), pop3, secure)) { email.OpenInbox(); email.AttachmentsPath = Path.Combine(ConfigSettings.DataStoragePath, String.Format("webmail{1}{0}{1}", UC.UserId, Path.DirectorySeparatorChar)); email.NextEmail(Convert.ToInt64(((Label)e.Item.FindControl("MailMsgId")).Text)); string eml = email.Original; Guid g = Guid.NewGuid(); using (DigiDapter dg = new DigiDapter()) { dg.Add("Guid", g); dg.Add("OwnerID", UC.UserId); dg.Add("IsReview", 0); dg.Add("ReviewNumber", 0); dg.Add("HaveRevision", false); dg.Add("CreatedDate", DateTime.UtcNow); dg.Add("CreatedByID", UC.UserId); dg.Add("Filename", email.Subject + ".eml"); dg.Add("size", eml.Length); dg.Add("Description", email.Subject); dg.Add("LastModifiedDate", DateTime.UtcNow); dg.Add("LastModifiedByID", UC.UserId); dg.Add("TYPE", 0); dg.Add("Groups", "|" + UC.UserGroupId.ToString() + "|"); object NewID = dg.Execute("FILEMANAGER", DigiDapter.Identities.Identity); docid = Convert.ToInt64(NewID); } string PathTemplate; PathTemplate = ConfigSettings.DataStoragePath; string NameOfFile = PathTemplate + Path.DirectorySeparatorChar + g.ToString() + ".eml"; FileStream newfile = new FileStream(NameOfFile, FileMode.Create); BinaryWriter wrtfile = new BinaryWriter(newfile); try { wrtfile.Write(eml); } finally { wrtfile.Close(); newfile.Close(); email.CloseConnection(); } } } ai.InsertActivity("5", "", UC.UserId.ToString(), C, A, L, mailsubject, mailbody, DateTime.UtcNow, UC, 1, false, docid, 0, 0); ClientScript.RegisterStartupScript(this.GetType(), "accretae", "<script>alert('" + Root.rm.GetString("WebMLtxt6") + "');</script>"); } else { ClientScript.RegisterStartupScript(this.GetType(), "accretae", "<script>alert('" + Root.rm.GetString("WebMLtxt7").Replace("'", "\'") + "');</script>"); } } else { ClientScript.RegisterStartupScript(this.GetType(), "accretae", "<script>alert('" + Root.rm.GetString("WebMLtxt7").Replace("'", "\'") + "');</script>"); } break; } }
private void Repeatermsg_ItemCommand(object source, RepeaterCommandEventArgs e) { switch (e.CommandName) { case "DeleteMail": try { DeleteClick(((Label)e.Item.FindControl("msgid")).Text, ((Label)e.Item.FindControl("msgMessageID")).Text); }catch {} break; case "OpenBody": this.dgmessages.Visible = true; Repeatermsg.Visible = false; long msgid = long.Parse(((Label)e.Item.FindControl("msgid")).Text); string MessageID = String.Empty; Message[] msgs = new Message[1]; ArrayList msgatt = new ArrayList(); string msgMessageID = ((Label)e.Item.FindControl("msgMessageID")).Text; string PathTemplate; PathTemplate = Path.Combine(ConfigSettings.DataStoragePath, String.Format("webmail{1}{0}{1}mails", UC.UserId, Path.DirectorySeparatorChar)); FileFunctions.CheckDir(PathTemplate, true); string NameOfFile = PathTemplate + Path.DirectorySeparatorChar + msgMessageID + ".tmsg"; if (!File.Exists(NameOfFile)) { DataRow dtPop3 = DatabaseConnection.CreateDataset("SELECT MAILSERVER,MAILUSER,MAILPASSWORD FROM ACCOUNT WHERE UID=" + UC.UserId).Tables[0].Rows[0]; string pop3 = dtPop3[0].ToString(); bool secure = false; if (pop3.StartsWith("!")) { pop3 = pop3.Substring(1); secure = true; } using (Pop3Client email = new Pop3Client(dtPop3[1].ToString(), dtPop3[2].ToString(), pop3, secure)) { try { email.OpenInbox(); email.AttachmentsPath = Path.Combine(ConfigSettings.DataStoragePath, String.Format("webmail{1}{0}{1}", UC.UserId, Path.DirectorySeparatorChar)); email.NextEmail(msgid); try { MessageID = (email.MessageID != null) ? Regex.Replace(email.MessageID.Trim('<', '>'), @"[^a-zA-Z0-9_]", "_") : ""; } catch { MessageID = String.Empty; } Message msg = new Message(); msg.From = (email.From != null && email.From.Length > 0) ? email.From : Root.rm.GetString("WebMLtxt11"); msg.To = (email.To != null && email.To.Length > 0) ? email.To : Root.rm.GetString("WebMLtxt11"); msg.Subject = (email.Subject != null && email.Subject.Length > 0) ? email.Subject : Root.rm.GetString("WebMLtxt11"); msg.MsgID = msgid; if (email.IsMultipart) { IEnumerator enumerator = email.MultipartEnumerator; Queue attach = new Queue(); string bodyhtml = null; string bodyplain = null; while (enumerator.MoveNext()) { Pop3Component multipart = (Pop3Component)enumerator.Current; if (multipart.IsBody) { if (multipart != null && multipart.ContentType.ToLower().IndexOf("text/html") > -1) { bodyhtml = multipart.Data; } else if (multipart != null && multipart.ContentType.ToLower().IndexOf("text/plain") > -1) { bodyplain = multipart.Data; //multipart.Data.Replace("\r","").Replace("\n","<br>"); } } else { if (multipart.ContentID != null && multipart.FilePath != null) { attach.Enqueue(multipart.ContentID); attach.Enqueue("/mailinglist/webmail/mailredir.aspx?render=no&att=1&img=" + multipart.FilePath.Replace(email.AttachmentsPath, "")); } else if (multipart.FilePath != null) { msgatt.Add(multipart.FilePath); } } } if (bodyhtml != null) { while (attach.Count > 0) { bodyhtml = Regex.Replace(bodyhtml, @"(?<=src=[""']?)cid:" + ((string)attach.Dequeue()).Trim('<', '>') + @"(?=[""']?)", (string)attach.Dequeue(), RegexOptions.IgnoreCase | RegexOptions.Multiline); } bodyhtml = Regex.Replace(bodyhtml, @"</?(html|body|link|meta)[\s\S]*?>", "", RegexOptions.IgnoreCase | RegexOptions.Multiline); bodyhtml = Regex.Replace(bodyhtml, @"<title[\s\S]*?</title[\s\S]*?>", "<body_not_allowed", RegexOptions.IgnoreCase | RegexOptions.Multiline); bodyhtml = Regex.Replace(bodyhtml, @"<(style|script|head)[\s\S]*?>", "<!--", RegexOptions.IgnoreCase | RegexOptions.Multiline); bodyhtml = Regex.Replace(bodyhtml, @"</(style|script|head)[\s\S]*?>", "-->", RegexOptions.IgnoreCase | RegexOptions.Multiline); bodyhtml = Regex.Replace(bodyhtml, @"(?<=<a)[ ](?=[\s\S]*?>)", " target=_blank ", RegexOptions.IgnoreCase | RegexOptions.Multiline); } if (bodyhtml != null) { msg.Body = bodyhtml; } else if (bodyplain != null) { msg.Body = bodyplain.Replace("\r", "").Replace("\n", "<br>"); } } else { if (email.IsHTML) { if (email.ContentTransferEncoding != null && email.ContentTransferEncoding.ToLower().Equals("quoted-printable")) { msg.Body = Pop3Utils.FromQuotedPrintable(email.Body); } else { msg.Body = email.Body; } msg.ContentType = "H"; } else { msg.ContentType = "P"; try { msg.Body = email.Body.Replace("\r", "").Replace("\n", "<br>"); } catch { msg.Body = String.Empty; } } } email.CloseConnection(); if (msgatt.Count > 0) { MessageAttach[] attach = new MessageAttach[msgatt.Count]; for (int i = 0; i < msgatt.Count; i++) { MessageAttach ma = new MessageAttach(); ma.Link = msgatt[i].ToString(); ma.Filename = Path.GetFileName(msgatt[i].ToString()); attach[i] = ma; } msg.Attachment = attach; } msgs[0] = msg; dgmessages.DataSource = msgs; dgmessages.DataBind(); tblpaging.Visible = false; if (MessageID.Length > 1) { PathTemplate = Path.Combine(ConfigSettings.DataStoragePath, String.Format("webmail{1}{0}{1}mails", UC.UserId, Path.DirectorySeparatorChar)); NameOfFile = PathTemplate + Path.DirectorySeparatorChar + MessageID + ".tmsg"; FileStream newfile = new FileStream(NameOfFile, FileMode.Create); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(newfile, msg); newfile.Close(); } } catch (Pop3PasswordException) { Context.Items.Add("warning", Root.rm.GetString("Mailtxt16")); } catch (Pop3LoginException) { Context.Items.Add("warning", Root.rm.GetString("Mailtxt17")); } catch (Pop3ConnectException) { Context.Items.Add("warning", Root.rm.GetString("Mailtxt16")); } catch (Pop3DecodeException) { Context.Items.Add("warning", Root.rm.GetString("Mailtxt25")); } catch (Pop3MissingBoundaryException) { Context.Items.Add("warning", Root.rm.GetString("Mailtxt25")); } } } else { Message msg = new Message(); FileStream newfile = new FileStream(NameOfFile, FileMode.Open); BinaryFormatter bf = new BinaryFormatter(); msg = (Message)bf.Deserialize(newfile); newfile.Close(); msgs[0] = msg; dgmessages.DataSource = msgs; dgmessages.DataBind(); tblpaging.Visible = false; } break; } }
private static void ObtainNewMails() { Pop3Client client = new Pop3Client(user, password, POP3Host); try { client.OpenInbox(); } catch (Pop3LoginException) { errUserOrPassword = true; return; } int num = 0; for (int i = 1; i <= client.MessageCount; i++) { string mailUidl = client.GetMailUidl(i); if (!mails.Contains(mailUidl)) { num++; mails.Add(mailUidl); } } client.CloseConnection(); if (num > 0) { SystemHintHelper.Show(string.Format("你共收到新的消息:{0}条", num)); } lastRequestTime = new DateTime?(DateTime.Now); }
private static void ReceiveMail() { XmlDocument doc = new XmlDocument(); doc.Load((string)cfg.GetValue("game.xml", typeof(string))); Pop3Client pop3 = new Pop3Client( (string)cfg.GetValue("pop3.username", typeof(string)), (string)cfg.GetValue("pop3.password", typeof(string)), (string)cfg.GetValue("pop3.server", typeof(string))); pop3.OpenInbox(); while (pop3.NextEmail()) { Log("Receiving \"" + pop3.Subject + "\" from " + pop3.From); string body; if (pop3.Charset == "koi8-r") { body = KoiToWin(pop3.Body); } else { body = pop3.Body; } string filename = ""; bool checker = false; bool save = true; string folder = (string)cfg.GetValue("mailbox", typeof(string)); if (pop3.Subject.ToLower() == "request") { int i = 1; while (File.Exists(Path.Combine(folder, "request." + i.ToString()))) { i++; } filename = "request." + i.ToString(); Log("..this is a request :)"); TextWriter tw = new StreamWriter(Path.Combine(folder, filename + ".confirm"), false, Encoding.GetEncoding(1251)); tw.WriteLine("To: " + pop3.From); tw.WriteLine("Subject: [Wasteland] Request confirmation"); tw.WriteLine(""); tw.WriteLine("Request accepted. Wait for next turn please."); tw.Close(); } else { string[] ss = body.Split('\n'); int i = 0; for (i = 0; i < ss.Length; i++) { string s = ss[i]; Regex re; // Orders re = new Regex(@"#orders (\d+) ""(.*?)"""); if (re.IsMatch(s)) { Match m = re.Match(s); string faction = m.Groups[1].Value; string password = m.Groups[2].Value; XmlElement elFaction = (XmlElement)doc.SelectSingleNode( String.Format("/game/faction[@num='{0}']", faction.Replace("'", ""))); if (elFaction == null) { Log("..faction " + faction + " not found"); } else if (elFaction.GetAttribute("password") != password) { Log("..wrong password for " + faction); } else { Log("..found orders for " + faction); filename = "order." + faction; checker = true; break; } } // Report resend re = new Regex(@"#resend (\d+) ""(.*?)"""); if (re.IsMatch(s)) { Match m = re.Match(s); string faction = m.Groups[1].Value; string password = m.Groups[2].Value; XmlElement elFaction = (XmlElement)doc.SelectSingleNode( String.Format("/game/faction[@num='{0}']", faction.Replace("'", ""))); if (elFaction == null) { Log("..faction " + faction + " not found"); } else if (elFaction.GetAttribute("password") != password) { Log("..wrong password for " + faction); } else { Log("..found resend request for " + faction); string gamedir = (string)cfg.GetValue("gamedir", typeof(string)); int turnnum = Convert.ToInt32(doc.SelectSingleNode("game/@turn").Value); string turnname = "turn." + (turnnum - 1).ToString(); FileInfo fi = new FileInfo(Path.Combine(Path.Combine(gamedir, turnname), "report." + faction)); if (fi.Exists) { fi.CopyTo(Path.Combine(folder, fi.Name), false); } checker = false; save = false; filename = "resend"; break; } } // Mail re = new Regex(@"#mail (person )?(\d+)( (\d+) ""(.*?)"")?"); if (re.IsMatch(s)) { Match m = re.Match(s); string person = m.Groups[1].Value; string to = m.Groups[2].Value; string faction = m.Groups[4].Value; string password = m.Groups[5].Value; XmlElement elFaction = (XmlElement)doc.SelectSingleNode( String.Format("/game/faction[@num='{0}']", faction.Replace("'", ""))); XmlElement elRecipient = null; XmlElement elPerson = null; if (person != "person ") { elRecipient = (XmlElement)doc.SelectSingleNode( String.Format("/game/faction[@num='{0}']", to.Replace("'", ""))); } else { elPerson = (XmlElement)doc.SelectSingleNode( String.Format("//person[@num='{0}']", to.Replace("'", ""))); if (elPerson != null) { elRecipient = (XmlElement)doc.SelectSingleNode( String.Format("/game/faction[@num='{0}']", elPerson.GetAttribute("faction"))); } } if (elFaction != null && elFaction.GetAttribute("password") != password) { Log("..wrong password for " + faction); } else if (elRecipient == null || elRecipient.GetAttribute("email") == "") { Log("..recipient " + to + " not found"); } else { Log("..found mail from " + faction); filename = "mail." + faction + "-" + to + "." + DateTime.Now.ToString("HHmmssfff"); TextWriter tw = new StreamWriter(Path.Combine(folder, filename), false, Encoding.GetEncoding(1251)); tw.WriteLine("To: " + elRecipient.GetAttribute("email")); string subj = "Subject: [Wasteland] Private message"; if (elFaction != null) { subj += " from " + elFaction.GetAttribute("name") + " (" + elFaction.GetAttribute("num") + ")"; } tw.WriteLine(subj); tw.WriteLine(""); if (elPerson != null) { tw.WriteLine("Message received by " + Translit(elPerson.GetAttribute("name")) + " (" + to + ")."); } for (int j = i + 1; j < ss.Length; j++) { if (ss[j].Trim() == "#end") { break; } tw.WriteLine(ss[j]); } tw.Close(); filename = "confirm." + faction + "-" + to + "." + DateTime.Now.ToString("HHmmssfff"); tw = new StreamWriter(Path.Combine(folder, filename), false, Encoding.GetEncoding(1251)); tw.WriteLine("To: " + pop3.From); tw.WriteLine("Subject: [Wasteland] Mail confirmation"); tw.WriteLine(""); if (elPerson == null) { tw.WriteLine("Message to " + elRecipient.GetAttribute("name") + " (" + to + ") sent."); } else { tw.WriteLine("Message to " + Translit(elPerson.GetAttribute("name")) + " (" + to + ") sent."); } tw.Close(); checker = false; save = false; break; } } } if (filename == "") { int j = 1; while (File.Exists(Path.Combine(folder, "spam." + j.ToString()))) { j++; } filename = "spam." + j.ToString(); Log("..this should be spam :/"); } } if (save) { TextWriter tw = new StreamWriter(Path.Combine(folder, filename), false, Encoding.GetEncoding(1251)); tw.WriteLine("From: " + pop3.From); tw.WriteLine("Subject: " + pop3.Subject); tw.WriteLine(""); tw.WriteLine(body); tw.Close(); } if (checker) { Log("Checking " + filename); RunEngine("/check " + Path.Combine(folder, filename)); } pop3.DeleteEmail(); } pop3.CloseConnection(); }
public static string FindAndRecordEmailBounces() { Pop3Client email = null; string message = string.Empty; try { email = new Pop3Client("*****@*****.**", "deadFax186", "mail.thebirthdayregister.com"); email.OpenInbox(); // only process x amount of messages at a time because deleting is not really done until the session is closed const long nMaxProcess = 2; long nTotalCount = Math.Min(nMaxProcess, email.MessageCount); long nMaxEmail = email.MessageCount; long nMinEmail = Math.Max(0, email.MessageCount - nMaxProcess); for (long i = nMaxEmail - 1; i >= nMinEmail; i--) { email.NextEmail(i); if (0 != string.Compare(email.To, "*****@*****.**", true)) { continue; } // check the subject, delete items as appropriate if (email.Subject.ToLower().Contains("delay")) { email.DeleteEmail(); } string szRecipient = "", szAction = "", szStatus = "", szTo = "", szFrom = "", szSubject = "", szDate = "", szReply_to = ""; if (email.Subject.ToLower().Contains("failure notice") || email.Subject.ToLower().Contains("Delivery Status Notification (Failure)") || email.Subject.ToLower().Contains("Mail Delivery Failure") || email.Subject.ToLower().Contains("Mail System Error - Returned Mail")) { if (!email.IsMultipart) { szTo = GetEmailFromValue(GetValueFromKey(email.Body, "To:")); szFrom = GetEmailFromValue(GetValueFromKey(email.Body, "From:")); szSubject = CleanSubject(GetValueFromKey(email.Body, "Subject:")); szDate = GetValueFromKey(email.Body, "Date:"); szRecipient = GetEmailFromValue(GetValueFromKey(email.Body, "Final-Recipient:")); szAction = GetValueFromKey(email.Body, "Action:"); szStatus = GetValueFromKey(email.Body, "Status:"); szReply_to = GetEmailFromValue(GetValueFromKey(email.Body, "Reply-To:")); } else { System.Collections.IEnumerator enumerator = email.MultipartEnumerator; while (enumerator.MoveNext()) { Pop3Component multipart = (Pop3Component)enumerator.Current; if (string.IsNullOrEmpty(szTo)) { szTo = GetEmailFromValue(GetValueFromKey(multipart.Data, "To:")); } if (string.IsNullOrEmpty(szTo)) { szTo = GetEmailFromValue(GetValueFromKey(multipart.Data, "Original-Recipient:")); } if (string.IsNullOrEmpty(szFrom)) { szFrom = GetEmailFromValue(GetValueFromKey(multipart.Data, "From:")); } if (string.IsNullOrEmpty(szSubject)) { szSubject = CleanSubject(GetValueFromKey(multipart.Data, "Subject:")); } if (string.IsNullOrEmpty(szDate)) { szDate = GetValueFromKey(multipart.Data, "Date:"); } if (string.IsNullOrEmpty(szDate)) { szDate = GetValueFromKey(multipart.Data, "Arrival-Date:"); } if (string.IsNullOrEmpty(szRecipient)) { szRecipient = GetEmailFromValue(GetValueFromKey(multipart.Data, "Final-Recipient:")); } if (string.IsNullOrEmpty(szAction)) { szAction = GetValueFromKey(multipart.Data, "Action:"); } if (string.IsNullOrEmpty(szStatus)) { szStatus = GetValueFromKey(multipart.Data, "Status:"); } if (string.IsNullOrEmpty(szReply_to)) { szReply_to = GetEmailFromValue(GetValueFromKey(multipart.Data, "Reply-To:")); } } } message = message + szTo + " | " + szFrom + " | " + szReply_to + " | " + szSubject + " | " + szDate + " <br/>"; email.DeleteEmail(); } } message = message + string.Format("Total message count: {0}, Process message count: {1}", email.MessageCount.ToString(), nTotalCount.ToString()); email.CloseConnection(); } catch (Exception ex) { if (null != email) { try { email.CloseConnection(); } catch { } } message = "Exception thrown in FindAndRecordEmailBounces. Message: " + ex.Message; } return(message); }