IMAP client.
Inheritance: IDisposable
Esempio n. 1
0
        /// <summary>
        /// Starts parsing FETCH response.
        /// </summary>
        /// <param name="imap">IMAP cleint.</param>
        /// <param name="line">Initial FETCH response line.</param>
        /// <param name="callback">Callback to be called when fetch completed.</param>
        /// <exception cref="ArgumentNullException">Is raised when <b>imap</b>,<b>line</b> or <b>callback</b> is null reference.</exception>
        internal void ParseAsync(IMAP_Client imap,string line,EventHandler<EventArgs<Exception>> callback)
        {
            if(imap == null){
                throw new ArgumentNullException("imap");
            }
            if(line == null){
                throw new ArgumentNullException("line");
            }
            if(callback == null){
                throw new ArgumentNullException("callback");
            }

            /* RFC 3501 7.4.2. FETCH Response.
                Example:    S: * 23 FETCH (FLAGS (\Seen) RFC822.SIZE 44827)
            */
                        
            StringReader r = new StringReader(line);

            // Eat '*'
            r.ReadWord();
            // Parse seqNo
            m_MsgSeqNo = Convert.ToInt32(r.ReadWord());
            // Eat 'FETCH'
            r.ReadWord();
            // Eat '(', if list of fetch data-items.
            r.ReadToFirstChar();
            if(r.StartsWith("(")){
                r.ReadSpecifiedLength(1);
            }

            ParseDataItems(imap,r,callback);
        }
Esempio n. 2
0
        public ActionResult About()
        {
            AUTH_Gmail_OAuth1_3leg oAuth = new AUTH_Gmail_OAuth1_3leg();
            // Create gmail access request.
            oAuth.GetRequestToken();
            // Get authorization URL, let user login to gmail and get verification code.
            System.Diagnostics.Process.Start(oAuth.GetAuthorizationUrl());
            Console.WriteLine("Enter(menu->Paste) gmail verification code:");
            // Get access token which is needed for accessing gmail API.
            oAuth.GetAccessToken(Console.ReadLine().Trim());

            using (IMAP_Client imap = new IMAP_Client())
            {
                imap.Logger = new LumiSoft.Net.Log.Logger();
                imap.Logger.WriteLog += delegate(object sender, LumiSoft.Net.Log.WriteLogEventArgs e)
                {
                    Console.WriteLine("log: " + e.LogEntry.Text);
                };
                //imap.Connect("imap.gmail.com", WellKnownPorts.IMAP4_SSL, true);
                imap.Connect("imap.gmail.com", WellKnownPorts.IMAP4, false);

                string email = oAuth.GetUserEmail();
                imap.Authenticate(new AUTH_SASL_Client_XOAuth(email, oAuth.GetXOAuthStringForImap(email)));
                imap.SelectFolder("inbox");

                Console.WriteLine("\r\n\r\n----- You are connected now. Press enter for exit.");
                Console.ReadLine();
            }

            return View();
        }
Esempio n. 3
0
        public void connect()
        {
            IMAP_Client client = new IMAP_Client();
            client.Connect("imap.yandex.ru", 995, true);
            client.Login("testkeepteam1", "testmail");
            client.SelectFolder("Inbox");

            /*    client
            client.Fetch(false,
                     IMAP_t_SeqSet.Parse("2:1"),
                     new IMAP_t_Fetch_i() {new IMAP_t_Fetch_i_Envelope()},
                     new EventHandler(Of LumiSoft.Net.EventArgs(Of IMAP_r_u))(AddressOf client_Fetch));

               */
        }
 public LumiIMAPGmailHelper()
 {
     _client = new IMAP_Client();
 }
Esempio n. 5
0
        //GMail Check fcn
        void gmailcheck()
        {
            ip = 1;
            imap = new IMAP_Client();
            fetchHandler = new IMAP_Client_FetchHandler();
            try
            {
                m_pTabPageMail_Messages.Items.Clear();
                imap.Connect("imap.gmail.com", 993, true);
                imap.Login(UserName.Text, Password.Text);
                imap.SelectFolder("INBOX");
                LoadMessages();
                LabelMail.Text = m_pTabPageMail_Messages.Items[ip - 2].SubItems[3].Text + m_pTabPageMail_Messages.Items[ip - 2].SubItems[4].Text;
                mainstring = m_pTabPageMail_Messages.Items[ip - 2].SubItems[3].Text + m_pTabPageMail_Messages.Items[ip - 2].SubItems[4].Text;
                substring = textBoxGmailCheckStr.Text;
                stringresult = mainstring.IndexOf(substring);
                imap.CloseFolder();
                imap.UnsubscribeFolder("INBOX");
                imap.Disconnect();
                imap.Dispose();

                if (stringresult != -1)
                {
                    labelRes.Text = "Found";
                }
                else
                {
                    labelRes.Text = "None";
                }
            }
            catch
            {
                MessageBox.Show("No internet Connection");
            }
        }
Esempio n. 6
0
        public void vl2fcn()
        {
            int incr = 0;
            while (true)
            {
                incr = incr + 1;
                Thread.Sleep(int.Parse(textBoxTime.Text) * 1000 * 60);

                    //Page4 Check
                    if (checkBoxWebPage4.Checked == true)
                    {
                        if (incr == int.Parse(textBoxTime2.Text))
                        {
                            Page4checkfcn();
                            Thread.Sleep(10000);
                            //int x = pageSource.IndexOf("Featured Episodes");
                            //newpageSource = pageSource;
                            labelBrowser.Text = newpageSource;
                            int fail = pageSource.IndexOf("download");
                            int fail2 = pageSource.IndexOf("Chrome");

                            if (oldpageSource != newpageSource && fail == -1 && fail2 == -1) // && oldpageSource != null)
                            {
                                oldpageSource = newpageSource;
                                googlecalendarSMSreminder(newpageSource);
                            }
                            incr = 0;
                        }
                    }

                    //Gmail Check
                    if (checkBoxGmail.Checked == true)
                    {
                        //button5_Click(sender, e);
                        ip = 1;
                        imap = new IMAP_Client();
                        fetchHandler = new IMAP_Client_FetchHandler();
                        try
                        {
                            m_pTabPageMail_Messages.Items.Clear();
                            imap.Connect("imap.gmail.com", 993, true);
                            imap.Login(UserName.Text, Password.Text);
                            imap.SelectFolder("INBOX");
                            LoadMessages();
                            LabelMail.Text = m_pTabPageMail_Messages.Items[ip - 2].SubItems[3].Text + m_pTabPageMail_Messages.Items[ip - 2].SubItems[4].Text;
                            mainstring = m_pTabPageMail_Messages.Items[ip - 2].SubItems[3].Text + m_pTabPageMail_Messages.Items[ip - 2].SubItems[4].Text;
                            substring = textBoxGmailCheckStr.Text;
                            stringresult = mainstring.IndexOf(substring);
                            imap.CloseFolder();
                            imap.UnsubscribeFolder("INBOX");
                            imap.Disconnect();
                            imap.Dispose();

                            if (stringresult != -1)
                            {
                                labelRes.Text = "Found";
                            }
                            else
                            {
                                labelRes.Text = "None";
                            }
                        }
                        catch
                        {
                            MessageBox.Show("No internet Connection");
                        }

                        if (mainstring != oldmainstring && stringresult != -1)
                        {
                            googlecalendarSMSreminder(m_pTabPageMail_Messages.Items[ip - 2].SubItems[4].Text);
                            oldmainstring = mainstring;
                        }

                    }

                    //WebPage Check 1,2
                    if (checkBoxWebPage.Checked == true)
                    {
                        //////////////////////////
                        //Check 0 original Lockerz PAGE1

                        // Create a request for the URL.
                        WebRequest request3 = WebRequest.Create(textBoxPage1.Text); //http://ptzplace.lockerz.com/
                        // If required by the server, set the credentials.
                        request3.Credentials = CredentialCache.DefaultCredentials;
                        // Get the response.
                        HttpWebResponse response3 = (HttpWebResponse)request3.GetResponse();
                        // Display the status.
                        Console.WriteLine(response3.StatusDescription);
                        // Get the stream containing content returned by the server.
                        Stream dataStream3 = response3.GetResponseStream();
                        // Open the stream using a StreamReader for easy access.
                        StreamReader reader3 = new StreamReader(dataStream3);
                        // Read the content.
                        string responseFromServer3 = reader3.ReadToEnd();
                        // Save to newer.
                        newer = responseFromServer3;
                        // Cleanup the streams and the response.
                        reader3.Close();
                        dataStream3.Close();
                        response3.Close();

                        //////////////////////////
                        //Check 1 Lockerznews PAGE2

                        // Create a request for the URL.
                        WebRequest request4 = WebRequest.Create(textBoxPage2.Text);
                        // If required by the server, set the credentials.
                        request4.Credentials = CredentialCache.DefaultCredentials;
                        // Get the response.
                        HttpWebResponse response4 = (HttpWebResponse)request4.GetResponse();
                        // Display the status.
                        Console.WriteLine(response4.StatusDescription);
                        // Get the stream containing content returned by the server.
                        Stream dataStream4 = response4.GetResponseStream();
                        // Open the stream using a StreamReader for easy access.
                        StreamReader reader4 = new StreamReader(dataStream4);
                        // Read the content.
                        string responseFromServer4 = reader4.ReadToEnd();
                        // Save to newer.
                        newer1 = responseFromServer4;
                        // Cleanup the streams and the response.
                        reader4.Close();
                        dataStream4.Close();
                        response4.Close();
                        newer1 = newer1.Substring(int.Parse(textBoxStrStart.Text), int.Parse(textBoxStrEnd.Text));

                        // Compare String
                        if (older != newer || older1 != newer1)
                        {
                            googlecalendarSMSreminder("Redemption begins");
                            // Save to older.
                            older = newer;
                            older1 = newer1;

                            labelRedeem.Text = "Reedem started";
                            labelRedeem.ForeColor = Color.Green;

                            //Notify Icon Change
                            notifyIcon1.Icon = SystemIcons.Exclamation;
                            notifyIcon1.BalloonTipTitle = "Lockerz";
                            notifyIcon1.BalloonTipText = "Redemption Start.";
                            notifyIcon1.BalloonTipIcon = ToolTipIcon.Error;
                            //this.Click += new EventHandler(Form1_Click);
                            notifyIcon1.ShowBalloonTip(30);
                        }
                    }
                labelLastCheck.Text = DateTime.Now.TimeOfDay.ToString();
            }
        }
Esempio n. 7
0
        public override void Open()
        {
            Logger.Debug("Opening IMAP connection {0}", LogSource.Channel, UniqueId);

            if (!(channelState == ChannelState.Closed || channelState == ChannelState.Broken))
            {
                Logger.Debug("SUCCESS Connection was allready open {0}", LogSource.Channel, UniqueId);

                return;
            }

            channelState = ChannelState.Connecting;
            client = new IMAP_Client();

            if ("/Settings/Channels/LoggerEnabled".AsKey(false))
            {
                client.Logger = new LumiSoft.Net.Log.Logger();
                client.Logger.WriteLog += (sender, e) => Logger.Debug(e.LogEntry.Text.Replace("{", "{{").Replace("}", "}}"), LogSource.Channel);
            }

            try
            {
                client.Connect(Hostname, Port, IsSecured);

                channelState = ChannelState.Connected;
            }
            catch (Exception ex)
            {
                channelState = ChannelState.Closed;

                Logger.Debug("Unable to connect to server. Exception = {0}", LogSource.Channel, ex);

                throw new ChannelException("Unable to connect to server", ex);
            }

            Logger.Debug("SUCCESS Opening connection {0}", LogSource.Channel, UniqueId);
        }
Esempio n. 8
0
        /// <summary>
        /// Reads string-literal(stores it to reader 'r') and continuing fetch line.
        /// </summary>
        /// <param name="imap">IMAP client.</param>
        /// <param name="r">String reader.</param>
        /// <param name="callback">Fetch completion callback.</param>
        /// <returns>Returns true if completed asynchronously or false if completed synchronously.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>imap</b>,<b>r</b> or <b>callback</b> is null reference.</exception>
        private bool ReadStringLiteral(IMAP_Client imap,StringReader r,EventHandler<EventArgs<Exception>> callback)
        {
            if(imap == null){
                throw new ArgumentNullException("imap");
            }
            if(r == null){
                throw new ArgumentNullException("r");
            }
            if(callback == null){
                throw new ArgumentNullException("callback");
            }

            if(r.SourceString.EndsWith("}") && r.SourceString.IndexOf("{") > -1){
                MemoryStream stream = new MemoryStream();
                string size = r.SourceString.Substring(r.SourceString.LastIndexOf("{") + 1,r.SourceString.Length - r.SourceString.LastIndexOf("{") - 2);
                // Remove {n} from string.
                r.RemoveFromEnd(r.SourceString.Length - r.SourceString.LastIndexOf('{'));

                IMAP_Client.ReadStringLiteralAsyncOP op = new IMAP_Client.ReadStringLiteralAsyncOP(stream,Convert.ToInt32(size));
                op.CompletedAsync += delegate(object sender,EventArgs<IMAP_Client.ReadStringLiteralAsyncOP> e){
                    try{
                        // Read string literal failed.
                        if(op.Error != null){
                            callback(this,new EventArgs<Exception>(op.Error));
                        }
                        else{
                            // Append string-literal to fetch reader.
                            r.AppendString(TextUtils.QuoteString(Encoding.UTF8.GetString(stream.ToArray())));

                            // Read next fetch line completed synchronously.
                            if(!ReadNextFetchLine(imap,r,callback)){
                                ParseDataItems(imap,r,callback);
                            }
                        }
                    }
                    catch(Exception x){
                        callback(this,new EventArgs<Exception>(x));
                    }
                    finally{
                        op.Dispose();
                    }
                };

                // Read string literal completed sync.
                if(!imap.ReadStringLiteralAsync(op)){
                    try{
                        // Read string literal failed.
                        if(op.Error != null){
                            callback(this,new EventArgs<Exception>(op.Error));

                            return true;
                        }
                        else{
                            // Append string-literal to fetch reader.
                            r.AppendString(TextUtils.QuoteString(Encoding.UTF8.GetString(stream.ToArray())));

                            return ReadNextFetchLine(imap,r,callback);
                        }
                    }
                    finally{
                        op.Dispose();
                    }
                }
                // Read string literal completed async.
                else{
                    return true;
                }
            }
            else{
                throw new ParseException("No string-literal available '" + r.SourceString + "'.");
            }
        }
Esempio n. 9
0
 public void Connect(String server, String User, String pass, int port, bool useSSl)
 {
     try
     {
         Client = new IMAP_Client();
         Client.Connect(server, port, useSSl);
         Client.Login(User, pass);
         _IsConnected = true;
     }
     catch (Exception exe)
     {
         throw new EMailException { ExceptionType = EMAIL_EXCEPTION_TYPE.ERROR_ON_CONNECTION, InnerException = exe };
     }
 }
