From: <che...@us...> - 2008-04-26 17:02:32
|
Revision: 1723 http://mp-plugins.svn.sourceforge.net/mp-plugins/?rev=1723&view=rev Author: chef_koch Date: 2008-04-26 10:02:11 -0700 (Sat, 26 Apr 2008) Log Message: ----------- moved MyMail to mp-Plugins Added Paths: ----------- trunk/plugins/MyMail/ trunk/plugins/MyMail/GUIMyMailPlugin.cs trunk/plugins/MyMail/MailClass.cs trunk/plugins/MyMail/MailDetailSetup.cs trunk/plugins/MyMail/MailDetailSetup.resx trunk/plugins/MyMail/MailInfo.cs trunk/plugins/MyMail/MailOverlay.cs trunk/plugins/MyMail/MailSetupFrom.cs trunk/plugins/MyMail/MailSetupFrom.resx trunk/plugins/MyMail/MyMail.csproj trunk/plugins/MyMail/MyMail.xmp trunk/plugins/MyMail/Properties/ trunk/plugins/MyMail/Properties/AssemblyInfo.cs trunk/plugins/MyMail/skinfiles/ trunk/plugins/MyMail/skinfiles/BlueTwo/ trunk/plugins/MyMail/skinfiles/BlueTwo/mailInfo.xml trunk/plugins/MyMail/skinfiles/BlueTwo/mailnotify.xml trunk/plugins/MyMail/skinfiles/BlueTwo/mymail.xml trunk/plugins/MyMail/skinfiles/BlueTwo wide/ trunk/plugins/MyMail/skinfiles/BlueTwo wide/mailInfo.xml trunk/plugins/MyMail/skinfiles/BlueTwo wide/mailnotify.xml trunk/plugins/MyMail/skinfiles/BlueTwo wide/mymail.xml Added: trunk/plugins/MyMail/GUIMyMailPlugin.cs =================================================================== --- trunk/plugins/MyMail/GUIMyMailPlugin.cs (rev 0) +++ trunk/plugins/MyMail/GUIMyMailPlugin.cs 2008-04-26 17:02:11 UTC (rev 1723) @@ -0,0 +1,654 @@ +#region Copyright (C) 2005-2008 Team MediaPortal + +/* + * Copyright (C) 2005-2008 Team MediaPortal + * http://www.team-mediaportal.com + * + * This Program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2, or (at your option) + * any later version. + * + * This Program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GNU Make; see the file COPYING. If not, write to + * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. + * http://www.gnu.org/copyleft/gpl.html + * + */ + +#endregion + +using System; +using System.Windows.Forms; +using System.Collections; + +using MediaPortal.Configuration; +using MediaPortal.Dialogs; +using MediaPortal.GUI.Library; + +namespace MediaPortal.GUI.MyMail +{ + /// <summary> + /// Zusammenfassung f\xFCr Class1. + /// </summary> + public class MyMailPlugin : GUIWindow, ISetupForm, IShowPlugin + { + + public MyMailPlugin() + { + GetID = 8000; + } + ~MyMailPlugin() + { + } + + #region "Declares" + // + enum Controls + { + CONTROL_LIST = 50, + CONTROL_LABELFILES = 1, + CONTROL_REFRESH_ALL = 20, + CONTROL_SWITCH_AUTOCHECK, + CONTROL_SET_ALL_UNREAD + + } + // + enum Views + { + VIEW_MAILBOX = 1, + VIEW_MAILS, + VIEW_ERROR_HAPPEND // here we dont set the list to view what happend + } + // + enum MailActions + { + ACTION_VIEW_MAILBOX = 1, // thats reserved. dont use it. + ACTION_LIST_MAILS, + ACTION_REFRESH_MAILBOX, + ACTION_TIMER_EVENT, + ACTION_DO_NOTHING, + ACTION_DELETE_MAIL + } + // + enum AutocheckStatus + { + AUTOCHECK_OFF = 0, + AUTOCHECK_ON + } + // + ArrayList m_mailBox = new ArrayList(); // stored mailboxes + MailClass m_mc = new MailClass(); // our class with the comm-parts + MailBox m_currMailBox; // the selected Mailbox + bool m_autoCheck; + bool m_bAutoCheck; // indicates auto check mails on/off + int m_currentView; + int m_currMailAction; + MailBox m_prevMailBox; + // this timer checks the inbox(es) for mail + System.Windows.Forms.Timer m_checkMailTimer = new Timer(); + ArrayList m_strUserName = new ArrayList(); + ArrayList m_strUserPass = new ArrayList(); + ArrayList m_knownMails = new ArrayList(); + #endregion + + #region ISetupForm + public bool HasSetup() + { + return true; + } + public string PluginName() + { + return "My Mail"; + } + public string Description() // Return the description which should b shown in the plugin menu + { + return "Receive and read your mails in MediaPortal"; + } + public string Author() // Return the author which should b shown in the plugin menu + { + return "_Agree_"; + } + public void ShowPlugin() // show the setup dialog + { + System.Windows.Forms.Form setup = new MailSetupFrom(); + setup.ShowDialog(); + } + public bool CanEnable() // Indicates whether plugin can be enabled/disabled + { + return true; + } + public int GetWindowId() // get ID of plugin window + { + return GetID; + } + public bool DefaultEnabled() // Indicates if plugin is enabled by default; + { + return false; + } + public bool GetHome(out string strButtonText, out string strButtonImage, out string + strButtonImageFocus, out string strPictureImage) + { + strButtonText = GUILocalizeStrings.Get(8000); + strButtonImage = ""; + strButtonImageFocus = ""; + strPictureImage = "hover_my mail.png"; + return true; + } + + #endregion + + #region IShowPlugin Members + + public bool ShowDefaultHome() + { + return false; + } + + #endregion + + public override bool Init() + { + // the event handler function gets the mail-data + m_mc.GotMailData += new MyMail.MailClass.GotMailDataEventHandler(m_mc_GotMailData); + m_mc.InformUser += new MyMail.MailClass.InformEventHandler(m_mc_InformUser); + LoadSettings(); + + if (m_mailBox.Count > 0) // when at least 1 mailbox is given + { + m_checkMailTimer.Tick += new EventHandler(checkMails); + m_checkMailTimer.Start(); + DisplayOverlayNotify(false, ""); + m_checkMailTimer.Enabled = true; + m_currentView = (int)Views.VIEW_MAILBOX; // for init show mailboxes + } + else + { + DisplayOverlayNotify(false, ""); + } + bool bResult = Load(GUIGraphicsContext.Skin + @"\mymail.xml"); + + return bResult; + } + + public override bool OnMessage(GUIMessage message) + { + switch (message.Message) + { + case GUIMessage.MessageType.GUI_MSG_WINDOW_INIT: + base.OnMessage(message); + GUIPropertyManager.SetProperty("#currentmodule", GUILocalizeStrings.Get(8000)); + + if (m_mailBox.Count == 0) // when at least 1 mailbox is given, + { + GUIDialogOK dlgOK = (GUIDialogOK)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_OK); + if (dlgOK != null) + { + dlgOK.SetHeading(8010); + dlgOK.SetLine(1, 8011); + dlgOK.SetLine(2, 8012); + dlgOK.SetLine(3, ""); + dlgOK.DoModal(GetID); + } + } + else + { + SetAutoCheckButton(); + m_autoCheck = false; + m_checkMailTimer.Stop(); + if (m_currentView == (int)Views.VIEW_MAILBOX) + SetMailBoxList(); + else + SetMailsList(); + } + return true; + + + + case GUIMessage.MessageType.GUI_MSG_WINDOW_DEINIT: + SaveSettings(); + m_checkMailTimer.Start(); + break; + + case GUIMessage.MessageType.GUI_MSG_CLICKED: + int iControl = message.SenderControlId; + if (iControl == (int)Controls.CONTROL_SET_ALL_UNREAD) + { + // unread all + foreach (MailBox mb in m_mailBox) + { + if (System.IO.File.Exists(mb.MailboxFolder + @"\knownmails.txt")) + System.IO.File.Delete(mb.MailboxFolder + @"\knownmails.txt"); + if (System.IO.File.Exists(mb.MailboxFolder + @"\transferList.txt")) + System.IO.File.Delete(mb.MailboxFolder + @"\transferList.txt"); + } + SetMailBoxList(); + } + if (iControl == (int)Controls.CONTROL_SWITCH_AUTOCHECK) + { + if (m_bAutoCheck == true) + m_bAutoCheck = false; + else + m_bAutoCheck = true; + + GUIToggleButtonControl theControl = (GUIToggleButtonControl)GUIWindowManager.GetWindow(GetID).GetControl(iControl); + if (theControl != null) + { + theControl.Selected = m_bAutoCheck; + SetAutoCheckButton(); + } + } + + if (iControl == (int)Controls.CONTROL_REFRESH_ALL) + { + RefreshAllBoxes(0); + } + + if (iControl == (int)Controls.CONTROL_LIST) + { + GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_ITEM_SELECTED, GetID, 0, iControl, 0, 0, null); + OnMessage(msg); + int iItem = (int)msg.Param1; + int iAction = (int)message.Param1; + if (iAction == (int)Action.ActionType.ACTION_SELECT_ITEM) + { + OnClick(iItem); + } + } + break; + + } + + return base.OnMessage(message); + } + + public override void OnAction(Action action) + { + if (action.wID == Action.ActionType.ACTION_PREVIOUS_MENU) + { + GUIWindowManager.ShowPreviousWindow(); + return; + } + base.OnAction(action); + } + private void checkMails(object sender, System.EventArgs e) + { + if (m_mailBox.Count > 0) + if (m_bAutoCheck) + { + m_autoCheck = true; + RefreshAllBoxes(0); + } + } + // + // handle data income + private void m_mc_InformUser(int msgNum, object data) + { + if ((int)GUIWindowManager.ActiveWindow == GetID) + { + string strObjects = String.Format("{0} {1}...", GUILocalizeStrings.Get(msgNum), (string)data); + GUIPropertyManager.SetProperty("#itemcount", strObjects); + GUIControl ctrl = GetControl((int)Controls.CONTROL_LABELFILES); + if (ctrl != null) + GUIControl.SetControlLabel(GetID, (int)Controls.CONTROL_LABELFILES, strObjects); + } + + } + private void m_mc_GotMailData(object eventObject, string mailText, int results) + { + int newMailsCount = 0; + // error handling + switch (results) + { + case 1:// timeout error + if ((int)GUIWindowManager.ActiveWindow == GetID) + { + string strObjects = String.Format("{0} '{1}'", "(!)Timeout", m_currMailBox.BoxLabel); + GUIPropertyManager.SetProperty("#itemcount", strObjects); + GUIControl ctrl = GetControl((int)Controls.CONTROL_LABELFILES); + if (ctrl != null) + GUIControl.SetControlLabel(GetID, (int)Controls.CONTROL_LABELFILES, strObjects); + } + m_currentView = (int)Views.VIEW_ERROR_HAPPEND; + break; + case 999:// this is an extended error, the message is from the mail server + if ((int)GUIWindowManager.ActiveWindow == GetID) + { + string strObjects = String.Format("{0} '{1}'", (string)eventObject, m_currMailBox.BoxLabel); + GUIPropertyManager.SetProperty("#itemcount", strObjects); + GUIControl ctrl = GetControl((int)Controls.CONTROL_LABELFILES); + if (ctrl != null) + GUIControl.SetControlLabel(GetID, (int)Controls.CONTROL_LABELFILES, strObjects); + } + m_currentView = (int)Views.VIEW_ERROR_HAPPEND; + break; + }// + // + switch (m_currMailAction) + { + case (int)MailActions.ACTION_REFRESH_MAILBOX: + int mbNumber = GetMailBoxNumber(m_currMailBox); + if (m_mailBox.Count > 0) + { + mbNumber++; + RefreshAllBoxes(mbNumber); + } + break; + case (int)MailActions.ACTION_LIST_MAILS: + break; + case (int)MailActions.ACTION_DO_NOTHING: + break; + case (int)MailActions.ACTION_TIMER_EVENT: + break; + case (int)MailActions.ACTION_DELETE_MAIL: + break; + + } + if (m_autoCheck == true) + { + string data = GUILocalizeStrings.Get(8023); + foreach (MailBox mb in m_mailBox) + { + newMailsCount += m_mc.CountNewMail(mb); + data += " in Mailbox '" + mb.BoxLabel + "': " + Convert.ToString(m_mc.CountNewMail(mb)) + " " + GUILocalizeStrings.Get(8004) + " "; + } + if (newMailsCount > 0) + { + MediaPortal.Util.Utils.PlaySound("notify.wav", false, true); + DisplayOverlayNotify(true, data); + } + } + } + // build the list of mailboxes + void SetMailBoxList() + { + m_currentView = (int)Views.VIEW_MAILBOX; + if ((int)GUIWindowManager.ActiveWindow == GetID) + { + + GUIControl.ClearControl(GetID, (int)Controls.CONTROL_LIST); + ArrayList itemlist = new ArrayList(); + // make item list + foreach (MailBox mb in m_mailBox) + { + m_mc.SetMailboxPath(mb.MailboxFolder, mb.AttachmentFolder); + int nmc = m_mc.CountNewMail(mb); + GUIListItem item = new GUIListItem(mb.Username); + if (nmc != 0) + item.IconImage = "newMailIcon.png"; + item.Label = mb.BoxLabel + " (" + Convert.ToString(mb.MailCount) + ")"; + item.Label2 = "(" + mb.ServerAddress + ")"; + item.Label3 = ""; + item.Path = mb.Username; + item.IsFolder = false; + itemlist.Add(item); + + } + + // list items + foreach (GUIListItem item in itemlist) + { + GUIControl.AddListItemControl(GetID, (int)Controls.CONTROL_LIST, item); + } + + //set object count label + GUIPropertyManager.SetProperty("#itemcount", Util.Utils.GetObjectCountLabel(itemlist.Count)); + GUIControl.SetControlLabel(GetID, (int)Controls.CONTROL_LABELFILES, Util.Utils.GetObjectCountLabel(itemlist.Count)); + } + + } + // + void ClearItemList() + { + if ((int)GUIWindowManager.ActiveWindow == GetID) + { + GUIControl.ClearControl(GetID, (int)Controls.CONTROL_LIST); + + //set object count label + GUIPropertyManager.SetProperty("#itemcount", Util.Utils.GetObjectCountLabel(0)); + GUIControl.SetControlLabel(GetID, (int)Controls.CONTROL_LABELFILES, Util.Utils.GetObjectCountLabel(0)); + } + } + // add a incoming mail + int GetMailBoxNumber(MailBox theMailbox) + { + int count = 0; + foreach (MailBox mb in m_mailBox) + { + if (mb.Equals(theMailbox)) + return count; + count++; + } + return -1; + } + void SetMailsList() + { + if ((int)GUIWindowManager.ActiveWindow == GetID && m_currMailBox.MailCount > 0) + { + m_currentView = (int)Views.VIEW_MAILS; + ArrayList itemlist = new ArrayList(); + GUIControl.ClearControl(GetID, (int)Controls.CONTROL_LIST); + System.IO.FileInfo[] theMails = null; + m_mc.SetMailboxPath(m_currMailBox.MailboxFolder, m_currMailBox.AttachmentFolder); + int mCount = m_mc.GetEMailList(m_currMailBox.MailboxFolder, ref theMails); + string path = m_currMailBox.MailboxFolder + @"\"; + foreach (System.IO.FileInfo fInfo in theMails) + { + eMail theMail = m_mc.ParseMailText(m_mc.LoadEMail(path + fInfo.Name), false); + GUIListItem item = new GUIListItem(theMail.Subject); + if (m_mc.IsMailKnown(path + fInfo.Name) == false) + item.IconImage = "newMailIcon.png"; + item.Label = theMail.Subject; + item.Label2 = theMail.From; + item.Label3 = ""; + item.Path = path + fInfo.Name; + item.IsFolder = false; + itemlist.Add(item); + } + // + GUIListItem dirUp = new GUIListItem(".."); + dirUp.Path = "mailboxlist"; // to get where we are + dirUp.IsFolder = false; + dirUp.ThumbnailImage = ""; + dirUp.IconImage = "defaultFolderBack.png"; + dirUp.IconImageBig = "defaultFolderBackBig.png"; + itemlist.Insert(0, dirUp); + // + foreach (GUIListItem item in itemlist) + { + GUIControl.AddListItemControl(GetID, (int)Controls.CONTROL_LIST, item); + } + + //set object count label + GUIPropertyManager.SetProperty("#itemcount", Util.Utils.GetObjectCountLabel(itemlist.Count - 1)); + GUIControl.SetControlLabel(GetID, (int)Controls.CONTROL_LABELFILES, Util.Utils.GetObjectCountLabel(itemlist.Count - 1)); + + DisplayOverlayNotify(false, ""); // remove the notify + } + } + + void SaveSettings() + { + using (MediaPortal.Profile.Settings xmlwriter = new MediaPortal.Profile.Settings(Config.GetFile(Config.Dir.Config, "MediaPortal.xml"))) + { + xmlwriter.SetValueAsBool("mymail", "autoCheck", m_bAutoCheck); + } + } + + void LoadSettings() + { + using (MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.Settings(Config.GetFile(Config.Dir.Config, "MediaPortal.xml"))) + { + int boxCount = 0; + MailBox tmpBox; + m_mailBox.Clear(); + m_checkMailTimer.Interval = xmlreader.GetValueAsInt("mymail", "timer", 300000); + m_bAutoCheck = xmlreader.GetValueAsBool("mymail", "autoCheck", false); + boxCount = xmlreader.GetValueAsInt("mymail", "mailBoxCount", 0); + System.IO.FileInfo[] theMails = null; + if (boxCount > 0) + { + for (int i = 0; i < boxCount; i++) + { + string[] boxData = null; + string mailBoxString = xmlreader.GetValueAsString("mymail", "mailBox" + Convert.ToString(i), ""); + if (mailBoxString.Length > 0) + { + boxData = mailBoxString.Split(new char[] { ';' }); + //<OKAY_AWRIGHT> + if ((boxData.Length == 8) || ((boxData.Length > 8) && (boxData[8] == "T"))) + { + tmpBox = new MailBox(boxData[0], boxData[1], boxData[2], boxData[3], Convert.ToInt16(boxData[4]), Convert.ToByte(boxData[5]), boxData[6], boxData[7]); + //</OKAY_AWRIGHT> + tmpBox.MailCount = m_mc.GetEMailList(tmpBox.MailboxFolder, ref theMails); + if (tmpBox != null) + m_mailBox.Add(tmpBox); + } + } + } + } + + } + } + + // set mail box + void OnClick(int iItem) + { + GUIListItem item = GetSelectedItem(); + if (item == null) return; + switch (m_currentView) + { + case (int)Views.VIEW_MAILBOX: + if (iItem >= 0 && iItem <= m_mailBox.Count - 1) + { + m_currMailBox = (MailBox)m_mailBox[iItem]; + m_mc.SetMailboxPath(m_currMailBox.MailboxFolder, m_currMailBox.AttachmentFolder); + m_prevMailBox = m_currMailBox; + if (m_currMailBox.MailCount > 0) + { + m_currMailAction = (int)MailActions.ACTION_LIST_MAILS; + m_currentView = (int)Views.VIEW_MAILS; + SetMailsList(); + } + } + break; + case (int)Views.VIEW_MAILS: + if (iItem >= 0) + { + if (iItem == 0) + SetMailBoxList(); + else + if (m_currMailBox.MailCount > 0) + { + //get email here + string mailText = m_mc.LoadEMail(item.Path); + eMail theMail = m_mc.ParseMailText(mailText, true); + if (theMail != null) + { + m_mc_InformUser(8025, " (please wait...)"); + m_mc.SetMailboxPath(m_currMailBox.MailboxFolder, m_currMailBox.AttachmentFolder); + m_mc.SetMailToKnownState(mailText); + ShowMail(theMail); + if (m_currMailBox.MailCount == 0) + SetMailBoxList(); + + } + } + + } + break; + } + } + + void RefreshAllBoxes(int mbNumber) + { + if (m_mailBox.Count > 0) + { + if (mbNumber <= m_mailBox.Count - 1) + { + + GUIControl.DisableControl(GetID, (int)Controls.CONTROL_REFRESH_ALL); + + m_currMailBox = (MailBox)m_mailBox[mbNumber]; + if ((int)GUIWindowManager.ActiveWindow == GetID) + { + string strObjects = String.Format("{0} '{1}'", GUILocalizeStrings.Get(8005), m_currMailBox.BoxLabel); + GUIPropertyManager.SetProperty("#itemcount", strObjects); + GUIControl ctrl = GetControl((int)Controls.CONTROL_LABELFILES); + if (ctrl != null) + GUIControl.SetControlLabel(GetID, (int)Controls.CONTROL_LABELFILES, strObjects); + } + m_currMailAction = (int)MailActions.ACTION_REFRESH_MAILBOX; + + m_mc.ReadMailBox(ref m_currMailBox); + } + else + { + GUIControl.EnableControl(GetID, (int)Controls.CONTROL_REFRESH_ALL); + + if (m_currentView == (int)Views.VIEW_MAILBOX) + { + SetMailBoxList(); + } + + if (m_currentView == (int)Views.VIEW_MAILS) + { + if (m_prevMailBox != null) + { + m_currMailBox = m_prevMailBox; + m_prevMailBox = null; + SetMailsList(); + } + } + } + } + } + + //mb.BoxLabel+"("+Convert.ToString(mb.NewMailCount)+"/"+Convert.ToString(mb.MailCount)+")"; + GUIListItem GetSelectedItem() + { + int iControl; + iControl = (int)Controls.CONTROL_LIST; + GUIListItem item = GUIControl.GetSelectedListItem(GetID, iControl); + return item; + } + + void ShowMail(eMail theMail) + { + MailInfo mailWindow = (MailInfo)GUIWindowManager.GetWindow(8001); + mailWindow.SetEMail = theMail; + mailWindow.SetMailBox = m_currMailBox; + GUIWindowManager.ActivateWindow(8001); + } + + void SetAutoCheckButton() + { + GUIToggleButtonControl theControl = (GUIToggleButtonControl)GUIWindowManager.GetWindow(GetID).GetControl((int)Controls.CONTROL_SWITCH_AUTOCHECK); + if (theControl != null) + { + theControl.Selected = m_bAutoCheck; + } + } + + void DisplayOverlayNotify(bool state, string data) + { + MailOverlay mailOverlay = (MailOverlay)GUIWindowManager.GetWindow(8002); + if (mailOverlay != null) + { + GUIFadeLabel fader = (GUIFadeLabel)mailOverlay.GetControl(2); + + if (fader != null) + { + fader.Label = data; + fader.IsVisible = state; + } + } + } + + } +} \ No newline at end of file Added: trunk/plugins/MyMail/MailClass.cs =================================================================== --- trunk/plugins/MyMail/MailClass.cs (rev 0) +++ trunk/plugins/MyMail/MailClass.cs 2008-04-26 17:02:11 UTC (rev 1723) @@ -0,0 +1,1702 @@ +#region Copyright (C) 2005-2008 Team MediaPortal + +/* + * Copyright (C) 2005-2008 Team MediaPortal + * http://www.team-mediaportal.com + * + * This Program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2, or (at your option) + * any later version. + * + * This Program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GNU Make; see the file COPYING. If not, write to + * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. + * http://www.gnu.org/copyleft/gpl.html + * + */ + +#endregion + +using System; +using System.Collections; +using System.Net.Sockets; +using System.Net; +using System.Text; +using System.Text.RegularExpressions; +using System.ComponentModel; +using System.Net.Security; +using System.Security.Cryptography.X509Certificates; +using System.Security.Cryptography; + +using MediaPortal.Dialogs; +using MediaPortal.GUI.Library; + +namespace MediaPortal.GUI.MyMail +{ + /// <summary> + /// this a mail-client in a class + /// to read a mailbox + /// </summary> + + public class MailClass + { + const int m_buffSize = 2048; // buffer for rec. data + const string _CRLF_ = "\r\n"; + const System.Net.Sockets.SocketFlags noFlags = System.Net.Sockets.SocketFlags.None; + MailBox m_mb; + IPEndPoint m_endPoint; + Socket m_mailSocket;// + NetworkStream m_mailSocketStream; + SslStream m_mailTLSStream; + + static string m_emptyBuffer = new string((char)0, 2048);// 2kbyte socket buffer + //System.Net.Sockets.TcpClient m_mailReciever=new TcpClient(); + int m_imailCount; + int m_currAction = -1; // + int m_mailAction; + int m_mailNumber; + int m_ierrorNumber; + string m_mailFolder; + string m_attachmentFolder; + string m_errorMessage; + int m_mailNumberSize; + string m_recMailData; + System.Windows.Forms.Timer m_timeOutTimer = new System.Windows.Forms.Timer(); + ArrayList m_knownMails = new ArrayList(); + System.Security.Cryptography.MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); + byte[] m_mailBuffer = new Byte[m_buffSize]; + Byte m_TLSSecured = MailBox.NO_SSL; //NO_SSL: user/password combination won't be encrypted, STLS: use explicit SSL, SSL_PORT: use implicit SSL; The authentication method is chosen during mailbox configuration + Boolean m_TLS_OK = false; //Are we actually protected under a SSL layer? + public const Boolean UntrustedRootOK = true; //Accept that the server to securely connect to has produced its own certificate + public const Boolean CertNameMistmatchOK = false; //Accept that the server name (domain name) to securely connect to may mismatch the one provided in the certificate + public const Boolean CertRevokedOK = true; //Allow expired certificates to be used by the server + + private struct MailMultiPart + { + public int lineStart; + public int lineEnd; + public string contentID; + public string boundary; + public string contentType; + public string fileName; + public string name; + public string transferEncoding; + public string contentDisposition; + } + public struct MailAttachment + { + public string attPath; + public string attFileName; + public int attKind; // 1 - image, 2 - audio, 3 - application rel. + } + // + enum SocketError + { + ERROR_NO_ERROR = 0, + ERROR_TIMEOUT, + ERROR_NO_DATA, + ERROR_CONNECTION_ERR, + ERROR_WRONG_DATA, + ERROR_SERVER_NOT_READY, + ERROR_UNKNOWN_MSG_FROM_SERVER = 999 + } + + enum MailAction + { + MAIL_MB_CONNECTED = 1, + MAIL_SEND_CAPABILITIES, + MAIL_SEND_STARTTLS, + MAIL_ACTION_WAIT_SERVER_CERTIFICATE, + MAIL_SEND_USER, + MAIL_SEND_PASS, + MAIL_SEND_STAT, + MAIL_SEND_RETR, + MAIL_SEND_QUIT, + MAIL_SEND_LIST, + MAIL_SEND_DELE, + MAIL_SEND_RETR_LIST, + MAIL_SEND_PERFORM, + MAIL_ACTION_INVALID, + MAIL_ACTION_READ_ON, + MAIL_ACTION_READ_LIST + + } + + enum InformNumber + { + INFORM_CONNECTED = 8030, + INFORM_GETTING_MAIL, + INFORM_LOGOUT, + INFORM_GETTING_MAIL_PROGRESS + } + // our events + // an event to set diverse data + public delegate void InformEventHandler(int informNumber, object informObject); + public event InformEventHandler InformUser; + // + // timout handler + public delegate void GotMailDataEventHandler(object mailObject, string mailData, int mailAction); + public event GotMailDataEventHandler GotMailData; + // + // get mail known state + // + public MailClass() + { + + m_timeOutTimer.Tick += new EventHandler(TimeOut); + } + ~MailClass() + { + //m_timeOutTimer.Tick-=new EventHandler(TimeOut); + } + // getting all mails from an mailbox + public void ReadMailBox(ref MailBox mailbox) + { + IPAddress[] addr = new IPAddress[0]; + if (ServerExists(mailbox, ref addr) == true) + { + System.Net.IPEndPoint ePoint = new IPEndPoint(addr[0], mailbox.Port); + //mailbox.ClearMailList(); + m_mb = mailbox; + m_mailNumber = 0; + m_endPoint = ePoint; + m_TLSSecured = mailbox.TLS; + m_mailSocket = new Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.IP); + m_ierrorNumber = (int)SocketError.ERROR_NO_ERROR; + m_errorMessage = ""; + m_mailFolder = mailbox.MailboxFolder; + m_attachmentFolder = mailbox.AttachmentFolder; + m_timeOutTimer.Interval = 60000; // set timeout to 15 seconds + m_timeOutTimer.Start(); + AsyncCallback callback = new AsyncCallback(ConnectCallback); + // Begin Asyncronous Connection + m_mailSocket.BeginConnect(ePoint, callback, m_mailSocket); + m_mailAction = (int)MailAction.MAIL_SEND_STAT; + m_mailBuffer.Initialize(); + + } + else + { + GUIDialogOK dlgOK = (GUIDialogOK)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_OK); + if (dlgOK != null) + { + string serverString = GUILocalizeStrings.Get(8014); + string mailBoxString = GUILocalizeStrings.Get(8015); + dlgOK.SetHeading(8013); + dlgOK.SetLine(1, string.Format(serverString, mailbox.ServerAddress)); + dlgOK.SetLine(2, string.Format(mailBoxString, mailbox.BoxLabel)); + dlgOK.SetLine(3, ""); + dlgOK.DoModal(8000); + + } + m_ierrorNumber = (int)SocketError.ERROR_SERVER_NOT_READY; + m_mb.MailCount = 0; + Log.Info("mymail: server connecting problem {0}", m_mb.ServerAddress); + InteractServer((int)MailAction.MAIL_SEND_QUIT); // logout from the server + } + } + // delete an mail from the server + + private void ConnectCallback(IAsyncResult ar) + { + try + { + Socket sock1 = (Socket)ar.AsyncState; + if (sock1.Connected) + { + InformUser((int)InformNumber.INFORM_CONNECTED, ""); + m_timeOutTimer.Stop(); + + m_mailSocketStream = new NetworkStream(m_mailSocket, false); + + if (m_TLSSecured == MailBox.SSL_PORT) + { + + AsyncCallback recieveData = new AsyncCallback(OnRecievedData); + + try + { + m_mailTLSStream = new SslStream(m_mailSocketStream, false, this.RemoteCertificateValidationCallback); + m_mailTLSStream.AuthenticateAsClient(m_mb.ServerAddress, null, System.Security.Authentication.SslProtocols.Ssl2 | System.Security.Authentication.SslProtocols.Ssl3 | System.Security.Authentication.SslProtocols.Tls, !CertRevokedOK); + + m_TLS_OK = true; + + m_currAction = (int)MailAction.MAIL_MB_CONNECTED; + m_mailTLSStream.BeginRead(m_mailBuffer, 0, m_buffSize, recieveData, m_mailTLSStream); + + Log.Info("mymail: connected to server {0} using SSL", m_mb.ServerAddress); + + } + catch //(Exception ee) + { + /* + Log.Info("mymail: SSL connection attempt to dedicated port failed: {0}", ee.Message); + + m_mailTLSStream = null; + m_TLS_OK = false; + + m_ierrorNumber = (int)SocketError.ERROR_CONNECTION_ERR; + m_currAction = (int)MailAction.MAIL_SEND_QUIT; + m_mailSocketStream.BeginRead(m_mailBuffer, 0, m_buffSize, recieveData, m_mailSocketStream); + */ + } + + + } + else + { + AsyncCallback recieveData = new AsyncCallback(OnRecievedData); + + m_TLS_OK = false; + + m_currAction = (int)MailAction.MAIL_MB_CONNECTED; + m_mailSocketStream.BeginRead(m_mailBuffer, 0, m_buffSize, recieveData, m_mailSocketStream); + + Log.Info("mymail: connected to server {0}", m_mb.ServerAddress); + + } + + } + } + catch + { + // + } + } + + private void OnRecievedData(IAsyncResult ar) + { + if (m_currAction == (int)MailAction.MAIL_ACTION_WAIT_SERVER_CERTIFICATE) + { + + if (m_TLSSecured == MailBox.STLS && m_TLS_OK) + { + Log.Info("mymail: re-connected to server {0} using SSL", m_mb.ServerAddress); + InteractServer((int)MailAction.MAIL_SEND_USER); + } + else + { + Log.Info("mymail: SSL re-connection attempt using STARTTLS command failed: Explicit TLS issued w/out any effective SSL layer protection"); + m_ierrorNumber = (int)SocketError.ERROR_CONNECTION_ERR; + InteractServer((int)MailAction.MAIL_SEND_QUIT); // logout from the server + } + return; + } + + int bytesCount; + if (m_TLSSecured != MailBox.NO_SSL && m_TLS_OK) + bytesCount = ((SslStream)ar.AsyncState).EndRead(ar); + else + bytesCount = ((NetworkStream)ar.AsyncState).EndRead(ar); + System.String strData = System.Text.Encoding.ASCII.GetString(m_mailBuffer, 0, bytesCount); + m_timeOutTimer.Stop(); + + try + { + + if (bytesCount == 0 && m_currAction == (int)MailAction.MAIL_ACTION_READ_ON) + { + Log.Info("mymail: there is an recieve error. no data was send from server"); + m_errorMessage = "Error. No Mail-End indicator found"; + m_ierrorNumber = (int)SocketError.ERROR_WRONG_DATA; + InteractServer((int)MailAction.MAIL_SEND_QUIT); // logout from the server + } + // getting mailbox list + + // getting mail number x + if (bytesCount > 0 && m_currAction == (int)MailAction.MAIL_ACTION_READ_ON) + { + + m_recMailData += strData; + + double percentDone = m_recMailData.Length * 100 / m_mailNumberSize; + if (percentDone > 100f) percentDone = 100f; + string percentDoneText = " (" + Convert.ToString(percentDone) + "%)"; + InformUser((int)InformNumber.INFORM_GETTING_MAIL, Convert.ToString((m_imailCount + 1) - m_mailNumber) + "/" + Convert.ToString(m_imailCount) + percentDoneText); + + if (m_recMailData.EndsWith(_CRLF_ + "." + _CRLF_) == false) + { + + AsyncCallback recieveData = new AsyncCallback(OnRecievedData); + //m_timeOutTimer.Start(); + m_mailBuffer = System.Text.Encoding.ASCII.GetBytes(m_emptyBuffer); + m_timeOutTimer.Start(); + if (recieveData != null) + if (m_TLSSecured != MailBox.NO_SSL && m_TLS_OK) + ((SslStream)ar.AsyncState).BeginRead(m_mailBuffer, 0, m_buffSize, recieveData, (SslStream)ar.AsyncState); + else + ((NetworkStream)ar.AsyncState).BeginRead(m_mailBuffer, 0, m_buffSize, recieveData, (NetworkStream)ar.AsyncState); + } + else + { + + Log.Info("mymail: recieved message number {0}", Convert.ToString(m_mailNumber)); + try + { + SaveEMail(m_recMailData, m_mailNumber); + } + catch + { + Log.Info("mymail: there was an error creating the mail nr. {0}", Convert.ToString(m_mailNumber)); + } + m_recMailData = ""; + m_mailNumber--; + + if (m_mailNumber <= 0) + { + m_mailBuffer = System.Text.Encoding.ASCII.GetBytes(m_emptyBuffer); + Log.Info("mymail: all messages transfered. count: {0}", Convert.ToString(m_imailCount)); + m_ierrorNumber = (int)SocketError.ERROR_NO_ERROR; + InteractServer((int)MailAction.MAIL_SEND_QUIT); // logout from the server + } + else + { + InformUser((int)InformNumber.INFORM_GETTING_MAIL, Convert.ToString((m_imailCount + 1) - m_mailNumber) + "/" + Convert.ToString(m_imailCount)); + Log.Info("mymail: getting message number {0}", Convert.ToString(m_mailNumber)); + m_mailAction = (int)MailAction.MAIL_SEND_LIST; + InteractServer((int)MailAction.MAIL_SEND_LIST); + } + return; + } + } + + + if (bytesCount > 0 && m_currAction != (int)MailAction.MAIL_ACTION_READ_ON) + { + + string strRecieved = strData; + + if (strRecieved.StartsWith("-ERR")) + { + m_errorMessage = strRecieved.Substring(4, strRecieved.Length - 4); + m_ierrorNumber = (int)SocketError.ERROR_UNKNOWN_MSG_FROM_SERVER; + InteractServer((int)MailAction.MAIL_SEND_QUIT); + } + if (strRecieved.Substring(0, 3).Equals("+OK")) + { + switch (m_currAction) + { + case (int)MailAction.MAIL_SEND_LIST: + + string size = strRecieved; + size = size.Replace(_CRLF_, ""); + string[] strSeg = size.Split(new char[] { ' ' }); + int count = int.Parse(strSeg[strSeg.Length - 1]); + + if (count > 0 && IsMailInList(size) == false) + { + AppendMailToList(size); + m_mailNumberSize = count; + m_mailAction = (int)MailAction.MAIL_SEND_RETR; + InteractServer((int)MailAction.MAIL_SEND_PERFORM); // get the next mail + } + else + { + Log.Info("mymail: message number {0} has already been downloaded or is malformed", Convert.ToString(m_mailNumber)); + m_mailNumber--; + if (m_mailNumber <= 0) + { + m_ierrorNumber = (int)SocketError.ERROR_NO_ERROR; + InteractServer((int)MailAction.MAIL_SEND_QUIT); // logout from the server + } + else + InteractServer((int)MailAction.MAIL_SEND_LIST); + } + break; + case (int)MailAction.MAIL_MB_CONNECTED: // send the user and begin login or first issue a STLS command + if (m_TLSSecured == MailBox.STLS && !m_TLS_OK) + InteractServer((int)MailAction.MAIL_SEND_CAPABILITIES); + else + InteractServer((int)MailAction.MAIL_SEND_USER); + break; + case (int)MailAction.MAIL_SEND_CAPABILITIES: // check server capabilities + + Boolean is_STLS_Authorized = false; + //A t'on \xE0 faire \xE0 un serveur qui peut utiliser une couche SSL/TLS? + Regex regexEndOfLine = new Regex(_CRLF_); + string[] caps = regexEndOfLine.Split(strRecieved); + for (int i = 0; i < caps.Length; i++) + if (caps[i].Substring(0, 4).Equals("STLS")) + { + is_STLS_Authorized = true; + InteractServer((int)MailAction.MAIL_SEND_STARTTLS); + break; + } + //Non? alors on arr\xEAte l\xE0... + if (!is_STLS_Authorized) + { + Log.Info("mymail: Server does not advertise STLS. No secure connection will be issued."); + m_ierrorNumber = (int)SocketError.ERROR_CONNECTION_ERR; + InteractServer((int)MailAction.MAIL_SEND_QUIT); // logout from the server + } + break; + case (int)MailAction.MAIL_SEND_STARTTLS: // SSL/TLS via standard POP3 port + + AsyncCallback recieveData_TLS = new AsyncCallback(OnRecievedData); + try + { + m_mailTLSStream = new SslStream((NetworkStream)ar.AsyncState, false, this.RemoteCertificateValidationCallback); + m_TLS_OK = true; + m_currAction = (int)MailAction.MAIL_ACTION_WAIT_SERVER_CERTIFICATE; + m_mailTLSStream.BeginAuthenticateAsClient(m_mb.ServerAddress, null, System.Security.Authentication.SslProtocols.Ssl2 | System.Security.Authentication.SslProtocols.Ssl3 | System.Security.Authentication.SslProtocols.Tls, !CertRevokedOK, recieveData_TLS, m_mailTLSStream); + } + catch (Exception ee) + { + m_mailSocket.Blocking = false; + + Log.Info("mymail: SSL connection attempt using STARTTLS command failed: {0}", ee.Message); + + m_mailTLSStream = null; + m_TLS_OK = false; + + m_ierrorNumber = (int)SocketError.ERROR_CONNECTION_ERR; + m_currAction = (int)MailAction.MAIL_SEND_QUIT; + m_mailSocketStream.BeginRead(m_mailBuffer, 0, m_buffSize, recieveData_TLS, m_mailSocketStream); + } + break; + case (int)MailAction.MAIL_SEND_USER: // send password + InteractServer((int)MailAction.MAIL_SEND_PASS); + break; + case (int)MailAction.MAIL_SEND_PASS: // if the pass is sended we perform our action + InteractServer((int)MailAction.MAIL_SEND_PERFORM); + break; + + case (int)MailAction.MAIL_SEND_PERFORM: // we quit now + + if (m_mailAction == (int)MailAction.MAIL_SEND_STAT) // return the mail count from the inbox + { + + // get the mails count + strRecieved = strRecieved.Replace(_CRLF_, ""); + try + { + m_imailCount = int.Parse(Regex.Replace(strRecieved, @"^.*\+OK[ | ]+([0-9]+)[ | ]+.*$", "$1")); + } + catch + { + m_imailCount = 0; + } + // m_imailCount=m_imailCount; + m_mb.MailCount = m_imailCount; + Log.Info("mymail: there are {0} messages in the mailbox {1}", Convert.ToString(m_imailCount), m_mb.BoxLabel); + if (m_imailCount > 0) + { + //m_lastMailToRecieve=m_mb.LastCheckCount; + m_mailNumber = m_imailCount; + //m_mb.LastCheckCount=m_imailCount; + InformUser((int)InformNumber.INFORM_GETTING_MAIL, Convert.ToString((m_imailCount + 1) - m_mailNumber) + "/" + Convert.ToString(m_imailCount)); + InteractServer((int)MailAction.MAIL_SEND_LIST); + // starting out with getting a list + //m_mailAction=(int)MailAction.MAIL_SEND_RETR_LIST; + //InteractServer((int)MailAction.MAIL_SEND_PERFORM); + } + else + { + m_ierrorNumber = 2;// no mails on server + m_mb.MailCount = CountMail(m_mb); + InteractServer((int)MailAction.MAIL_SEND_QUIT); // logout from the server + } + } + if (m_mailAction == (int)MailAction.MAIL_SEND_RETR) // return the mail content (if its size is greater than the actual buffer size, will pursue using MAIL_ACTION_READ_ON command on next buffer filling pass) + { + //m_recMailData = ""; + m_recMailData = strRecieved; + //QUICK FIX: mail bodies whose size is lower than buffer length don't pass MAIL_ACTION_READ_ON related procedure through MAIL_SEND_RETR related procedure. + if (strRecieved.EndsWith(_CRLF_ + "." + _CRLF_)) + { + Log.Info("mymail: recieved message number {0}", Convert.ToString(m_mailNumber)); + try + { + SaveEMail(m_recMailData, m_mailNumber); + } + catch + { + Log.Info("mymail: there was an error creating the mail nr. {0}", Convert.ToString(m_mailNumber)); + } + m_recMailData = ""; + m_mailNumber--; + if (m_mailNumber <= 0) + { + m_mailBuffer = System.Text.Encoding.ASCII.GetBytes(m_emptyBuffer); + Log.Info("mymail: all messages transfered. count: {0}", Convert.ToString(m_imailCount)); + m_ierrorNumber = (int)SocketError.ERROR_NO_ERROR; + InteractServer((int)MailAction.MAIL_SEND_QUIT); // logout from the server + } + else + { + InformUser((int)InformNumber.INFORM_GETTING_MAIL, Convert.ToString((m_imailCount + 1) - m_mailNumber) + "/" + Convert.ToString(m_imailCount)); + Log.Info("mymail: getting message number {0}", Convert.ToString(m_mailNumber)); + m_mailAction = (int)MailAction.MAIL_SEND_LIST; + InteractServer((int)MailAction.MAIL_SEND_LIST); + } + } + else + { + m_currAction = (int)MailAction.MAIL_ACTION_READ_ON; + AsyncCallback recieveData = new AsyncCallback(OnRecievedData); + if (m_TLSSecured != MailBox.NO_SSL && m_TLS_OK) + ((SslStream)ar.AsyncState).BeginRead(m_mailBuffer, 0, m_buffSize, recieveData, (SslStream)ar.AsyncState); + else + ((NetworkStream)ar.AsyncState).BeginRead(m_mailBuffer, 0, m_buffSize, recieveData, (NetworkStream)ar.AsyncState); + } + } + if (m_mailAction == (int)MailAction.MAIL_SEND_DELE) // return the mail count from the inbox + InteractServer((int)MailAction.MAIL_SEND_QUIT); // logout from the server + + break; + case (int)MailAction.MAIL_SEND_QUIT: + m_mb.MailCount = CountMail(m_mb); + m_timeOutTimer.Stop(); + m_mailSocket.Close(); + m_mailSocketStream = null; + m_mailTLSStream = null; + if (m_ierrorNumber != 0) + { + Log.Info("mymail: an error occured. errornumber {0} on mailbox {1}", Convert.ToString(m_ierrorNumber), m_mb.ServerAddress); + Log.Info("mymail: an error occured. errormessage from server {0}", m_errorMessage); + } + GotMailData(m_errorMessage, "Ready", m_ierrorNumber); // ready + break; + } + } // else we are ready + } + } + catch + { + Log.Info("mymail: recieve error. mail number {0} on mailbox {1}", Convert.ToString(m_mailNumber), m_mb.BoxLabel); + InteractServer((int)MailAction.MAIL_SEND_QUIT); // logout from the server + } + } + // sending some request to the mailserver + // and set the required mailAction + // for example: if we sended the user we send the pass... + private int InteractServer(int action) + { + Socket sock1 = m_mailSocket; + byte[] toSend = System.Text.ASCIIEncoding.ASCII.GetBytes(""); + if (sock1.Connected == true) + { + switch (action) + { + case (int)MailAction.MAIL_SEND_LIST: // send user + toSend = System.Text.ASCIIEncoding.ASCII.GetBytes("list " + Convert.ToString(m_mailNumber) + _CRLF_); + break; + case (int)MailAction.MAIL_SEND_CAPABILITIES: //check capabilities (to this date, only used to verify if server supports STARTTLS) + toSend = System.Text.ASCIIEncoding.ASCII.GetBytes("capa" + _CRLF_); + break; + case (int)MailAction.MAIL_SEND_STARTTLS: //authenticate through explicit SSL/TLS + toSend = System.Text.ASCIIEncoding.ASCII.GetBytes("stls" + _CRLF_); + break; + case (int)MailAction.MAIL_SEND_USER: // send user + toSend = System.Text.ASCIIEncoding.ASCII.GetBytes("user " + m_mb.Username + _CRLF_); + break; + case (int)MailAction.MAIL_SEND_PASS: // send pass + toSend = System.Text.ASCIIEncoding.ASCII.GetBytes("pass " + m_mb.Password + _CRLF_); + break; + case (int)MailAction.MAIL_SEND_PERFORM: // send depends on what we request in Connect() + if (m_mailAction == (int)MailAction.MAIL_SEND_STAT) + toSend = System.Text.ASCIIEncoding.ASCII.GetBytes("stat" + _CRLF_); + if (m_mailAction == (int)MailAction.MAIL_SEND_RETR) + toSend = System.Text.ASCIIEncoding.ASCII.GetBytes("retr " + Convert.ToString(m_mailNumber) + _CRLF_); + if (m_mailAction == (int)MailAction.MAIL_SEND_DELE) + toSend = System.Text.ASCIIEncoding.ASCII.GetBytes("dele " + Convert.ToString(m_mailNumber) + _CRLF_); + if (m_mailAction == (int)MailAction.MAIL_SEND_RETR_LIST) + toSend = System.Text.ASCIIEncoding.ASCII.GetBytes("list" + _CRLF_); + break; + case (int)MailAction.MAIL_SEND_QUIT: + toSend = System.Text.ASCIIEncoding.ASCII.GetBytes("QUIT" + _CRLF_); + break; + default: + toSend = System.Text.ASCIIEncoding.ASCII.GetBytes(""); + break; + } + } + //m_timeOutTimer.Start(); + if (sock1.Connected == true && action > 0 && toSend.Length > 1) + { + m_currAction = action; + AsyncCallback recieveData = new AsyncCallback(OnRecievedData); + sock1.Blocking = false; + //Log.Info(System.Text.Encoding.ASCII.GetString(toSend)); + //sock1.Poll(15000,System.Net.Sockets.SelectMode.SelectRead); + //sock1.Send(toSend,0,toSend.Length,noFlags); + if (m_TLSSecured != MailBox.NO_SSL && m_TLS_OK) + m_mailTLSStream.Write(toSend, 0, toSend.Length); + else + m_mailSocketStream.Write(toSend, 0, toSend.Length); + m_mailBuffer = System.Text.Encoding.ASCII.GetBytes(m_emptyBuffer); + m_timeOutTimer.Start(); + //sock1.BeginReceive( m_mailBuffer, 0, m_buffSize, noFlags, recieveData , sock1 ); + if (m_TLSSecured != MailBox.NO_SSL && m_TLS_OK) + m_mailTLSStream.BeginRead(m_mailBuffer, 0, m_buffSize, recieveData, m_mailTLSStream); + else + m_mailSocketStream.BeginRead(m_mailBuffer, 0, m_buffSize, recieveData, m_mailSocketStream); + } + return 0; + } + + private bool RemoteCertificateValidationCallback(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) + { + SslPolicyErrors errors = sslPolicyErrors; + + if (((errors & SslPolicyErrors.RemoteCertificateChainErrors) == + SslPolicyErrors.RemoteCertificateChainErrors) && UntrustedRootOK) + { + errors -= SslPolicyErrors.RemoteCertificateChainErrors; + } + + /* --> CertNameMistmatchOK is always set to false + if (((errors & SslPolicyErrors.RemoteCertificateNameMismatch) == + SslPolicyErrors.RemoteCertificateNameMismatch) && CertNameMistmatchOK) + { + errors -= SslPolicyErrors.RemoteCertificateNameMismatch; + } + */ + + if (errors == SslPolicyErrors.None) + return true; + else + return false; + + //Le serveur doit s'authentifier sans erreur + } + + private void TimeOut(object sender, System.EventArgs e) + { + + m_mailSocket.Close(); + m_ierrorNumber = (int)SocketError.ERROR_TIMEOUT; // error timeout + GotMailData(m_errorMessage, "Ready", m_ierrorNumber); // ready + + } + public void SetMailboxPath(string mailbox, string attachments) + { + m_mailFolder = mailbox; + m_attachmentFolder = attachments; + } + public Socket GetSocket + { + get { return m_mailSocket; } + } + // get a mail + protected virtual bool ServerExists(MailBox mb) + { + try + { + IPHostEntry hostIP = Dns.GetHostEntry(mb.ServerAddress); + IPAddress[] addr = hostIP.AddressList; + } + catch + { + return false; + } + return true; + } + protected virtual bool ServerExists(MailBox mb, ref IPAddress[] addr) + { + try + { + IPHostEntry hostIP = Dns.GetHostEntry(mb.ServerAddress); + string[] aliases = hostIP.Aliases; + addr = hostIP.AddressList; + } + catch + { + return false; + } + return true; + } + // email body line + bool IsBodyLine(string line) + { + return false; + } + // parse the mail + public eMail ParseMailText(string mailText, bool decodeBody) + { + eMail retMail = new eMail(); + bool isMultipartMail = false; + string mailBoundary = ""; + string multipartType = ""; + string headerCheckText = ""; + int bodyBlockOffset = 0; + ArrayList headerBlock = new ArrayList(); + ArrayList bodyBlock = new ArrayList(); + retMail.AttachmentsPath = m_attachmentFolder; + retMail.MailboxPath = m_mailFolder; + string singlePartType = ""; + Regex mailSeparator = new Regex(@_CRLF_); + InformUser(8025, ""); + try + { + string[] lines = mailSeparator.Split(mailText); + // first getting the header-block + int counter = 0; + foreach (string line in lines) + { + if (line == "") break; // the first empty line indicates header end + headerBlock.Add(line); + headerCheckText += line; + counter += 1; + } + // header ready + byte[] mailID = md5.ComputeHash(System.Text.Encoding.ASCII.GetBytes(headerCheckText), 0, headerCheckText.Length); + retMail.MailID = System.Text.Encoding.ASCII.GetString(mailID); + // + bodyBlockOffset = counter + 1; + if (decodeBody == true) + for (int i = counter + 1; i < lines.Length; i++) + bodyBlock.Add(lines[i]); + // getting the body block + foreach (string line in headerBlock) + { + string tmpText = ""; + if (Regex.Match(line, "^.*boundary=[\"]*([^\"]*).*$").Success) + mailBoundary = Regex.Replace(line, "^.*boundary=[\"]*([^\"]*).*$", "$1"); + + + if (Regex.Match(line, @"^Content-Type: (.*)$").Success) + { + tmpText = Regex.Replace(line, @"^Content-Type: (.*)$", "$1"); + if (Regex.Match(tmpText, "^multipart/.*").Success) + { isMultipartMail = true; multipartType = tmpText; } + else + singlePartType = Regex.Replace(tmpText, @"(.*);.*", "$1"); + } + // get sender + // get sender + + if (line.Length > 5) + if (line.Substring(0, 5).Equals("From:")) + { + tmpText = Regex.Replace(line, @"^From:.*[ |<]([a-z|A-Z|0-9|\.|\-|_]+@[a-z|A-Z|0-9|\.|\-|_]+).*$", "$1"); + if (tmpText != "" && retMail.From.Equals("")) + { retMail.From = tmpText; continue; } + } + // get to + if (line.Length > 3) + if (line.Substring(0, 3).Equals("To:")) + { + tmpText = Regex.Replace(line, @"^To:.*[ |<]([a-z|A-Z|0-9|\.|\-|_]+@[a-z|A-Z|0-9|\.|\-|_]+).*$", "$1"); + if (tmpText != "" && retMail.To.Equals("")) + { retMail.To = tmpText; continue; } + } + // get subject + if (line.Length > 8) + if (line.Substring(0, 8).Equals("Subject:")) + { + tmpText = Regex.Replace(line, @"^Subject: (.*)$", "$1"); + if (tmpText != "" && retMail.Subject.Equals("")) + { + tmpText = Regex.Replace(tmpText, @".*=\?.*\?.*\?(.*)\?=$", "$1"); + tmpText = Regex.Replace(tmpText, @"_", " "); + retMail.Subject += tmpText; + retMail.Subject = TextToIntText(retMail.Subject); + retMail.Subject.TrimEnd(new char[] { ' ' }); + continue; + } + } + if (retMail.Subject != "" && Regex.Match(line, @".*=\?.*\?.*\?").Success) + { + tmpText = Regex.Replace(line, @".*=\?.*\?.*\?(.*)\?=$", "$1"); + tmpText = Regex.Replace(tmpText, @"_", " "); + retMail.Subject += tmpText; + retMail.Subject.TrimEnd(new char[] { ' ' }); + retMail.Subject = TextToIntText(retMail.Subject); + } + + } + if (isMultipartMail == true && decodeBody == true)//isMultipartMail==true && + { + ArrayList boundarys = new ArrayList(); + ArrayList multiParts = new ArrayList(); + bool getAll = GetAllBoundarys(bodyBlock, mailBoundary, ref boundarys); + GetAllMultiParts(bodyBlock, boundarys, ref multiParts);// we set all the parts from the mail + if (multiParts.Count > 0) + { + int stepCount = 0; + foreach (MailMultiPart mp in multiParts) + { + stepCount++; + string mimeType = ""; + string mimeSubType = ""; + string contentType = mp.contentType.Replace(";", ""); + string[] splitter = contentType.Split(new char[] { '/' }); + InformUser(8025, " (step " + Convert.ToString(stepCount) + "/" + Convert.ToString(multiParts.Count) + ")"); + if (splitter.Length > 0) + { + string path = m_attachmentFolder + @"\"; + mimeType = splitter[0]; + mimeSubType = splitter[1]; + string tmpData = ""; + byte[] binData = null; + MailAttachment mailAtt = new MailAttachment(); + System.IO.FileStream fs = null; + string tmpName = ""; + if (mimeType != "image" && mimeType != "multipart") + { + string[] splitt = mp.fileName.Split(new char[] { '.' }); + if (splitt.Length > 1) + { + switch (splitt[splitt.Length - 1].ToLower()) + { + case "jpg": + case "gif": + case "png": + case "tiff": + case "bmp": + case "jpeg": + mimeType = "application"; + mimeSubType = splitt[splitt.Length - 1].ToLower(); + break; + default: + // + break; + } + } + else + { + splitt = mp.fileName.Split(new char[] { '.' }); + if (splitt.Length > 1) + { + switch (splitt[splitt.Length - 1].ToLower()) + { + case "jpg": + case "gif": + case "png": + case "tiff": + case "bmp": + case "jpeg": + mimeType = "application"; + mimeSubType = splitt[splitt.Length - 1].ToLower(); + break; + default: + // + break; + } + } + + } + } + switch (mimeType) + { + + case "text": // here are the plain and html body we want + if (mp.contentDisposition == "") // not an attachment + {... [truncated message content] |