📄 pop3main.cs
字号:
using System;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;
using System.Text;
using System.Collections.Specialized;
using System.Xml;
using System.Data;
using System.Data.SqlClient;
using System.Timers;
using System.Web;
public class POP3Main
{
public int FetchIntervalInMinutes;
protected string config_file;
protected bool verbose;
protected string MessageInputFile;
protected string MessageOutputFile;
protected string ConnectionString;
protected string Pop3Server;
protected string SubjectMustContain;
protected string SubjectCannotContain;
protected string FromMustContain;
protected string FromCannotContain;
protected string DeleteMessagesOnServer;
protected string InsertBugUrl;
protected string ServiceUsername;
protected string ServicePassword;
protected Timer timer;
///////////////////////////////////////////////////////////////////
public POP3Main(string config_file, bool verbose)
{
this.config_file = config_file;
this.verbose = verbose;
// Do the first fetching of messages
do_work(null, null);
// continue working
resume();
}
///////////////////////////////////////////////////////////////////
public void pause()
{
timer.Enabled = false;
}
///////////////////////////////////////////////////////////////////
public void resume()
{
// Set up a timer so that we keep fetching messages
timer = new System.Timers.Timer();
timer.Elapsed+=new ElapsedEventHandler(do_work);
// Set the timer interval
timer.Interval=60 * 1000 * FetchIntervalInMinutes;
timer.Enabled=true;
}
///////////////////////////////////////////////////////////////////
protected void write_line(object o)
{
if (verbose)
{
Console.WriteLine(o);
}
}
///////////////////////////////////////////////////////////////////
public void do_work(object source, ElapsedEventArgs eea)
{
get_settings();
fetch_messages_for_projects();
}
///////////////////////////////////////////////////////////////////
protected void get_settings()
{
MessageInputFile = "";
MessageOutputFile = "";
ConnectionString = "";
Pop3Server = "";
SubjectMustContain = "";
SubjectCannotContain = "";
FromMustContain = "";
FromCannotContain = "";
DeleteMessagesOnServer = "";
InsertBugUrl = "";
ServiceUsername = "";
ServicePassword = "";
string filename = config_file;
XmlTextReader tr;
try
{
tr = new XmlTextReader(filename);
while(tr.Read())
{
if (tr.Name == "add")
{
if (tr["key"] == "MessageInputFile")
{
write_line(tr["key"] + "=" + tr["value"]);
MessageInputFile = tr["value"];
}
if (tr["key"] == "MessageOutputFile")
{
write_line(tr["key"] + "=" + tr["value"]);
MessageOutputFile = tr["value"];
}
if (tr["key"] == "ConnectionString")
{
write_line(tr["key"] + "=" + tr["value"]);
ConnectionString = tr["value"];
}
else if (tr["key"] == "Pop3Server")
{
write_line(tr["key"] + "=" + tr["value"]);
Pop3Server = tr["value"];
}
else if (tr["key"] == "SubjectMustContain")
{
write_line(tr["key"] + "=" + tr["value"]);
SubjectMustContain = tr["value"];
}
else if (tr["key"] == "SubjectCannotContain")
{
write_line(tr["key"] + "=" + tr["value"]);
SubjectCannotContain = tr["value"];
}
else if (tr["key"] == "FromMustContain")
{
write_line(tr["key"] + "=" + tr["value"]);
FromMustContain = tr["value"];
}
else if (tr["key"] == "FromCannotContain")
{
write_line(tr["key"] + "=" + tr["value"]);
FromCannotContain = tr["value"];
}
else if (tr["key"] == "DeleteMessagesOnServer")
{
write_line(tr["key"] + "=" + tr["value"]);
DeleteMessagesOnServer = tr["value"];
}
else if (tr["key"] == "FetchIntervalInMinutes")
{
write_line(tr["key"] + "=" + tr["value"]);
FetchIntervalInMinutes = Convert.ToInt32(tr["value"]);
}
else if (tr["key"] == "InsertBugUrl")
{
write_line(tr["key"] + "=" + tr["value"]);
InsertBugUrl = tr["value"];
}
else if (tr["key"] == "ServiceUsername")
{
write_line(tr["key"] + "=" + tr["value"]);
ServiceUsername = tr["value"];
}
else if (tr["key"] == "ServicePassword")
{
write_line(tr["key"] + "=" + tr["value"]);
ServicePassword = tr["value"];
}
}
}
}
catch (Exception e) {
write_line("Error trying to read file: " + filename);
write_line(e);
return;
}
}
///////////////////////////////////////////////////////////////////////
protected void fetch_messages_for_projects()
{
// Get the list of accounts to read
try
{
string sql = @"select
pj_id, pj_pop3_username, pj_pop3_password
from projects
where pj_enable_pop3 = 1";
DataSet ds = get_dataset(sql);
foreach (DataRow dr in ds.Tables[0].Rows)
{
write_line ("processing project:");
write_line(dr["pj_id"]);
write_line(dr["pj_pop3_username"]);
fetch_messages (
(string) dr["pj_pop3_username"],
(string) dr["pj_pop3_password"],
(int) dr["pj_id"]);
}
}
catch (Exception e) {
write_line("Error trying to process messages");
write_line(e);
return;
}
}
///////////////////////////////////////////////////////////////////////
protected void fetch_messages(string user, string password, int projectid)
{
string[] messages = null;
Regex regex = new Regex("\r\n");
string[] test_message_text = new string[100];
POP3Client.POP3client client = null;
if (MessageInputFile == "")
{
client = new POP3Client.POP3client();
write_line ("****connecting to server:");
write_line (client.connect (Pop3Server));
write_line ("sending POP3 command USER");
write_line (client.USER (user));
write_line ("sending POP3 command PASS");
write_line (client.PASS (password));
write_line ("sending POP3 command STAT");
write_line (client.STAT () );
write_line ("sending POP3 command LIST");
string list;
list = client.LIST ();
write_line ("list follows:");
write_line (list);
messages = regex.Split(list);
}
else
{
write_line ("opening input file " + MessageInputFile);
StreamReader sr = File.OpenText(MessageInputFile);
string test_messages = sr.ReadToEnd();
Regex test_regex = new Regex("Q6Q6\r\n");
test_message_text = test_regex.Split(test_messages);
}
string message;
int message_number = 0;
int start;
int end;
if (MessageInputFile == "")
{
start = 1;
end = messages.Length-1;
}
else
{
start = 0;
end = test_message_text.Length;
if (end > 99) end = 99;
}
// loop through the messages
for (int i = start;i < end; i++)
{
// fetch the message
write_line ("i:" + Convert.ToString(i));
if (MessageInputFile == "")
{
int space_pos = messages[i].IndexOf(" ");
message_number = Convert.ToInt32(messages[i].Substring(0,space_pos));
message = client.RETR (message_number);
}
else
{
message = test_message_text[message_number++];
}
// for diagnosing problems
if (MessageOutputFile != "")
{
System.IO.StreamWriter w = System.IO.File.AppendText(MessageOutputFile);
w.WriteLine(message);
w.Flush();
w.Close();
}
// break the message up into lines
string [] lines = regex.Split(message);
string from = "";
string subject = "";
bool encountered_subject = false;
bool encountered_from = false;
// Loop through the lines of a message.
// Pick out the subject and body
for (int j=0;j < lines.Length; j++)
{
if (lines[j].IndexOf("Subject: ") == 0 && !encountered_subject)
{
subject = lines[j].Replace("Subject: ","");
encountered_subject = true;
}
else if (lines[j].IndexOf("From: ") == 0 && !encountered_from)
{
from = lines[j].Replace("From: ","");
encountered_from = true;
}
} // end for each line
write_line("\nFrom: " + from);
write_line("Subject: " + subject);
if (SubjectMustContain != "" && subject.IndexOf(SubjectMustContain) < 0)
{
write_line("skipping because subject does not contain: " + SubjectMustContain);
continue;
}
if (SubjectCannotContain != "" && subject.IndexOf(SubjectCannotContain) >= 0)
{
write_line("skipping because subject cannot contain: " + SubjectCannotContain);
continue;
}
if (FromMustContain != "" && from.IndexOf(FromMustContain) < 0)
{
write_line("skipping because from does not contain: " + FromMustContain);
continue;
}
if (FromCannotContain != "" && from.IndexOf(FromCannotContain) >= 0)
{
write_line("skipping because from cannot contain: " + FromCannotContain);
continue;
}
write_line("calling insert_bug.aspx");
string Url = InsertBugUrl;
// Try to parse out the bugid from the subject line
int pos = subject.IndexOf("DO NOT EDIT THIS:");
if (pos >= 0)
{
// position of colon
pos=subject.IndexOf(":",pos);
pos++;
// position of close paren
int pos2=subject.IndexOf(")",pos);
if (pos2 > pos)
{
string bugid_string = subject.Substring(pos,pos2-pos);
write_line("BUGID=" + bugid_string);
try
{
int bugid = Int32.Parse(bugid_string);
Url += "?bugid=" + Convert.ToString(bugid);
write_line ("updating existing bug " + Convert.ToString(bugid));
}
catch(Exception e)
{
write_line("bugid not numeric " + e.Message);
}
}
}
string post_data = "username=" + HttpUtility.UrlEncode(ServiceUsername)
+ "&password=" + HttpUtility.UrlEncode(ServicePassword)
+ "&projectid=" + Convert.ToString(projectid)
+ "&from=" + HttpUtility.UrlEncode(from)
+ "&short_desc=" + HttpUtility.UrlEncode(subject)
+ "&message=" + HttpUtility.UrlEncode(message);
byte[] bytes = Encoding.UTF8.GetBytes(post_data);
// send request to web server
HttpWebResponse res = null;
try
{
HttpWebRequest req = (HttpWebRequest) System.Net.WebRequest.Create(Url);
req.Method = "POST";
req.ContentType= "application/x-www-form-urlencoded";
req.ContentLength=bytes.Length;
Stream request_stream = req.GetRequestStream();
request_stream.Write(bytes,0,bytes.Length);
request_stream.Close();
res = (HttpWebResponse) req.GetResponse();
}
catch (Exception e)
{
write_line("HttpWebRequest error url=" + Url);
write_line(e);
}
// examine response
if (res != null) {
int http_status = (int) res.StatusCode;
string http_response_header = res.Headers["BTNET"];
write_line (Convert.ToString(http_status));
write_line (http_response_header);
res.Close();
// only delete message from pop3 server if we
// know we stored in on the web server ok
if (MessageInputFile == ""
&& http_status == 200
&& DeleteMessagesOnServer == "1"
&& http_response_header.IndexOf("OK") == 0)
{
write_line ("sending POP3 command DELE");
write_line (client.DELE (message_number));
}
}
} // end for each message
if (MessageInputFile == "")
{
write_line ("\nsending POP3 command QUIT");
write_line (client.QUIT ());
}
else
{
write_line ("\nclosing input file " + MessageInputFile);
}
}
///////////////////////////////////////////////////////////////////////
protected DataSet get_dataset(string sql)
{
DataSet ds = new DataSet();
SqlConnection conn = new SqlConnection(ConnectionString);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
da.Fill(ds);
return ds;
}
};
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -