示例#1
0
        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);
        }
示例#2
0
        public override Server creack(String ip, int port, String username, String password, int timeOut)
        {
            IMAP_Client conn   = null;
            Server      server = new Server();

            try
            {
                conn = new IMAP_Client();
                //与IMAP服务器建立连接
                conn.Timeout = timeOut;
                conn.Connect(ip, port, true);
                if (conn.IsConnected)
                {
                    conn.Login(username, password);

                    if (conn.IsAuthenticated)
                    {
                        server.isSuccess = conn.IsAuthenticated;
                        server.banner    = conn.GreetingText;
                    }
                }
            }
            catch (Exception e) {
                throw e;
            }
            finally
            {
                if (conn != null)
                {
                    conn.Disconnect();
                }
            }
            return(server);
        }
示例#3
0
        /// <summary>
        /// Connects to email server.
        /// </summary>
        /// <param name="useSSL">if set to <c>true</c> [use SSL].</param>
        /// <returns></returns>
        private bool ConnectToEmailServer(bool useSSL)
        {
            Disconnect();
            if (_client != null && !_client.IsDisposed)
            {
                _client.Dispose();
            }
            _client = new IMAP_Client();
            try {
                if (useSSL)
                {
                    _client.Connect(_settings.Server, WellKnownPorts.IMAP4_SSL, true);          //port 993
                }
                else
                {
                    _client.Connect(_settings.Server, WellKnownPorts.IMAP4, false);             //port 143
                }
                if (_settings.Security == SecurityEnum.TLS)
                {
                    _client.StartTls();
                }

                _client.Login(_settings.User, _settings.Pass);

                return(true);
            } catch (Exception ex) {
                //Debug.WriteLine(ex.Message);
                AppJournal.Write("EmailImapTransport: ConnectToEmailServer " + ex.Message);
                return(false);
            }
        }
示例#4
0
 /// <summary>
 /// Get connect from yandex.
 /// </summary>
 /// <param name="login">Login from email.</param>
 /// <param name="password">Password from email.</param>
 public void connect(string login, string password)
 {
     client = new IMAP_Client();
     client.Connect("imap.yandex.ru", 993, true);
     client.Login(login, password);
     Console.Out.WriteLine("метод connect");
 }
示例#5
0
        /// <summary>
        /// Удаляет все сообщения из IMAP папки по фильтру subject
        /// </summary>
        public static void ClearImapFolder(string mailbox, string password, string folder, string subject)
        {
            using (var imapClient = new IMAP_Client()) {
                imapClient.Connect(Settings.Default.IMAPHost, Convert.ToInt32(Settings.Default.IMAPPort));
                imapClient.Authenticate(mailbox, password);
                imapClient.SelectFolder(folder);
                var sequenceSet = new IMAP_SequenceSet();
                sequenceSet.Parse("1:*", Int64.MaxValue);
                var items = String.IsNullOrEmpty(subject)
                                        ? imapClient.FetchMessages(sequenceSet, IMAP_FetchItem_Flags.UID, false, false)
                                        : imapClient.FetchMessages(sequenceSet, IMAP_FetchItem_Flags.UID | IMAP_FetchItem_Flags.Envelope, false, false);

                //производим фильтрацию, если параметр subject установлен
                if (!String.IsNullOrEmpty(subject) && items != null && items.Length > 0)
                {
                    items = items
                            .Where(i => i.Envelope.Subject?.Equals(subject, StringComparison.CurrentCultureIgnoreCase) == true)
                            .ToArray();
                }

                if ((items != null) && (items.Length > 0))
                {
                    var sequenceMessages = new IMAP_SequenceSet();
                    sequenceMessages.Parse(String.Join(",", items.Select(i => i.UID.ToString()).ToArray()), long.MaxValue);
                    imapClient.DeleteMessages(sequenceMessages, true);
                }
            }
        }
示例#6
0
        /*
         *      public void marksUnread(IMAP_Client client, IMAP_Client_FetchHandler fetchHandler)
         *      {
         *           IMAP_SequenceSet sequence = new IMAP_SequenceSet();
         *          //sequence.Parse("*:1"); // from first to last
         *          // 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);
         *
         *      }*/

        #region method LoadFolderMessages

        /// <summary>
        /// Gets specified folder messages list from IMAP server and adds them to UI.
        /// </summary>
        /// <param name="folder">IMAP folder which messages to load.</param>
        private void LoadFolderMessages(IMAP_Client m_pImap, string folder)
        {
            try
            {
                m_pImap.SelectFolder(folder);
                // No messages in folder, skip fetch.
                if (m_pImap.SelectedFolder.MessagesCount == 0)
                {
                    return;
                }
                // Start fetching.
                m_pImap.Fetch(
                    false,
                    IMAP_t_SeqSet.Parse("*"),
                    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_Rfc822Size(),
                    new IMAP_t_Fetch_i_Uid()
                }, m_pImap_Fetch_MessageItems_UntaggedResponse
                    );
            }
            catch (Exception x)
            {
                Console.WriteLine(x.ToString());
            }
        }
示例#7
0
        public void functionIMAP()
        {
            using (IMAP_Client c = new IMAP_Client())
            {
                try
                {
                    //连接IMAP_Client服务器
                    c.Connect("outlook.office365.com", 993, true);
                    //验证用户身份
                    c.Login(UserName, Pwd);  //邮件密码/smtp、pop3授权码

                    //MessageBox.Show("数量:" + c.GetFolders(null).ToList().Count().ToString());
                    c.GetFolders(null).ToList().ForEach(f => {
                        Console.WriteLine(f.FolderName);
                        var s = c.FolderStatus(f.FolderName);
                        s.ToList().ForEach(sIt => {
                            MessageBox.Show(string.Format("总数:{0},未读:{1},最近{2}", sIt.MessagesCount, sIt.MessagesCount, sIt.UnseenCount));
                        });
                    });
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
            }
        }
        public void getMailSendImap(string userName, string psw, string service, bool ssl, int port)
        {
            try
            {
                IMAP_Client imapc      = loginMail(userName, psw, service, ssl, port);
                var         folderlist = imapc.GetFolders(null);
                imapc.SelectFolder("Éléments envoyés");
                //imapc.SelectFolder("INBOX");
                var folder = imapc.SelectedFolder;
                var seqSet = IMAP_t_SeqSet.Parse("1:*");
                var items  = new IMAP_t_Fetch_i[]
                {
                    new IMAP_t_Fetch_i_Envelope(),
                    new IMAP_t_Fetch_i_Uid(),
                    new IMAP_t_Fetch_i_Flags(),
                    new IMAP_t_Fetch_i_InternalDate(),
                    new IMAP_t_Fetch_i_Rfc822()
                };

                imapc.Fetch(false, seqSet, items, this.m_pImap_Fetch_MessageItems_UntaggedResponse);
                System.Threading.Thread.Sleep(500);
                DataTable      dtmail           = datalistmail.getInstance().getdtSend();
                SqlDataAdapter adapteremailrecu = CreerDataAdapterFormail("MailSend");
                dtmail.DefaultView.Sort = "maildateTime DESC";
                int tr   = adapteremailrecu.Update(dtmail.Select(null, null, DataViewRowState.ModifiedCurrent));
                int tr12 = adapteremailrecu.Update(dtmail.Select(null, null, DataViewRowState.Added));
                //System.Threading.Thread.Sleep(500);
                imapc.Disconnect();
            }
            catch (Exception ex)
            {
                Console.WriteLine("ErrGetMail:" + ex.Message);
            }
        }
        public void supprMailIMAP(string userName, string psw, string service, bool ssl, int port, string mailsupprBegin, string mailsupprEnd)
        {
            IMAP_Client imapc      = loginMail(userName, psw, service, ssl, port);
            var         folderlist = imapc.GetFolders(null);

            imapc.SelectFolder("INBOX");
            var folder = imapc.SelectedFolder;
            var seqSet = IMAP_t_SeqSet.Parse("@begin:@end".Replace("@begin", mailsupprBegin).Replace("@end", mailsupprEnd));
            var items  = new IMAP_t_Fetch_i[]
            {
                new IMAP_t_Fetch_i_Envelope(),
                new IMAP_t_Fetch_i_Uid(),
                new IMAP_t_Fetch_i_Flags(),
                new IMAP_t_Fetch_i_InternalDate(),
                new IMAP_t_Fetch_i_Rfc822()
            };

            try
            {
                imapc.StoreMessageFlags(true, seqSet, IMAP_Flags_SetType.Add, new IMAP_t_MsgFlags(new string[] { IMAP_t_MsgFlags.Deleted }));
            }
            catch
            {
            }
            imapc.Disconnect();
        }
示例#10
0
        /// <summary>
        /// Loads IMAP server folders to UI.
        /// </summary>
        private void LoadFolders(IMAP_Client m_pImap)
        {
            IMAP_r_u_List[] folders = m_pImap.GetFolders(null);

            char folderSeparator = m_pImap.FolderSeparator;

            foreach (IMAP_r_u_List folder in folders)
            {
                string[] folderPath = folder.FolderName.Split(folderSeparator);
                Console.WriteLine(folder.FolderName);
                // Conatins sub folders.
                if (folderPath.Length > 1)
                {
                    string currentPath = "";
                    foreach (string fold in folderPath)
                    {
                        if (currentPath.Length > 0)
                        {
                            Console.WriteLine(currentPath, fold);
                            currentPath += "/" + fold;
                        }
                        else
                        {
                            Console.WriteLine(currentPath, fold);
                            currentPath = fold;
                        }
                    }
                }
            }
        }
示例#11
0
 public static void StoreMessage(string mailbox, string password, string folder, byte[] messageBytes)
 {
     using (var imapClient = new IMAP_Client()) {
         imapClient.Connect(Settings.Default.IMAPHost, Convert.ToInt32(Settings.Default.IMAPPort));
         imapClient.Authenticate(mailbox, password);
         imapClient.SelectFolder(Settings.Default.IMAPSourceFolder);
         imapClient.StoreMessage(folder, messageBytes);
     }
 }
示例#12
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);
        }
示例#13
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
         };
     }
 }
示例#14
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));
             *
             */
        }
示例#15
0
        public static List <IMAP_FetchItem> CheckImapFolder(string mailbox, string password, string folder)
        {
            using (var imapClient = new IMAP_Client()) {
                imapClient.Connect(Settings.Default.IMAPHost, Convert.ToInt32(Settings.Default.IMAPPort));
                imapClient.Authenticate(mailbox, password);
                imapClient.SelectFolder(folder);
                var sequenceSet = new IMAP_SequenceSet();
                sequenceSet.Parse("1:*", Int64.MaxValue);
                var items = imapClient.FetchMessages(sequenceSet, IMAP_FetchItem_Flags.UID | IMAP_FetchItem_Flags.Envelope, false, false);
                if ((items != null) && (items.Length > 0))
                {
                    return(items.ToList());
                }
            }

            return(new List <IMAP_FetchItem>());
        }
        public IMAP_Client loginMail(string userName, string psw, string service, bool ssl, int port)
        {
            IMAP_Client imapc = new IMAP_Client();

            try
            {
                if (imapc.IsConnected)
                {
                    imapc.Disconnect();
                }
                imapc.Connect(service, port, ssl);
                imapc.Login(userName, psw);
            }
            catch (Exception ex)
            {
                Console.WriteLine("ErrConnect:" + ex.Message);
            }
            return(imapc);
        }
示例#17
0
 private void LoadMessage(IMAP_Client m_pImap, string folder)
 {
     try
     {//uid.ToString()
         m_pImap.SelectFolder(folder);
         // Start fetching.
         m_pImap.Fetch(
             true,
             IMAP_t_SeqSet.Parse("*"),//последнее письмо должно быть
             new IMAP_t_Fetch_i[] {
             new IMAP_t_Fetch_i_Rfc822()
         },
             this.m_pImap_Fetch_Message_UntaggedResponse
             );
     }
     catch (Exception x)
     {
         Console.WriteLine("ЭКСЕПШН" + x.ToString() + "ЗАКОНЧИЛСЯ");
     }
 }
        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);
        }
示例#19
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);
        }
示例#20
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);
            }
        }
示例#21
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 + "'.");
            }
        }
示例#22
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;
        }
示例#23
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;
            }
        }
示例#24
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);
        }
示例#25
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))
                {
                    // BODYSTRUCTURE can contain string literals, we just try to parse it.
                    // If parse fails, just get string literal and try again as long as all BODYSTRUCTURE data has read.

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

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

                        try{
                            bodyStructure = tmpReader.ReadParenthesized();
                            // We got full BODYSTRUCTURE, 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_BodyStructure.Parse(new StringReader(bodyStructure)));
                }

                #endregion

                #region BODYSTRUCTURE

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

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

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

                        try{
                            bodyStructure = tmpReader.ReadParenthesized();
                            // We got full BODYSTRUCTURE, 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_BodyStructure.Parse(new StringReader(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));
        }
示例#26
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);
        }
示例#27
0
            /// <summary>
            /// Default constructor.
            /// </summary>
            /// <param name="imap">IMAP client.</param>
            /// <param name="fetchLine">Initial FETCH response line.</param>
            /// <param name="handler">Fetch data-items handler.</param>
            /// <exception cref="ArgumentNullException">Is raised when <b>imap</b>,<b>fetchLine</b> or <b>handler</b> is null reference.</exception>
            public _FetchResponseReader(IMAP_Client imap,string fetchLine,IMAP_Client_FetchHandler handler)
            {
                if(imap == null){
                    throw new ArgumentNullException("imap");
                }
                if(fetchLine == null){
                    throw new ArgumentNullException("fetchLine");
                }
                if(handler == null){
                    throw new ArgumentNullException("handler");
                }

                m_pImap     = imap;
                m_FetchLine = fetchLine;
                m_pHandler  = handler;
            }
示例#28
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 + "'.");
            }
        }
示例#29
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));
        }
示例#30
0
        private void imapRecvMail()
        {
            using (var imap_client = new IMAP_Client())
            {
                imap_client.Connect(mailAccount.recv_server, mailAccount.recv_port, mailAccount.recv_ssl);

                // Call Capability even if you don't care about capabilities, it also controls IMAP client features.
                imap_client.Capability();

                imap_client.Login(mailAccount.account, mailAccount.password);
                imap_client.SelectFolder("INBOX");
                try
                {
                    imap_total = imap_client.SelectedFolder.MessagesCount;

                    workInfo.SetInfo("正在接收邮件列表... 请稍后");

                    imap_recv_messages = new List<IMAP_r_u_Fetch>();

                    imap_client.Fetch(
                        false,
                        IMAP_t_SeqSet.Parse("1:*"),
                        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_Rfc822Size(),
                        new IMAP_t_Fetch_i_Uid()
                    },
                        this.callback_fetch_message_items
                    );

                    if (imap_recv_messages.Count == 0)
                        return;
                    workInfo.SetInfo("正在接收邮件... 请稍后");

                    imap_total = imap_recv_messages.Count;
                    int count = 1;
                    imap_client.FetchGetStoreStream += imap_client_FetchGetStoreStream;
                    foreach (IMAP_r_u_Fetch reps in imap_recv_messages)
                    {
                        if (isStop)
                            return;
                        workInfo.SetProgress(imap_total, count);
                        current_imap_fetch = reps;

                        string text = null;
                        if (reps.Envelope != null)
                        {
                            if (reps.Envelope.Subject != null && reps.Envelope.Subject.IndexOf("&#") != -1)
                                workInfo.AddDetail("正在接收邮件:" + (text = HttpUtility.HtmlDecode(reps.Envelope.Subject)), Colors.Black);
                            else
                                workInfo.AddDetail("正在接收邮件:" + (text = reps.Envelope.Subject), Colors.Black);
                        }

                        //--通知其他订阅人--//
                        XElement el = new XElement("subscribe");
                        el.SetAttributeValue("total", imap_total);
                        el.SetAttributeValue("count", count);
                        el.SetAttributeValue("account", mailAccount.account);
                        el.SetAttributeValue("type", "accept_mail");
                        el.SetAttributeValue("detail", "true");
                        el.SetAttributeValue("principal", Desktop.instance.loginedPrincipal.loginId);
                        el.SetAttributeValue("principal_name", Desktop.instance.loginedPrincipal.name);
                        el.SetAttributeValue("subject", "正在接收邮件:" + text);
                        MessageManager.instance.publishMessage(mailAccount.pubId, "subscribe", el.ToString());
                        //-----------//

                        imap_client.Fetch(
                            true,
                            IMAP_t_SeqSet.Parse(reps.UID.UID.ToString()),
                            new IMAP_t_Fetch_i[]{
                            new IMAP_t_Fetch_i_Rfc822Header(),
                            new IMAP_t_Fetch_i_Rfc822()
                        },
                            this.callback_fetch_message
                        );
                        count++;

                        try
                        {
                            //唤醒Syncworker
                            SyncWorker.instance.Notify(imap_total);
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Debug.WriteLine(ex.Message);
                        }
                    }
                    imap_client.FetchGetStoreStream -= imap_client_FetchGetStoreStream;

                    if (imap_recv_messages.Count > 0)
                    {
                        SyncWorker.instance.WorkInfo = workInfo;
                        if (SyncWorker.instance.Thread != null)
                            SyncWorker.instance.Thread.Join();
                    }
                }
                catch (Exception ex)
                {
                    workInfo.SetStatus(false, "邮件接收过程中发生错误:" + ex.Message);
                    hasError = true;
                }
            }
        }
示例#31
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);
        }
 public virtual void IMAPAuth(IMAP_Client c)
 {
     c.Authenticate(Settings.Default.IMAPUser, Settings.Default.IMAPPass);
 }
示例#33
0
        public void ProcessIMAPFolder()
        {
            using (var imapClient = new IMAP_Client()) {
                _imapClient = imapClient;
                ConnectToIMAP();

                try {
                    var items    = Enumerable.Empty <IMAP_FetchItem>().ToArray();
                    var toDelete = new List <IMAP_FetchItem>();
                    do
                    {
                        toDelete.Clear();
                        ImapReader.PingReader();
                        items = FetchUIDs();
                        if (log.IsDebugEnabled)
                        {
                            log.DebugFormat("Получено {0} UIDs", items.Length);
                        }
                        //обрабатываем мисьма пачками что бы уменьшить вероятность появления дублей
                        //при остановке шатной или аварийной остановке
                        items = items.Take(100).ToArray();
                        ImapReader.PingReader();

                        foreach (var item in items)
                        {
                            if (log.IsDebugEnabled)
                            {
                                log.DebugFormat("Обработка {0} UID", item.UID);
                            }

                            IMAP_FetchItem[] OneItem = null;
                            try {
                                OneItem = FetchMessages(item.UID);

                                Message = Mime.Parse(OneItem[0].MessageData);

                                CurrentUID = item.UID;

                                ImapReader.PingReader();
                                ImapReader.ProcessMime(Message);
                                toDelete.Add(item);
                            }
                            catch (Exception ex) {
                                if (log.IsDebugEnabled)
                                {
                                    log.Debug(String.Format("Не удалось обработать письмо {0} UID", item.UID), ex);
                                }
                                Message = null;
                                var errorInfo = GetErrorInfo(item.UID);
                                if (UIDTimeout(errorInfo))
                                {
                                    ErrorInfos.Remove(errorInfo);
                                    toDelete.Add(item);
                                    ImapReader.ProcessBrokenMessage(item, OneItem, ex);
                                }
                            }
                        }

                        //Производим удаление писем
                        if (toDelete.Count > 0)
                        {
                            var sequence = new IMAP_SequenceSet();

                            sequence.Parse(String.Join(",", toDelete.Select(i => i.UID.ToString())), long.MaxValue);
                            imapClient.DeleteMessages(sequence, true);
                        }
                    } while (items.Length > 0 && toDelete.Count > 0);
                }
                finally {
                    Message = null;
                }
            }
        }
示例#34
0
 public override void IMAPAuth(IMAP_Client client)
 {
     client.Authenticate(_imapUser, _imapPassword);
 }
示例#35
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();
            }
        }
