0% found this document useful (0 votes)
598 views17 pages

Email Tray Tool: POP3 Email Client

This document contains code for a C# application that checks an email server for new messages via POP3 and notifies the user when new emails arrive. It minimizes to the system tray and displays a tooltip. When clicked, it retrieves new emails and displays them. The code connects to a POP3 server, logs in with credentials, retrieves messages, and disconnects. It also contains code to load configuration settings from a database.

Uploaded by

JoeDabid
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
598 views17 pages

Email Tray Tool: POP3 Email Client

This document contains code for a C# application that checks an email server for new messages via POP3 and notifies the user when new emails arrive. It minimizes to the system tray and displays a tooltip. When clicked, it retrieves new emails and displays them. The code connects to a POP3 server, logs in with credentials, retrieves messages, and disconnects. It also contains code to load configuration settings from a database.

Uploaded by

JoeDabid
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 17

/* * Created by SharpDevelop.

* User: User * Date: 6/16/2012 * Time: 8:23 AM * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using using using using using using using using using using using using using using using using using using using using using System; [Link]; [Link]; [Link]; [Link]; [Link]; [Link]; [Link]; [Link]; [Link]; [Link]; [Link]; [Link]; [Link]; [Link].X509Certificates; [Link]; [Link]; [Link]; [Link]; OpenPop.Pop3; Email_Tray_Tool_Config;

namespace Email_Tray_Tool { public partial class EmailTrayTool : Form { private string dbConnection = "Data Source=Config.s3db"; private string InfoText = "Email Tray Tool V.1"; private string TrayInfoText = "XXX Team Email Notification"; private string myServer; private string myPort; private string mySSL; private string myUsername; private string myPassword; private int MsgIndexNum; private int messageCount; private int emailMsgsUnread; private [Link] SelectedMsg; private frm_Config ConfigForm; private int triggerminutes; private DateTime IconSavedTime; private DateTime TimerSavedTime; public EmailTrayTool() { InitializeComponent(); } // based on tutorials in // [Link] ication-minimize-to-system-tray-in-c%23/

// [Link] // [Link] -POP3-Server-Using-C // [Link] ton-on-Forms // [Link] tion10282006032802am/[Link] // [Link] [Link] // [Link] -[Link] // [Link] /894d0814-dcf1-4cd6-9cca-2c6239794442/ // [Link] // // Disable close button /* // POP3 Mail Ver. 1 public TcpClient Server; public NetworkStream NetStrm; public StreamReader RdStrm; public string Data; public byte[] szData; public string CRLF = "\r\n"; // Connect to POP3 private void ConnectToPop3() { string PopServer = "[Link]"; string UserName = "user"; string PassWord = "mypass"; // change cursor into wait cursor Cursor cr = [Link]; [Link] = [Link]; // create server POP3 with port 110 Server = new TcpClient(PopServer, 110); [Link](); try { // initialization NetStrm = [Link](); RdStrm = new StreamReader([Link]()); [Link]([Link]()); // Login Process Data = "USER " + UserName + CRLF; szData = [Link]([Link]()) ; [Link](szData, 0, [Link]); [Link]([Link]()); Data = "PASS " + PassWord + CRLF; szData = [Link]([Link]()) ; [Link](szData, 0, [Link]); [Link]([Link]());

// Send STAT command to get information ie: number of mail and s ize Data = "STAT" + CRLF; szData = [Link]([Link]()) ; [Link](szData, 0, [Link]); [Link]([Link]()); // change enabled - disabled button [Link] = false; [Link] = true; [Link] = true; // back to normal cursor [Link] = cr; } catch (InvalidOperationException err) { [Link]("Error: " + [Link]()); } } private void DisconnectPop3() { // change cursor into wait cursor Cursor cr = [Link]; [Link] = [Link]; // Send QUIT command to close session from POP server Data = "QUIT" + CRLF; szData = [Link]([Link]()); [Link](szData, 0, [Link]); [Link]([Link]()); //close connection [Link](); [Link](); // change enabled - disabled button [Link] = true; [Link] = false; [Link] = false; // back to normal cursor [Link] = cr; [Link](); } private void RetrievePop3() { string EmailNum = tbx_Num.Text; // change cursor into wait cursor Cursor cr = [Link]; [Link] = [Link]; string szTemp; [Link](); try { // retrieve mail with number mail parameter

Data = "RETR " + EmailNum + CRLF; szData = [Link]([Link]()) ; [Link](szData, 0, [Link]); szTemp = [Link](); if (szTemp[0] != '-') { while (szTemp != ".") { [Link] += szTemp; szTemp = [Link](); } } else { [Link](szTemp); } // back to normal cursor [Link] = cr; } catch (InvalidOperationException err) { [Link]("Error: " + [Link]()); } } private void ConnectBtn_Click(object sender, EventArgs e) { ConnectToPop3(); } private void DisconnectBtn_Click(object sender, EventArgs e) { DisconnectPop3(); } private void RetrieveBtn_Click(object sender, EventArgs e) { RetrievePop3(); } // end POP3 Mail V.1 */ private const int CP_NOCLOSE_BUTTON = 0x200; protected override CreateParams CreateParams { get { CreateParams myCp = [Link]; [Link] = [Link] | CP_NOCLOSE_B UTTON ; return myCp;

} } // End Disable close button private void OnListBoxMouseMove ( object sender, MouseEventArgs e ) { ///string strTip = "To open, highlight email and double click, right click for other menu..."; //Get the item ///int nIdx = [Link]([Link]); /* * Display tip as mouse is moved over e-mail headers if ((nIdx >= 0) && (nIdx < [Link])) strTip = strTip + ": " + [Link][nIdx].T oString(); */ ///tT_MsgListbox.SetToolTip(myMessage, strTip); } private void EmailTrayToolLoad(object sender, EventArgs e) { // TimerSavedTime = [Link]; IconSavedTime = [Link]; [Link] = InfoText; [Link] = (int)(([Link])/2 .5); [Link] = (int)(([Link]) /4); [Link] = [Link]; [Link] = false; [Link](); LoadConfig(); DeleteUsedMsgFile(); [Link](2000); // checks after 2 sec since startup CheckUnreadMsgs(); } private int MsgLimit() { int limit = 0; if (Convert.ToInt32(tST_MsgLimit.Text) <= 1) { tST_MsgLimit.Text = "1"; limit = 1; } else limit = Convert.ToInt32(tST_MsgLimit.Text); return limit; } private void LoadConfig() { tmr_CheckMsg.Stop(); try { string query = "select UserName \"User Name\", " ;

query += "Password \"Password\", "; query += "ServerName \"Server Name\", "; query += "Port \"Port\", "; query += "SSL \"SSL\" "; query += "from tbl_Settings "; query += "limit 1;"; DataTable savedConfig = GetDataTable(dbConnectio n, query); DataGrid savedConfigDataGrid = new DataGrid(); [Link] = savedConfig; foreach (DataRow row in [Link]) { myUsername = row["User Name"].ToString() ; myPassword = row["Password"].ToString(); myServer = row["Server Name"].ToString() ; myPort = row["Port"].ToString(); mySSL = row["SSL"].ToString(); } [Link](); [Link](); // } catch(Exception fail) { string error = "Error in verifying database for POP3 E-mail Account:\n\n"; error += [Link]() + "\n\n"; [Link](error); } tmr_CheckMsg.Start(); } private DataTable GetDataTable(string dbConnection, string sql) { DataTable dt = new DataTable(); try { SQLiteConnection cnn = new SQLiteConnection(dbCo nnection); [Link](); SQLiteCommand mycommand = new SQLiteCommand(cnn) ; [Link] = sql; SQLiteDataReader reader = [Link] r(); [Link](reader); [Link](); [Link](); } catch (Exception e) { throw new Exception([Link]); } return dt; } private void MsgListbox_Resize() {

[Link] = (int)([Link]); [Link] = (int)([Link]); if ([Link] < (int)([Link] ht / 6)) [Link] = (int)([Link]. Height / 6); if ([Link] < (int)([Link] / 4)) [Link] = (int)([Link].W idth /4); } private void EmailTrayToolWindow_Resize(object sender, EventArgs e) { MsgListbox_Resize(); } private void EmailTrayTool_Resize(object sender, EventArgs e) { if ([Link] == [Link]) { tmr_CheckMsg.Start(); [Link](); ShowTrayToolTip(true, 2000);; } } private void ntIcon_techteam_DoubleClick(object sender, EventArg s e) { [Link](); [Link] = [Link]; MsgListbox_Resize(); UpdateFromEmailServer(); } private void tSM_CloseApp_Click(object sender, EventArgs e) { if ([Link]("Are you sure you want to end monito ring new e-mails?", "E-mail Tray Tool Closing Verificati on Note", [Link], MessageBoxI [Link]) == [Link]) { tmr_CheckMsg.Stop(); tmr_CheckMsg.Dispose(); DeleteUsedMsgFile(); [Link](); } } private void tSM_ConfigEmail_Click(object sender, EventArgs e) { [Link](); ConfigForm = new frm_Config(); [Link] = true; [Link]();

} private void tSM_ConfigAdmin_Click(object sender, EventArgs e) { [Link](); ConfigForm = new frm_Config(); [Link] = true; [Link](); } private void tSM_HideMenu_Click(object sender, EventArgs e) { [Link] = [Link]; [Link](); tmr_CheckMsg.Start(); } private void tSM_ReadEmail_Click(object sender, EventArgs e) { [Link](); [Link] = [Link]; MsgListbox_Resize(); UpdateFromEmailServer(); } private void tSM_EmailTimer_Click(object sender, EventArgs e) { [Link](); ConfigForm = new frm_Config(); [Link] = true; [Link](); } private void numMsg_Click(object sender, EventArgs e) { UpdateFromEmailServer(); } private void TS_RefreshClick(object sender, EventArgs e) { UpdateFromEmailServer(); } // POP3 Mail V.2 private void UpdateFromEmailServer() { // LoadConfig(); ShowHeaders(myServer, myPort, mySSL, myUsername, myPassw ord, MsgLimit()); } private void ShowHeaders(string hostname, string port, string us eSsl, string username, string password, int limit) { tmr_CheckMsg.Stop(); [Link](); [Link] = InfoText + " - Updating from Email Server, p lease wait..."; int portnum = Convert.ToInt32(port);

bool SSL = false; if ([Link]() == "yes") SSL = true; else SSL = false; using (Pop3Client client = new Pop3Client()) { [Link](hostname, portnum, SSL); [Link](username, password); messageCount = [Link](); int diff = (messageCount - limit) + 1; int unreadmsgs = 0; int readmsgs = 0; string emailCount = [Link](); string MsgInfo = ""; string date = ""; string subject = ""; string sender = ""; if (diff >= 1) { for (int i = messageCount; i >= diff; i-) { MessageHeader headers = client.G etMessageHeaders(i); date = [Link] (); subject = [Link] ng(); sender = [Link]() ; if (MsgHeaderDB_NewMsg(date, sub ject, sender)) { unreadmsgs++; MsgInfo = "Message Unrea d => Date: " + date + " || Subject: " + subject + " || From:" + sender; } else //e-mail previously read { readmsgs++; MsgInfo = "Already Read => Date: " + date + " || Subject: " + subject + " || From:" + sender; } [Link] (MsgInfo); } } else { for (int i = messageCount; i >= 1 ; i--) { MessageHeader headers = client.G etMessageHeaders(i); date = [Link] (); subject = [Link] ng(); sender = [Link]() ;

if (MsgHeaderDB_NewMsg(date, sub ject, sender)) { unreadmsgs++; MsgInfo = "Message Unrea d => Date: " + date + " || Subject: " + subject + " || From:" + sender; } else //e-mail previously read { readmsgs++; MsgInfo = "Already Read => Date: " + date + " || Subject: " + subject + " || From:" + sender; } [Link] (MsgInfo); } } // [Link] (""); [Link] ("Summary: " + [Link] ring() + " read e-mails, " + [Link]() + " u nread. " + "A total of " + (readmsgs + unreadmsgs).ToString() + " emails shown out of " + e mailCount + " total received messages (of which "+ emailMsgsUnread + " are unr ead)."); [Link] (""); [Link] ("Retrieving e-mail list fro m server may take long time to complete."); [Link] ("To open, highlight email a nd double click, right click for other menus."); [Link] ("E-mails with photos/graphi cs or attachments may take longer time to open..."); [Link] (""); [Link] ("To show the other e-mails, right-click to change setting for the number " + "of shown messages (default of 5 e-mails). "); [Link] ("E-mail messages shown from most recent (top most) downwards."); [Link](); [Link] = InfoText; } tmr_CheckMsg.Start(); } private int MsgsUnread(string hostname, string port, string useS sl, string username, string password) { int newmsgs = 0; int portnum = Convert.ToInt32(port); bool SSL = false; if ([Link]() == "yes") SSL = true; else SSL = false; using (Pop3Client client = new Pop3Client())

{ [Link](hostname, portnum, SSL); [Link](username, password); messageCount = [Link](); string date = ""; string subject = ""; string sender = ""; for (int i = messageCount; i > 1; i--) { MessageHeader headers = [Link] eHeaders(i); date = [Link](); subject = [Link]().Rep lace("'","''"); // avoid single quote errors sender = [Link](); if (MsgHeaderDB_NewMsg(date, subject, se nder)) { newmsgs++; } } // [Link](); } return newmsgs; } private bool LoadedSelectedMsg(string hostname, string port, str ing useSsl, string username, string password) { tmr_CheckMsg.Stop(); bool loaded = false; int portnum = Convert.ToInt32(port); bool SSL = false; if ([Link]() == "yes") SSL = true; else SSL = false; using (Pop3Client client = new Pop3Client()) { [Link](hostname, portnum, SSL); [Link](username, password); messageCount = [Link](); int index = messageCount - MsgIndexNum; if (index > 0 && index > (messageCount - Convert .ToInt32(tST_MsgLimit.Text))) { SelectedMsg = [Link](index); loaded = true; } else { loaded = false; } [Link](); } tmr_CheckMsg.Start(); return loaded; }

private void MyMessageMouseDoubleClick(object sender, MouseEvent Args e) { if ([Link] != null) { MsgIndexNum = [Link]; LoadConfig(); if (LoadedSelectedMsg(myServer, myPort, mySSL, m yUsername, myPassword)) { [Link] = InfoText + " - Opening Selec ted Message from Email Server, please wait..."; StoreAndOpenMsg(SelectedMsg); UpdateFromEmailServer(); [Link] = InfoText; } } } private bool MsgHeadrDB_Inserted() { tmr_CheckMsg.Stop(); bool inserted = false; string date = [Link](); string subject = [Link](). Replace("'","''"); string from = [Link](); try { SQLiteConnection cnn = new SQLiteConnection(dbCo nnection); [Link](); SQLiteCommand mycommand = new SQLiteCommand(cnn) ; string cmd = "insert into tbl_MessageHeader "; cmd += "values (null, '" + date + "', '" + subje ct + "', '" + from + "');"; [Link] = cmd; SQLiteDataReader reader = [Link] r(); [Link](); [Link](); inserted = true; } catch(Exception fail) { inserted = false; string error = "Error in saving e-mail header to database:\n\n"; error += [Link]() + "\n\n"; [Link](error); } tmr_CheckMsg.Start(); return inserted; } private bool MsgHeaderDB_NewMsg(string date, string subject, str ing sender) {

bool newmsg = true; string myquery = ""; string subject2 = [Link]("'","''"); // avoid si ngle quote errors myquery myquery myquery myquery myquery try { DataTable savedhdr = GetDataTable(dbConnection, myquery); DataGrid savedhdrDataGrid = new DataGrid(); [Link] = savedhdr; foreach (DataRow row in [Link]) { if (Convert.ToInt32(row["MsgID"].ToStrin g()) > 0) // header exists means not new newmsg = false; else newmsg = true; } [Link](); [Link](); // } catch(Exception err) { string error = "Error in comparing e-mail header with database:\n\n"; error += [Link]() + "\n\n"; [Link](error); } return newmsg; } private void SaveSelectedMsgHeader() { if (MsgHeadrDB_Inserted()) { //[Link]("Viewed e-mail headers saved.. ."); } else [Link]("Error saving headers of viewed e-mails..."); } private void ShowToolTrayTip(object sender, MouseEventArgs e) { ShowTrayToolTip(false, 500); } private void ChangeIcon() { DateTime GetTime = [Link]; TimeSpan timediff = GetTime - IconSavedTime; if ([Link] > 1) // change tray icon every 2 se = "select MsgID "; += "from tbl_MessageHeader "; += "where Date = '"+ date + "' "; += "and MsgSubject = '" + subject2 + "' "; += "and Sender = '" + sender + "';";

c { ntIcon_techteam.Icon = new Icon("techteam2_msg.i co"); if ([Link] > 2) IconSavedTime = [Link]; } else // 2 sec normal icon { ntIcon_techteam.Icon = new Icon("[Link]") ; } } private void ShowTrayToolMsgIcon() { if (emailMsgsUnread > 0) ChangeIcon(); } private void ShowTrayToolTip(bool startup, int msec) { string unreadmsgPrompt; if (startup) { unreadmsgPrompt = "Note: Notification for new emails active..."; ntIcon_techteam.Icon = new Icon("[Link]") ; } else { unreadmsgPrompt = "Note: " + [Link] tring() + " messages unread!...Click here or the tray icon to view.."; if (emailMsgsUnread > 0) ChangeIcon(); } ntIcon_techteam.ShowBalloonTip(msec, "XXX Technical Team ", unreadmsgPrompt, [Link]); } private void CheckUnreadMsgs() { // Check unread messages // Only if minimized to tray tmr_CheckMsg.Start(); if ([Link] == [Link]) { [Link](); emailMsgsUnread = MsgsUnread(myServer, myPort, m ySSL, myUsername, myPassword); if (emailMsgsUnread > 0) { LoadConfig(); ShowTrayToolTip(false, 3000); ntIcon_techteam.Text = "XXX Tech. Team: "+ emailMsgsUnread + " E-mails unread, double click icon to show."; } else {

ntIcon_techteam.Text = TrayInfoText; } } else //normal window state { UpdateFromEmailServer(); } } private void DeleteMsgFile(string filepath) { try { [Link](filepath); } catch (IOException) { // Error in deletion } // } private void DeleteUsedMsgFile() { FileInfo file = new FileInfo("[Link]"); DeleteMsgFile([Link]()); // } private void StoreAndOpenMsg([Link] message) { // Save/load message FileInfo file = new FileInfo("[Link]"); // Delete existing file first DeleteMsgFile([Link]()); // try { [Link](file); [Link](@"[Link]") ; SaveSelectedMsgHeader(); } catch(Exception fail) { string error = "Unable to read selected e-mail:\ n\n"; error += [Link]() + "\n\n"; [Link](error); } } private int TimerSettingValue() { int timer = 30; try { string query = "select Timer \"Timer\" ";

query += "from tbl_Password "; query += "where UserName = \"admin\" limit 1;"; DataTable tmr = GetDataTable(dbConnection, query ); DataGrid tmrDataGrid = new DataGrid(); [Link] = tmr; foreach (DataRow row in [Link]) { timer = Convert.ToInt32(row["Timer"].ToS tring()); } [Link](); [Link](); } catch(Exception fail) { string error = "Error in getting database value of timer:\n\n"; error += [Link]() + "\n\n"; [Link](error); } return timer; } private int ElapsedTime() { int elapsed = 0; DateTime GetTime = [Link]; TimeSpan timediff = GetTime - TimerSavedTime; elapsed = [Link]; TimerSavedTime = [Link]; return elapsed; } private void timer_Count_Tick(object sender, EventArgs e) { ShowTrayToolMsgIcon(); // if (triggerminutes != TimerSettingValue()) { triggerminutes = TimerSettingValue(); } if (ElapsedTime() >= triggerminutes) { CheckUnreadMsgs(); } } // End POP3 Mail V.2 void TS_AboutClick(object sender, EventArgs e) { string msg = "E-mail Tray Tool V.1 software developed by JG Paramo "; msg += "for xxx (c) xxxx. Development and SDK tools "; msg += "include SharpDevelop (C# language), SQLite, .Net 2.0 Framework, and [Link]. "; msg += "System requirements: Windows XP or later, .Net 2 .0"; [Link](msg, "", [Link], MessageBo

[Link]); } } }

You might also like