Esempio n. 10
0
        /// <summary>
        /// Reads IMAP string(string-literal,quoted-string,NIL) and remaining FETCH line if needed.
        /// </summary>
        /// <param name="imap">IMAP client.</param>
        /// <param name="r">Fetch line reader.</param>
        /// <param name="callback">Fetch completion callback.</param>
        /// <param name="stream">Stream where to store readed data.</param>
        /// <returns>Returns true if completed asynchronously or false if completed synchronously.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>imap</b>,<b>r</b>,<b>callback</b> or <b>stream</b> is null reference.</exception>
        private bool ReadData(IMAP_Client imap,StringReader r,EventHandler<EventArgs<Exception>> callback,Stream stream)
        {
            if(imap == null){
                throw new ArgumentNullException("imap");
            }
            if(r == null){
                throw new ArgumentNullException("r");
            }
            if(callback == null){
                throw new ArgumentNullException("callback");
            }
            if(stream == null){
                throw new ArgumentNullException("stream");
            }

            r.ReadToFirstChar();

            // We don't have data.
            if(r.StartsWith("NIL",false)){
                // Eat NIL.
                r.ReadWord();

                return false;
            }
            // Data value is returned as string-literal.
            else if(r.StartsWith("{",false)){
                IMAP_Client.ReadStringLiteralAsyncOP op = new IMAP_Client.ReadStringLiteralAsyncOP(stream,Convert.ToInt32(r.ReadParenthesized()));
                op.CompletedAsync += delegate(object sender,EventArgs<IMAP_Client.ReadStringLiteralAsyncOP> e){
                    try{
                        // Read string literal failed.
                        if(op.Error != null){
                            callback(this,new EventArgs<Exception>(op.Error));
                        }
                        else{
                            // Read next fetch line completed synchronously.
                            if(!ReadNextFetchLine(imap,r,callback)){
                                ParseDataItems(imap,r,callback);
                            }
                        }
                    }
                    catch(Exception x){
                        callback(this,new EventArgs<Exception>(x));
                    }
                    finally{
                        op.Dispose();
                    }
                };

                // Read string literal completed sync.
                if(!imap.ReadStringLiteralAsync(op)){
                    try{
                        // Read string literal failed.
                        if(op.Error != null){
                            callback(this,new EventArgs<Exception>(op.Error));

                            return true;
                        }
                        else{
                            // Read next fetch line completed synchronously.
                            if(!ReadNextFetchLine(imap,r,callback)){
                                return false;
                            }
                            else{
                                return true;
                            }
                        }
                    }
                    finally{
                        op.Dispose();
                    }
                }
                // Read string literal completed async.
                else{
                    return true;
                }
            }
            // Data is quoted-string.
            else{
                byte[] data = Encoding.UTF8.GetBytes(r.ReadWord());
                stream.Write(data,0,data.Length);

                return false;
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Starts parsing fetch data-items,
        /// </summary>
        /// <param name="imap">IMAP client.</param>
        /// <param name="r">Fetch line reader.</param>
        /// <param name="callback">Callback to be called when parsing completes.</param>
        /// <exception cref="ArgumentNullException">Is raised when <b>imap</b>,<b>r</b> or <b>callback</b> is null reference.</exception>
        private void ParseDataItems(IMAP_Client imap,StringReader r,EventHandler<EventArgs<Exception>> callback)
        {
            if(imap == null){
                throw new ArgumentNullException("imap");
            }
            if(r == null){
                throw new ArgumentNullException("r");
            }
            if(callback == null){
                throw new ArgumentNullException("callback");
            }

            /* RFC 3501 7.4.2. FETCH Response.
                Example:    S: * 23 FETCH (FLAGS (\Seen) RFC822.SIZE 44827)
            */

            while(true){
                r.ReadToFirstChar();

                #region BODY[]

                if(r.StartsWith("BODY[",false)){
                    /* RFC 3501 7.4.2. FETCH Response.
                        BODY[<section>]<<origin octet>>
                         A string expressing the body contents of the specified section.
                         The string SHOULD be interpreted by the client according to the
                         content transfer encoding, body type, and subtype.

                         If the origin octet is specified, this string is a substring of
                         the entire body contents, starting at that origin octet.  This
                         means that BODY[]<0> MAY be truncated, but BODY[] is NEVER
                         truncated.

                            Note: The origin octet facility MUST NOT be used by a server
                            in a FETCH response unless the client specifically requested
                            it by means of a FETCH of a BODY[<section>]<<partial>> data
                            item.

                         8-bit textual data is permitted if a [CHARSET] identifier is
                         part of the body parameter parenthesized list for this section.
                         Note that headers (part specifiers HEADER or MIME, or the
                         header portion of a MESSAGE/RFC822 part), MUST be 7-bit; 8-bit
                         characters are not permitted in headers.  Note also that the
                         [RFC-2822] delimiting blank line between the header and the
                         body is not affected by header line subsetting; the blank line
                         is always included as part of header data, except in the case
                         of a message which has no body and no blank line.

                         Non-textual data such as binary data MUST be transfer encoded
                         into a textual form, such as BASE64, prior to being sent to the
                         client.  To derive the original binary data, the client MUST
                         decode the transfer encoded string.
                    */

                    // Eat BODY word.
                    r.ReadWord();

                    // Read body-section.
                    string section = r.ReadParenthesized();

                    // Read origin if any.
                    int offset = -1;
                    if(r.StartsWith("<")){
                        offset = Convert.ToInt32(r.ReadParenthesized().Split(' ')[0]);
                    }

                    IMAP_t_Fetch_r_i_Body dataItem = new IMAP_t_Fetch_r_i_Body(section,offset,new MemoryStreamEx(32000));
                    m_pDataItems.Add(dataItem);

                    // Raise event, allow user to specify store stream.
                    IMAP_Client_e_FetchGetStoreStream eArgs = new IMAP_Client_e_FetchGetStoreStream(this,dataItem);
                    imap.OnFetchGetStoreStream(eArgs);
                    // User specified own stream, use it.
                    if(eArgs.Stream != null){
                        dataItem.Stream.Dispose();
                        dataItem.SetStream(eArgs.Stream);
                    }

                    // Read data will complete async and will continue data-items parsing, exit this method.
                    if(ReadData(imap,r,callback,dataItem.Stream)){
                        return;
                    }
                    // Continue processing.
                    //else{
                }

                #endregion

                #region BODY

                else if(r.StartsWith("BODY ",false)){
                    //IMAP_t_Fetch_r_i_BodyS
                }

                #endregion

                #region BODYSTRUCTURE

                else if(r.StartsWith("BODYSTRUCTURE",false)){
                    //IMAP_t_Fetch_r_i_BodyStructure
                }

                #endregion

                #region ENVELOPE

                else if(r.StartsWith("ENVELOPE",false)){
                    // Envelope can contain string literals, we just try to parse it.
                    // If parse fails, just get string literal and try again as long as all ENVELOPE data has read.

                    string envelope = null;
                    while(true){
                        // Create temporary reader(we don't want to read partial ENVELOPE data from reader).
                        StringReader tmpReader = new StringReader(r.SourceString);

                        // Eat ENVELOPE word.
                        tmpReader.ReadWord();
                        tmpReader.ReadToFirstChar();

                        try{
                            envelope = tmpReader.ReadParenthesized();
                            // We got full ENVELOPE, so use tmp reader as reader.
                            r = tmpReader;

                            break;
                        }
                        catch{
                            // Read completed async, it will continue parsing.
                            if(ReadStringLiteral(imap,r,callback)){
                                return;
                            }
                        }
                    }

                    m_pDataItems.Add(IMAP_t_Fetch_r_i_Envelope.Parse(new StringReader(envelope)));
                }

                #endregion

                #region FLAGS

                else if(r.StartsWith("FLAGS",false)){
                    /* RFC 3501 7.4.2. FETCH Response.
                        FLAGS
                            A parenthesized list of flags that are set for this message.
                    */

                    // Eat FLAGS word.
                    r.ReadWord();

                    m_pDataItems.Add(new IMAP_t_Fetch_r_i_Flags(IMAP_t_MsgFlags.Parse(r.ReadParenthesized())));
                }

                #endregion

                #region INTERNALDATE

                else if(r.StartsWith("INTERNALDATE",false)){
                    /* RFC 3501 7.4.2. FETCH Response.
                        INTERNALDATE
                            A string representing the internal date of the message.
                    */

                    // Eat INTERNALDATE word.
                    r.ReadWord();

                    m_pDataItems.Add(new IMAP_t_Fetch_r_i_InternalDate(IMAP_Utils.ParseDate(r.ReadWord())));
                }

                #endregion

                #region RFC822

                else if(r.StartsWith("RFC822 ",false)){
                    /* RFC 3501 7.4.2. FETCH Response.
                        RFC822
                            Equivalent to BODY[].
                    */

                    // Eat RFC822 word.
                    r.ReadWord();
                    r.ReadToFirstChar();

                    IMAP_t_Fetch_r_i_Rfc822 dataItem = new IMAP_t_Fetch_r_i_Rfc822(new MemoryStreamEx(32000));
                    m_pDataItems.Add(dataItem);

                    // Raise event, allow user to specify store stream.
                    IMAP_Client_e_FetchGetStoreStream eArgs = new IMAP_Client_e_FetchGetStoreStream(this,dataItem);
                    imap.OnFetchGetStoreStream(eArgs);
                    // User specified own stream, use it.
                    if(eArgs.Stream != null){
                        dataItem.Stream.Dispose();
                        dataItem.SetStream(eArgs.Stream);
                    }

                    // Read data will complete async and will continue data-items parsing, exit this method.
                    if(ReadData(imap,r,callback,dataItem.Stream)){
                        return;
                    }
                    // Continue processing.
                    //else{
                }

                #endregion

                #region RFC822.HEADER

                else if(r.StartsWith("RFC822.HEADER",false)){
                    /* RFC 3501 7.4.2. FETCH Response.
                        RFC822.HEADER
                            Equivalent to BODY[HEADER].  Note that this did not result in
                            \Seen being set, because RFC822.HEADER response data occurs as
                            a result of a FETCH of RFC822.HEADER.  BODY[HEADER] response
                            data occurs as a result of a FETCH of BODY[HEADER] (which sets
                            \Seen) or BODY.PEEK[HEADER] (which does not set \Seen).
                    */

                    // Eat RFC822.HEADER word.
                    r.ReadWord();
                    r.ReadToFirstChar();

                    IMAP_t_Fetch_r_i_Rfc822Header dataItem = new IMAP_t_Fetch_r_i_Rfc822Header(new MemoryStreamEx(32000));
                    m_pDataItems.Add(dataItem);

                    // Raise event, allow user to specify store stream.
                    IMAP_Client_e_FetchGetStoreStream eArgs = new IMAP_Client_e_FetchGetStoreStream(this,dataItem);
                    imap.OnFetchGetStoreStream(eArgs);
                    // User specified own stream, use it.
                    if(eArgs.Stream != null){
                        dataItem.Stream.Dispose();
                        dataItem.SetStream(eArgs.Stream);
                    }

                    // Read data will complete async and will continue data-items parsing, exit this method.
                    if(ReadData(imap,r,callback,dataItem.Stream)){
                        return;
                    }
                    // Continue processing.
                    //else{
                }

                #endregion

                #region RFC822.SIZE

                else if(r.StartsWith("RFC822.SIZE",false)){
                    /* RFC 3501 7.4.2. FETCH Response.
                        RFC822.SIZE
                            A number expressing the [RFC-2822] size of the message.
                    */

                    // Eat RFC822.SIZE word.
                    r.ReadWord();

                    m_pDataItems.Add(new IMAP_t_Fetch_r_i_Rfc822Size(Convert.ToInt32(r.ReadWord())));
                }

                #endregion

                #region RFC822.TEXT

                else if(r.StartsWith("RFC822.TEXT",false)){
                    /* RFC 3501 7.4.2. FETCH Response.
                        RFC822.TEXT
                            Equivalent to BODY[TEXT].
                    */

                    // Eat RFC822.TEXT word.
                    r.ReadWord();
                    r.ReadToFirstChar();

                    IMAP_t_Fetch_r_i_Rfc822Text dataItem = new IMAP_t_Fetch_r_i_Rfc822Text(new MemoryStreamEx(32000));
                    m_pDataItems.Add(dataItem);

                    // Raise event, allow user to specify store stream.
                    IMAP_Client_e_FetchGetStoreStream eArgs = new IMAP_Client_e_FetchGetStoreStream(this,dataItem);
                    imap.OnFetchGetStoreStream(eArgs);
                    // User specified own stream, use it.
                    if(eArgs.Stream != null){
                        dataItem.Stream.Dispose();
                        dataItem.SetStream(eArgs.Stream);
                    }

                    // Read data will complete async and will continue data-items parsing, exit this method.
                    if(ReadData(imap,r,callback,dataItem.Stream)){
                        return;
                    }
                    // Continue processing.
                    //else{
                }

                #endregion

                #region UID

                else if(r.StartsWith("UID",false)){
                    /* RFC 3501 7.4.2. FETCH Response.
                        UID
                            A number expressing the unique identifier of the message.
                    */

                    // Eat UID word.
                    r.ReadWord();

                    m_pDataItems.Add(new IMAP_t_Fetch_r_i_Uid(Convert.ToInt64(r.ReadWord())));
                }

                #endregion

                #region X-GM-MSGID

                else if(r.StartsWith("X-GM-MSGID",false)){
                    /* http://code.google.com/intl/et/apis/gmail/imap X-GM-MSGID.

                    */

                    // Eat X-GM-MSGID word.
                    r.ReadWord();

                    m_pDataItems.Add(new IMAP_t_Fetch_r_i_X_GM_MSGID(Convert.ToUInt64(r.ReadWord())));
                }

                #endregion

                #region X-GM-THRID

                else if(r.StartsWith("X-GM-THRID",false)){
                    /* http://code.google.com/intl/et/apis/gmail/imap X-GM-THRID.

                    */

                    // Eat X-GM-THRID word.
                    r.ReadWord();

                    m_pDataItems.Add(new IMAP_t_Fetch_r_i_X_GM_THRID(Convert.ToUInt64(r.ReadWord())));
                }

                #endregion

                #region ) - fetch closing.

                else if(r.StartsWith(")",false)){
                    break;
                }

                #endregion

                else{
                    throw new ParseException("Not supported FETCH data-item '" + r.ReadToEnd() + "'.");
                }
            }

            callback(this,new EventArgs<Exception>(null));
        }
Esempio n. 12
0
        /// <summary>
        /// Intializes destination object. Makes it ready to store messages messages into it.
        /// </summary>
        private void InitDestination()
        {
            #region LumiSoft Mail Server User

            // LumiSoft Mail Server User
            if(m_DestinationType == 0){
                m_pDestinationObject = m_pUser.VirtualServer.Users.GetUserByName(m_pDestination_TypeLSUser_User.Text);
            }

            #endregion

            #region IMAP

            // IMAP
            else if(m_DestinationType == 1){
                IMAP_Client imap = new IMAP_Client();
                imap.Connect(m_pDestination_TypeIMAP_Host.Text,(int)m_pDestination_TypeIMAP_Port.Value,m_pDestination_TypeIMAP_UseSSL.Checked);
                imap.Login(m_pDestination_TypeIMAP_User.Text,m_pDestination_TypeIMAP_Password.Text);
                m_pDestinationObject = imap;
            }

            #endregion

            #region ZIP

            // ZIP
            else if(m_DestinationType == 2){
                ZipOutputStream zipFile = new ZipOutputStream(File.Create(m_pDestination_TypeZIP_File.Text));
                zipFile.SetLevel(9);
                m_pDestinationObject = zipFile;
            }

            #endregion

            else{
                throw new Exception("Invalid destination type '" + m_DestinationType.ToString() + "' !");
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Intializes source object. Makes it ready to get messages info and messages.
        /// </summary>
        private void InitSource()
        {
            #region LumiSoft Mail Server User

            // LumiSoft Mail Server User
            if(m_SourceType == 0){
                m_pSourceObject = m_pUser.VirtualServer.Users.GetUserByName(m_pSource_TypeLSUser_User.Text);
            }

            #endregion

            #region IMAP

            // IMAP
            else if(m_SourceType == 1){
                IMAP_Client imap = new IMAP_Client();
                imap.Connect(m_pSource_TypeIMAP_Host.Text,(int)m_pSource_TypeIMAP_Port.Value,m_pSource_TypeIMAP_UseSSL.Checked);
                imap.Login(m_pSource_TypeIMAP_User.Text,m_pSource_TypeIMAP_Password.Text);
                m_pSourceObject = imap;
            }

            #endregion

            #region ZIP

            // ZIP
            else if(m_SourceType == 2){
                m_pSourceObject = new ZipFile(m_pSource_TypeZIP_File.Text);
            }

            #endregion

            else{
                throw new Exception("Invalid source type '" + m_SourceType.ToString() + "' !");
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Reads parenthesized list of addresses.
        /// </summary>
        /// <param name="fetchReader">Fetch reader.</param>
        /// <returns>Returns read addresses.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>fetchReader</b> is null reference.</exception>
        private static Mail_t_Address[] ReadAddresses(IMAP_Client._FetchResponseReader fetchReader)
        {
            if(fetchReader == null){
                throw new ArgumentNullException("fetchReader");
            }

            /* RFC 3501 7.4.2.
                An address structure is a parenthesized list that describes an
                electronic mail address.  The fields of an address structure
                are in the following order: personal name, [SMTP]
                at-domain-list (source route), mailbox name, and host name.

                [RFC-2822] group syntax is indicated by a special form of
                address structure in which the host name field is NIL.  If the
                mailbox name field is also NIL, this is an end of group marker
                (semi-colon in RFC 822 syntax).  If the mailbox name field is
                non-NIL, this is a start of group marker, and the mailbox name
                field holds the group name phrase.
            */

            fetchReader.GetReader().ReadToFirstChar();
            if(fetchReader.GetReader().StartsWith("NIL",false)){
                fetchReader.GetReader().ReadWord();

                return null;
            }
            else{
                List<Mail_t_Address> retVal = new List<Mail_t_Address>();
                // Eat addresses starting "(".
                fetchReader.GetReader().ReadSpecifiedLength(1);

                while(fetchReader.GetReader().Available > 0){
                    // We have addresses ending ")".
                    if(fetchReader.GetReader().StartsWith(")")){
                        fetchReader.GetReader().ReadSpecifiedLength(1);
                        break;
                    }

                    // Eat address starting "(".
                    fetchReader.GetReader().ReadSpecifiedLength(1);

                    string personalName = ReadAndDecodeWord(fetchReader.ReadString());
                    string atDomainList = fetchReader.ReadString();
                    string mailboxName  = fetchReader.ReadString();
                    string hostName     = fetchReader.ReadString();

                    retVal.Add(new Mail_t_Mailbox(personalName,mailboxName + "@" + hostName));

                    // Eat address ending ")".
                    fetchReader.GetReader().ReadSpecifiedLength(1);
                    fetchReader.GetReader().ReadToFirstChar();
                }

                return retVal.ToArray();
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Parses IMAP FETCH ENVELOPE data-item.
        /// </summary>
        /// <param name="fetchReader">Fetch reader.</param>
        /// <returns>Returns parsed IMAP FETCH ENVELOPE data-item.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>fetchReader</b> is null reference.</exception>
        internal static IMAP_Envelope Parse(IMAP_Client._FetchResponseReader fetchReader)
        {
            if(fetchReader == null){
                throw new ArgumentNullException("fetchReader");
            }

            /* RFC 3501 7.4.2 ENVELOPE.
                A parenthesized list that describes the envelope structure of a
                message.  This is computed by the server by parsing the
                [RFC-2822] header into the component parts, defaulting various
                fields as necessary.

                The fields of the envelope structure are in the following
                order: date, subject, from, sender, reply-to, to, cc, bcc,
                in-reply-to, and message-id.  The date, subject, in-reply-to,
                and message-id fields are strings.  The from, sender, reply-to,
                to, cc, and bcc fields are parenthesized lists of address
                structures.

                An address structure is a parenthesized list that describes an
                electronic mail address.  The fields of an address structure
                are in the following order: personal name, [SMTP]
                at-domain-list (source route), mailbox name, and host name.

                [RFC-2822] group syntax is indicated by a special form of
                address structure in which the host name field is NIL.  If the
                mailbox name field is also NIL, this is an end of group marker
                (semi-colon in RFC 822 syntax).  If the mailbox name field is
                non-NIL, this is a start of group marker, and the mailbox name
                field holds the group name phrase.

                If the Date, Subject, In-Reply-To, and Message-ID header lines
                are absent in the [RFC-2822] header, the corresponding member
                of the envelope is NIL; if these header lines are present but
                empty the corresponding member of the envelope is the empty
                string.

                    Note: some servers may return a NIL envelope member in the
                    "present but empty" case.  Clients SHOULD treat NIL and
                    empty string as identical.

                    Note: [RFC-2822] requires that all messages have a valid
                    Date header.  Therefore, the date member in the envelope can
                    not be NIL or the empty string.

                    Note: [RFC-2822] requires that the In-Reply-To and
                    Message-ID headers, if present, have non-empty content.
                    Therefore, the in-reply-to and message-id members in the
                    envelope can not be the empty string.

                If the From, To, cc, and bcc header lines are absent in the
                [RFC-2822] header, or are present but empty, the corresponding
                member of the envelope is NIL.

                If the Sender or Reply-To lines are absent in the [RFC-2822]
                header, or are present but empty, the server sets the
                corresponding member of the envelope to be the same value as
                the from member (the client is not expected to know to do
                this).

                    Note: [RFC-2822] requires that all messages have a valid
                    From header.  Therefore, the from, sender, and reply-to
                    members in the envelope can not be NIL.
            */

            // Eat "ENVELOPE".
            fetchReader.GetReader().ReadWord();
            fetchReader.GetReader().ReadToFirstChar();
            // Eat starting "(".
            fetchReader.GetReader().ReadSpecifiedLength(1);

            // Read "date".
            DateTime date = DateTime.MinValue;
            string dateS = fetchReader.ReadString();
            if(dateS != null){
                date = MIME_Utils.ParseRfc2822DateTime(dateS);
            }

            // Read "subject".
            string subject =  ReadAndDecodeWord(fetchReader.ReadString());

            // Read "from"
            Mail_t_Address[] from = ReadAddresses(fetchReader);

            //Read "sender"
            Mail_t_Address[] sender = ReadAddresses(fetchReader);

            // Read "reply-to"
            Mail_t_Address[] replyTo = ReadAddresses(fetchReader);

            // Read "to"
            Mail_t_Address[] to = ReadAddresses(fetchReader);

            // Read "cc"
            Mail_t_Address[] cc = ReadAddresses(fetchReader);

            // Read "bcc"
            Mail_t_Address[] bcc = ReadAddresses(fetchReader);

            // Read "in-reply-to"
            string inReplyTo = fetchReader.ReadString();

            // Read "message-id"
            string messageID = fetchReader.ReadString();

            // Eat ending ")".
            fetchReader.GetReader().ReadToFirstChar();
            fetchReader.GetReader().ReadSpecifiedLength(1);

            return new IMAP_Envelope(date,subject,from,sender,replyTo,to,cc,bcc,inReplyTo,messageID);
        }
Esempio n. 16
0
        /// <summary>
        /// Reads next continuing FETCH line and stores to fetch reader 'r'.
        /// </summary>
        /// <param name="imap">IMAP client.</param>
        /// <param name="r">String reader.</param>
        /// <param name="callback">Fetch completion callback.</param>
        /// <returns>Returns true if completed asynchronously or false if completed synchronously.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>imap</b>,<b>r</b> or <b>callback</b> is null reference.</exception>
        private bool ReadNextFetchLine(IMAP_Client imap,StringReader r,EventHandler<EventArgs<Exception>> callback)
        {
            if(imap == null){
                throw new ArgumentNullException("imap");
            }
            if(r == null){
                throw new ArgumentNullException("r");
            }
            if(callback == null){
                throw new ArgumentNullException("callback");
            }

            SmartStream.ReadLineAsyncOP readLineOP = new SmartStream.ReadLineAsyncOP(new byte[64000],SizeExceededAction.JunkAndThrowException);
            readLineOP.Completed += delegate(object sender,EventArgs<SmartStream.ReadLineAsyncOP> e){
                try{
                    // Read line failed.
                    if(readLineOP.Error != null){
                        callback(this,new EventArgs<Exception>(readLineOP.Error));
                    }
                    else{
                        // Log.
                        imap.LogAddRead(readLineOP.BytesInBuffer,readLineOP.LineUtf8);

                        // Append fetch line to fetch reader.
                        r.AppendString(readLineOP.LineUtf8);

                        ParseDataItems(imap,r,callback);
                    }
                }
                catch(Exception x){
                    callback(this,new EventArgs<Exception>(x));
                }
                finally{
                    readLineOP.Dispose();
                }
            };

            // Read line completed synchronously.
            if(imap.TcpStream.ReadLine(readLineOP,true)){
                try{
                    // Read line failed.
                    if(readLineOP.Error != null){
                        callback(this,new EventArgs<Exception>(readLineOP.Error));

                        return true;
                    }
                    else{
                        // Log.
                        imap.LogAddRead(readLineOP.BytesInBuffer,readLineOP.LineUtf8);

                        // Append fetch line to fetch reader.
                        r.AppendString(readLineOP.LineUtf8);

                        return false;
                    }
                }
                finally{
                    readLineOP.Dispose();
                }
            }

            return true;
        }
Esempio n. 17
0
 public IMAP_Client loginAs(string login, string password)
 {
     IMAP_Client client = new IMAP_Client();
     client.Connect("imap.yandex.ru", 993, true);
     client.Login(login, password);
     client.SelectFolder("INBOX");
     Console.Out.WriteLine("метод loginAS");
     return client;
 }
Esempio n. 18
0
        public override void init()
        {
            using (IMAP_Client imap = new IMAP_Client())
            {
                imap.Connect(m_host, m_port);
                imap.Capability();
                imap.Login(m_user, m_pwd);

                var seqSet = LumiSoft.Net.IMAP.IMAP_t_SeqSet.Parse("1:*");
                var imap_t_Fetch_i = new IMAP_t_Fetch_i[]{
                         new IMAP_t_Fetch_i_Envelope(),//邮件的标题、正文等信息
                         new IMAP_t_Fetch_i_Flags(),//此邮件的标志,应该是已读未读标志
                         new IMAP_t_Fetch_i_InternalDate(),//貌似是收到的日期
                         new IMAP_t_Fetch_i_Rfc822(),//Rfc822是标准的邮件数据流,可以通过Lumisoft.Net.Mail.Mail_Message对象解析出邮件的所有信息(不确定有没有附件的内容)。
                         new IMAP_t_Fetch_i_Uid()
                };

                imap.SelectFolder("INBOX");
                EventHandler<LumiSoft.Net.EventArgs<IMAP_r_u>> lumisoftHandler = new EventHandler<LumiSoft.Net.EventArgs<IMAP_r_u>>(Fetchcallback);
                imap.Fetch(false, seqSet, imap_t_Fetch_i, lumisoftHandler);
            }
        }
Esempio n. 19
-1
        public void getEmail(string login, string password)
        {
            IMAP_Client client = new IMAP_Client();
            client.Connect("imap.yandex.ru", 993, true);
            client.Login(login, password);
            client.SelectFolder("INBOX");

            IMAP_SequenceSet sequence = new IMAP_SequenceSet();
            //sequence.Parse("*:1"); // from first to last
            IMAP_Client_FetchHandler fetchHandler = new IMAP_Client_FetchHandler();

            fetchHandler.NextMessage += new EventHandler(delegate(object s, EventArgs e)
            {
                Console.WriteLine("next message");
            });

            fetchHandler.Envelope += new EventHandler<EventArgs<IMAP_Envelope>>(delegate(object s, EventArgs<IMAP_Envelope> e)
            {
                IMAP_Envelope envelope = e.Value;
                if (envelope.From != null && !String.IsNullOrWhiteSpace(envelope.Subject))
                {
                    Console.WriteLine(envelope.Subject);
                }
            });
            // the best way to find unread emails is to perform server search
            int[] unseen_ids = client.Search(false, "UTF-8", "unseen");
            Console.WriteLine("unseen count: " + unseen_ids.Count().ToString());
            // now we need to initiate our sequence of messages to be fetched
            sequence.Parse(string.Join(",", unseen_ids));
            // fetch messages now
            client.Fetch(false, sequence, new IMAP_Fetch_DataItem[] { new IMAP_Fetch_DataItem_Envelope() }, fetchHandler);
            // uncomment this line to mark messages as read
            // client.StoreMessageFlags(false, sequence, IMAP_Flags_SetType.Add, IMAP_MessageFlags.Seen);
        }