示例#36
0
        //#region 获取当前外网ip地址
        //private string GetIP()
        //{
        //    string strUrl = "http://www.ip138.com/ip2city.asp"; //获得IP的网址了
        //    Uri uri = new Uri(strUrl);
        //    WebRequest wr = WebRequest.Create(uri);
        //    Stream s = wr.GetResponse().GetResponseStream();
        //    StreamReader sr = new StreamReader(s, Encoding.Default);
        //    string all = sr.ReadToEnd(); //读取网站的数据
        //    int i = all.IndexOf("[") + 1;
        //    string tempip = all.Substring(i, 15);
        //    string ip = tempip.Replace("]", "").Replace(" ", "");
        //    return ip;
        //}
        //#endregion


        #region 未读邮件信息

        private void QueryEmailStatus()
        {
            IMAP_Client IMAPServer = new IMAP_Client();

            try
            {
                //连接邮件服务器通过传入邮件服务器地址和用于IMAP协议的端口号
                IMAPServer.Connect(@"imap.exmail.sina.com", 143, false);
                string currUserCode  = UserInfo.GetInstence().UserCode;
                string emailPassword = string.Empty;
                //登陆邮箱,前者帐号后者密码
                using (var context = new BugTraceEntities(EntityContextHelper.GetEntityConnString()))
                {
                    var currUserExt = context.SYS_UserExt.Where(p => p.UserCode == currUserCode).FirstOrDefault();
                    if (currUserExt != null)
                    {
                        emailPassword = Encrypt.TripleDESDecrypting(currUserExt.EmailPassword);
                    }
                }
                if (string.IsNullOrWhiteSpace(emailPassword))
                {
                    this.Invoke(new MethodInvoker(delegate
                    {
                        this.lblEmailInfo.Text = "邮箱登陆失败!请先在个人设置中设置密码!";
                    }));
                    return;
                }
                IMAPServer.Login(currUserCode + "@ecode.net.cn", emailPassword);

                //选中收件箱
                IMAPServer.SelectFolder("INBOX");

                //取出收件箱
                var folder = IMAPServer.SelectedFolder;

                //收件箱邮件总数
                //folder.MessagesCount.ToString();
                //收件箱未读邮件总数
                //folder.RecentMessagesCount.ToString();



                //以下开始取出邮件
                //首先确定取第x到第n封邮件,"1:*"表示第1封到最后一封
                int msgCount = folder.MessagesCount - 20;
                if (msgCount <= 0)
                {
                    msgCount = 1;
                }
                var seqSet = LumiSoft.Net.IMAP.IMAP_t_SeqSet.Parse(msgCount.ToString() + ":*");
                //根据数组中的成员决定取出邮件的那些信息
                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()           //返回邮件的UID号,UID号是唯一标识邮件的一个号码
                };
                //创建一个符合lumisoft的回调函数的委托。
                //当调用fetch函数完成时,会自动调用用户自定义的函数,这里是Fetchcallback(我自己起的名字,名字无意义,保证参数是object,LumiSoft . Net . EventArgs<IMAP_r_u> 两个就好
                EventHandler <LumiSoft.Net.EventArgs <IMAP_r_u> > lumisoftHandler = new EventHandler <LumiSoft.Net.EventArgs <IMAP_r_u> >(Fetchcallback);

                //把上边定义好的参数传入fetch函数,就会取出邮件
                //lumisoftHandler指向的函数在每取出一封邮件的时候会被触发一次
                IMAPServer.Fetch(false, seqSet, imap_t_Fetch_i, lumisoftHandler);
                this.Invoke(new MethodInvoker(delegate
                {
                    this.lblEmailInfo.Text     = "";
                    this.linkEmailInfo.Text    = "您当前共有" + UnReadEmailCount + "封未读邮件!<<click me>>(只搜索最近20封邮件)";
                    this.linkEmailInfo.Visible = true;
                    this.dgvEmail.DataSource   = dtblEmail;
                }));
            }
            catch (Exception ex)
            {
                MyLog.LogError("读取未读邮件失败!", ex);
                if (ex.Message.IndexOf("Invalid login credentials") != -1)
                {
                    this.Invoke(new MethodInvoker(delegate
                    {
                        this.lblEmailInfo.Text = "邮箱登陆失败!请先在个人设置中设置密码!";
                    }));
                }
            }
            finally
            {
                IMAPServer.Disconnect();
            }
        }