POP3 Client.
Inheritance: IDisposable
        /// <summary>
        /// 从邮件中获取新的更新信息
        /// </summary>
        protected void GetEmailUpdateInfo()
        {
            //获取邮件配置信息
            FrameConfig FC = new FrameConfig();
            string ConfigStr = FC.GetDetail("HostMail").ConfigValue;
            FrameCommon FComm = new FrameCommon();
            string UserName = FComm.FindValueFromStr(ConfigStr, "UserName="******"Password="******"POP3Host=").Trim();
            int Pop3Port = Convert.ToInt32(FComm.FindValueFromStr(ConfigStr, "POP3Port=").Trim());
            bool IsSSL = FComm.FindValueFromStr(ConfigStr, "EnableSsl=").Trim() == "1" ? true : false;
            //连接邮件服务器
            using (POP3_Client MyClient = new POP3_Client())
            {
                MyClient.Connect(Pop3Host, Pop3Port, IsSSL);
                MyClient.Authenticate(UserName, Password, false);
                string SystemGuid = FComm.GetSystemGuid();
                for (int i = 0; i < MyClient.Messages.Count; i++)
                {
                    POP3_ClientMessage mail = MyClient.Messages[i];
                    Mime m = Mime.Parse(mail.MessageToByte());
                    if (m.Attachments.Length > 0 && m.MainEntity.Subject.ToLower().IndexOf(SystemGuid.ToLower()) > -1) //如果有附件,且为该系统的标识
                    {
                        string UpdateSubject = m.MainEntity.Subject;
                        DateTime UpdateTime = m.MainEntity.Date;
                        string UpdateContent = m.BodyText;
                        int FileCount = m.Attachments.Length;
                        string UpdateGuid = System.Guid.NewGuid().ToString();
                        string FilePath = "/UpdateBackUp/" + UpdateTime.ToString("yyyyMMdd") + "-" + new System.Random().Next(1000, 9999).ToString() + "/"; //生成路径
                        string FilenameList = "";
                        //将基本信息存入数据库

                        foreach (MimeEntity entry in m.Attachments)
                        {

                            string fileName = entry.ContentDisposition_FileName; //获取文件名称
                            if (fileName != null && fileName.Trim() != "")  //有些文件取不到,如txt
                            {
                                FilenameList = FilenameList + fileName + ";";
                                string DirPath = Server.MapPath(FilePath);
                                System.IO.Directory.CreateDirectory(DirPath);
                                string FileURL = DirPath + fileName;
                                FileInfo fi = new FileInfo(FileURL);
                                byte[] data = entry.Data;
                                FileStream pFileStream = null;
                                pFileStream = new FileStream(FileURL, FileMode.Create);
                                pFileStream.Write(data, 0, data.Length);
                                pFileStream.Close();
                            }
                        }
                        mail.MarkForDeletion();
                        new FrameUpdate().InsertUpdate(UpdateGuid, UpdateTime, UpdateSubject, UpdateContent, FileCount, FilenameList, FilePath);
                    }

                }
                MyClient.Disconnect();
            }

            this.Refresh();
        }
Exemple #2
0
 public ReceiverMail(Guid Receiver)
 {
     _Pop3Client = new POP3_Client();
     _Account = MailAccountHelper.GetMailAccount(Receiver);
     _InvalidMails = new ManageMail();
        // _FE = new FleetEntities();
     _ReceiverObjects = new List<ReceiverObject>();
 }
        private void StartEmailDownload()
        {
            
            using (POP3_Client pop3 = new POP3_Client())
            {
                pop3.Connect(this.qqEmailServer, 995, true);

                pop3.Login(this.emailAccount, this.password);
                
                POP3_ClientMessageCollection messages = pop3.Messages;

                Console.WriteLine("EmailCount:{0}", messages.Count);

                for (int i = 0; i < messages.Count; i++)
                {
                    POP3_ClientMessage message = messages[i];   //转化为POP3  

                    Console.WriteLine("\r\nChecking Email :{0} ...", i + 1);

                    if (message != null)
                    {
                        byte[] messageBytes = message.MessageToByte();
                        Mail_Message mime_message = Mail_Message.ParseFromByte(messageBytes);

                        string senderAddress = mime_message.From == null ? "<NULL>" : mime_message.From[0].Address;
                        string subject = mime_message.Subject ?? "<NULL>";

                        Console.WriteLine(subject);
                        
                        DirectoryInfo dir = new DirectoryInfo(this.savePath);
                        if (!dir.Exists) dir.Create();

                        MIME_Entity[] attachments = mime_message.GetAttachments(true);

                        foreach (MIME_Entity entity in attachments)
                        {
                            if (entity.ContentDisposition != null)
                            {
                                string fileName = entity.ContentDisposition.Param_FileName;
                                string extension = new FileInfo(fileName).Extension;

                                if (!string.IsNullOrEmpty(fileName) && extension == ".pdf")
                                {
                                    string path = Path.Combine(dir.FullName, fileName);
                                    MIME_b_SinglepartBase byteObj = (MIME_b_SinglepartBase)entity.Body;
                                    Stream decodedDataStream = byteObj.GetDataStream();
                        
                                    using (FileStream fs = new FileStream(path, FileMode.Create))
                                    {
                                        LumiSoft.Net.Net_Utils.StreamCopy(decodedDataStream, fs, 4000);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Disposes message.
        /// </summary>
        internal void Dispose()
        {
            if (m_IsDisposed)
            {
                return;
            }

            m_IsDisposed = true;
            m_Pop3Client = null;
        }
        public static List<Email> GetAllEmails(string server, int port, string user, string pwd, bool usessl, bool deleteafterread, ref List<string> errors )
        {
            var ret = new List<Email>();
            errors.Clear();
            var oClient = new POP3_Client();
            try
            {
                oClient.Connect(server, port, usessl);
                oClient.Authenticate(user, pwd, true);
            }
            catch (Exception exception)
            {
                errors.Add("Error connect/authenticate - " + exception.Message);
                return null;
            }
            foreach (POP3_ClientMessage message in oClient.Messages)
            {
                var wrapper = new Email();
                wrapper.Uid = message.UID;
                try
                {
                    Mail_Message mime = Mail_Message.ParseFromByte(message.HeaderToByte());
                    wrapper.Subject = mime.Subject;
                    wrapper.From = mime.From[0].Address;
                    wrapper.To = mime.To[0].ToString();
                    mime = Mail_Message.ParseFromByte(message.MessageToByte());

                    string sa = mime.BodyHtmlText;
                    if (sa == null)
                        wrapper.TextBody = mime.BodyText;
                    else
                        wrapper.HtmlBody = sa;
                }
                catch (Exception exception)
                {
                    errors.Add("Error reading " + wrapper.Uid + " - " + exception.Message);
                }
                if(deleteafterread)
                    message.MarkForDeletion();
                ret.Add(wrapper);
            }
            oClient.Disconnect();
            oClient.Dispose();

            return ret;
        }
Exemple #6
0
            /// <summary>
            /// Starts operation processing.
            /// </summary>
            /// <param name="owner">Owner POP3 client.</param>
            /// <returns>Returns true if asynchronous operation in progress or false if operation completed synchronously.</returns>
            /// <exception cref="ArgumentNullException">Is raised when <b>owner</b> is null reference.</exception>
            internal bool Start(POP3_Client owner)
            {
                if(owner == null){
                    throw new ArgumentNullException("owner");
                }

                m_pPop3Client = owner;

                SetState(AsyncOP_State.Active);

                try{
                    /* RFC 5034 4. The AUTH Command.

                        AUTH mechanism [initial-response]

                        Arguments:

                        mechanism: A string identifying a SASL authentication mechanism.

                        initial-response: An optional initial client response, as
                                          defined in Section 3 of [RFC4422].  If present, this response
                                          MUST be encoded as Base64 (specified in Section 4 of
                                          [RFC4648]), or consist only of the single character "=", which
                                          represents an empty initial response.
                    */

                    if(m_pSASL.SupportsInitialResponse){
                        byte[] buffer = Encoding.UTF8.GetBytes("AUTH " + m_pSASL.Name + " " + Convert.ToBase64String(m_pSASL.Continue(null)) + "\r\n");

                        // Log
                        m_pPop3Client.LogAddWrite(buffer.Length,Encoding.UTF8.GetString(buffer).TrimEnd());

                        // Start command sending.
                        m_pPop3Client.TcpStream.BeginWrite(buffer,0,buffer.Length,this.AuthCommandSendingCompleted,null);
                    }
                    else{
                        byte[] buffer = Encoding.UTF8.GetBytes("AUTH " + m_pSASL.Name + "\r\n");

                        // Log
                        m_pPop3Client.LogAddWrite(buffer.Length,"AUTH " + m_pSASL.Name);

                        // Start command sending.
                        m_pPop3Client.TcpStream.BeginWrite(buffer,0,buffer.Length,this.AuthCommandSendingCompleted,null);
                    }
                }
                catch(Exception x){
                    m_pException = x;
                    m_pPop3Client.LogAddException("Exception: " + x.Message,x);
                    SetState(AsyncOP_State.Completed);
                }

                // Set flag rise CompletedAsync event flag. The event is raised when async op completes.
                // If already completed sync, that flag has no effect.
                lock(m_pLock){
                    m_RiseCompleted = true;

                    return m_State == AsyncOP_State.Active;
                }
            }
Exemple #7
0
            /// <summary>
            /// Starts operation processing.
            /// </summary>
            /// <param name="owner">Owner POP3 client.</param>
            /// <returns>Returns true if asynchronous operation in progress or false if operation completed synchronously.</returns>
            /// <exception cref="ArgumentNullException">Is raised when <b>owner</b> is null reference.</exception>
            internal bool Start(POP3_Client owner)
            {
                if(owner == null){
                    throw new ArgumentNullException("owner");
                }

                m_pPop3Client = owner;

                SetState(AsyncOP_State.Active);

                try{
                    /* RFC 2449 CAPA
                        Arguments:
                            none

                        Restrictions:
                            none

                        Discussion:
                            An -ERR response indicates the capability command is not
                            implemented and the client will have to probe for
                            capabilities as before.

                            An +OK response is followed by a list of capabilities, one
                            per line.  Each capability name MAY be followed by a single
                            space and a space-separated list of parameters.  Each
                            capability line is limited to 512 octets (including the
                            CRLF).  The capability list is terminated by a line
                            containing a termination octet (".") and a CRLF pair.

                        Possible Responses:
                            +OK -ERR

                        Examples:
                            C: CAPA
                            S: +OK Capability list follows
                            S: TOP
                            S: USER
                            S: SASL CRAM-MD5 KERBEROS_V4
                            S: RESP-CODES
                            S: LOGIN-DELAY 900
                            S: PIPELINING
                            S: EXPIRE 60
                            S: UIDL
                            S: IMPLEMENTATION Shlemazle-Plotz-v302
                            S: .
                    */

                    byte[] buffer = Encoding.UTF8.GetBytes("CAPA\r\n");

                    // Log
                    m_pPop3Client.LogAddWrite(buffer.Length,"CAPA");

                    // Start command sending.
                    m_pPop3Client.TcpStream.BeginWrite(buffer,0,buffer.Length,this.CapaCommandSendingCompleted,null);
                }
                catch(Exception x){
                    m_pException = x;
                    m_pPop3Client.LogAddException("Exception: " + x.Message,x);
                    SetState(AsyncOP_State.Completed);
                }

                // Set flag rise CompletedAsync event flag. The event is raised when async op completes.
                // If already completed sync, that flag has no effect.
                lock(m_pLock){
                    m_RiseCompleted = true;

                    return m_State == AsyncOP_State.Active;
                }
            }
        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="pop3">Owner POP3 client.</param>
        internal POP3_ClientMessageCollection(POP3_Client pop3)
        {
            m_pPop3Client = pop3;

            m_pMessages = new List <POP3_ClientMessage>();
        }
 /// <summary>
 /// Default constructor.
 /// </summary>
 /// <param name="pop3">Owner POP3 client.</param>
 /// <param name="seqNumber">Message 1 based sequence number.</param>
 /// <param name="size">Message size in bytes.</param>
 internal POP3_ClientMessage(POP3_Client pop3,int seqNumber,int size)
 {
     m_Pop3Client     = pop3;
     m_SequenceNumber = seqNumber;
     m_Size           = size;
 }
Exemple #10
0
        /// <summary>
        /// Reads the mail.
        /// </summary>
        public MailboxReaderResult ReadMail()
        {
            var result = new MailboxReaderResult();
            IList<Project> projects = new List<Project>();

            LogInfo("MailboxReader: Begin read mail.");

            try
            {
                using (var pop3Client = new POP3_Client())
                {
                    // configure the logger
                    pop3Client.Logger = new Logger();
                    pop3Client.Logger.WriteLog += LogPop3Client;

                    // connect to the server
                    pop3Client.Connect(Config.Server, Config.Port, Config.UseSsl);

                    // authenticate
                    pop3Client.Login(Config.Username, Config.Password);

                    // process the messages on the server
                    foreach (POP3_ClientMessage message in pop3Client.Messages)
                    {
                        var mailHeader = Mail_Message.ParseFromByte(message.HeaderToByte());

                        if (mailHeader != null)
                        {
                            var recipients = mailHeader.To.Mailboxes.Select(mailbox => mailbox.Address).ToList();

                            if (mailHeader.Cc != null)
                            {
                                recipients.AddRange(mailHeader.Cc.Mailboxes.Select(mailbox => mailbox.Address));
                            }

                            if (mailHeader.Bcc != null)
                            {
                                recipients.AddRange(mailHeader.Bcc.Mailboxes.Select(mailbox => mailbox.Address));
                            }

                            // first check if this is a comment (comments are implemented using plus addressing)
                            // a comment will have a replyto address like [email]+iid-[number]@domain.com
                            bool isProcessed = false;
                            if (HostSettingManager.Get<bool>(HostSettingNames.Pop3AllowReplyToEmail, false))
                            {
                                isProcessed = ProcessNewComment(recipients, message, mailHeader, result);
                            }
                            if (!isProcessed)
                            {
                                isProcessed = ProcessNewIssue(recipients, message, mailHeader, projects, result);
                            }

                            if (isProcessed)
                            {
                                LogInfo(string.Format(
                                    "MailboxReader: Message #{0} processing finished, found [{1}] attachments, total saved [{2}].",
                                    message.SequenceNumber,
                                    0, 0));

                                try
                                {
                                    // delete the message?.
                                    if (Config.DeleteAllMessages)
                                    {
                                        message.MarkForDeletion();
                                    }
                                }
                                catch (Exception)
                                { }
                            }
                            else
                            {
                                LogWarning(string.Format("pop3Client: Message #{0} header could not be parsed.", message.SequenceNumber));
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogException(ex);
                result.LastException = ex;
                result.Status = ResultStatuses.FailedWithException;
            }

            LogInfo("MailboxReader: End read mail.");

            return result;
        }
Exemple #11
0
            /// <summary>
            /// Starts operation processing.
            /// </summary>
            /// <param name="owner">Owner POP3 client message.</param>
            /// <returns>Returns true if asynchronous operation in progress or false if operation completed synchronously.</returns>
            /// <exception cref="ArgumentNullException">Is raised when <b>owner</b> is null reference.</exception>
            internal bool Start(POP3_ClientMessage owner)
            {
                if(owner == null){
                    throw new ArgumentNullException("owner");
                }

                m_pOwner      = owner;
                m_pPop3Client = owner.m_Pop3Client;

                SetState(AsyncOP_State.Active);

                try{
                    /* RFC 1939 5. RETR
                         Arguments:
                             a message-number (required) which may NOT refer to a
                             message marked as deleted

                         Restrictions:
                             may only be given in the TRANSACTION state

                         Discussion:
                             If the POP3 server issues a positive response, then the
                             response given is multi-line.  After the initial +OK, the
                             POP3 server sends the message corresponding to the given
                             message-number, being careful to byte-stuff the termination
                             character (as with all multi-line responses).

                         Possible Responses:
                             +OK message follows
                             -ERR no such message

                         Examples:
                             C: RETR 1
                             S: +OK 120 octets
                             S: <the POP3 server sends the entire message here>
                             S: .
			        */

                    byte[] buffer = Encoding.UTF8.GetBytes("RETR " + owner.SequenceNumber.ToString() + "\r\n");

                    // Log
                    m_pPop3Client.LogAddWrite(buffer.Length,"RETR " + owner.SequenceNumber.ToString());

                    // Start command sending.
                    m_pPop3Client.TcpStream.BeginWrite(buffer,0,buffer.Length,this.RetrCommandSendingCompleted,null);
                }
                catch(Exception x){
                    m_pException = x;
                    m_pPop3Client.LogAddException("Exception: " + x.Message,x);
                    SetState(AsyncOP_State.Completed);
                }

                // Set flag rise CompletedAsync event flag. The event is raised when async op completes.
                // If already completed sync, that flag has no effect.
                lock(m_pLock){
                    m_RiseCompleted = true;

                    return m_State == AsyncOP_State.Active;
                }
            }
Exemple #12
0
        /// <summary>
		/// Starts messages fetching.
		/// </summary>
		public void StartFetching()
		{
			if(m_Fetching){
				return;
			}

			m_Fetching = true;

            try{
			    DataView dvUsers = m_pApi.GetUsers("ALL");

			    using(DataView dvServers = m_pApi.GetUserRemoteServers("")){
				    foreach(DataRowView drV in dvServers){
					    try{
                            if(!ConvertEx.ToBoolean(drV["Enabled"])){
                                continue;
                            }

						    // Find user name from user ID
						    string userName = "";
						    dvUsers.RowFilter = "UserID='" + drV["UserID"] + "'";
						    if(dvUsers.Count > 0){
							    userName = dvUsers[0]["UserName"].ToString();
						    }
						    else{
							    continue;
						    }

						    string server = drV.Row["RemoteServer"].ToString();
						    int    port   = Convert.ToInt32(drV.Row["RemotePort"]);
						    string user   = drV.Row["RemoteUserName"].ToString();
						    string passw  = drV.Row["RemotePassword"].ToString();
                            bool   useSSL = ConvertEx.ToBoolean(drV["UseSSL"]);
    					
						    // Connect and login to pop3 server
						    using(POP3_Client clnt = new POP3_Client()){
                                clnt.Logger = new LumiSoft.Net.Log.Logger();
                                clnt.Logger.WriteLog += new EventHandler<WriteLogEventArgs>(Pop3_WriteLog);
							    clnt.Connect(server,port,useSSL);
							    clnt.Authenticate(user,passw,false);

                                foreach(POP3_ClientMessage message in clnt.Messages){
                                    // Store message
								    m_pServer.ProcessUserMsg("","",userName,"Inbox",new MemoryStream(message.MessageToByte()),null);

                                    message.MarkForDeletion();
                                }
						    }
					    }
					    catch{
					    }
				    }
			    }

			    m_LastFetch = DateTime.Now;
            }
            catch(Exception x){
                Error.DumpError(m_pServer.Name,x);
            }
			m_Fetching = false;
		}
Exemple #13
0
            /// <summary>
            /// Starts operation processing.
            /// </summary>
            /// <param name="owner">Owner POP3 client.</param>
            /// <returns>Returns true if asynchronous operation in progress or false if operation completed synchronously.</returns>
            /// <exception cref="ArgumentNullException">Is raised when <b>owner</b> is null reference.</exception>
            internal bool Start(POP3_Client owner)
            {
                if(owner == null){
                    throw new ArgumentNullException("owner");
                }

                m_pPop3Client = owner;

                SetState(AsyncOP_State.Active);

                try{
                    /* RFC 2595 4. POP3 STARTTLS extension.
                        Arguments: none

                        Restrictions:
                            Only permitted in AUTHORIZATION state.
                     
                        Possible Responses:
                             +OK -ERR

                         Examples:
                             C: STLS
                             S: +OK Begin TLS negotiation
                             <TLS negotiation, further commands are under TLS layer>
                               ...
                             C: STLS
                             S: -ERR Command not permitted when TLS active
                    */

                    byte[] buffer = Encoding.UTF8.GetBytes("STLS\r\n");

                    // Log
                    m_pPop3Client.LogAddWrite(buffer.Length,"STLS");

                    // Start command sending.
                    m_pPop3Client.TcpStream.BeginWrite(buffer,0,buffer.Length,this.StlsCommandSendingCompleted,null);
                }
                catch(Exception x){
                    m_pException = x;
                    m_pPop3Client.LogAddException("Exception: " + x.Message,x);
                    SetState(AsyncOP_State.Completed);
                }

                // Set flag rise CompletedAsync event flag. The event is raised when async op completes.
                // If already completed sync, that flag has no effect.
                lock(m_pLock){
                    m_RiseCompleted = true;

                    return m_State == AsyncOP_State.Active;
                }
            }
Exemple #14
0
            /// <summary>
            /// Starts operation processing.
            /// </summary>
            /// <param name="owner">Owner POP3 client.</param>
            /// <returns>Returns true if asynchronous operation in progress or false if operation completed synchronously.</returns>
            /// <exception cref="ArgumentNullException">Is raised when <b>owner</b> is null reference.</exception>
            internal bool Start(POP3_Client owner)
            {
                if(owner == null){
                    throw new ArgumentNullException("owner");
                }

                m_pPop3Client = owner;

                SetState(AsyncOP_State.Active);

                try{
                    /* RFC 1935.7. UIDL
                      Arguments:
                          a message-number (optional), which, if present, may NOT
                          refer to a message marked as deleted

                      Restrictions:
                          may only be given in the TRANSACTION state.

                      Discussion:
                          If an argument was given and the POP3 server issues a positive
                          response with a line containing information for that message.
                          This line is called a "unique-id listing" for that message.

                          If no argument was given and the POP3 server issues a positive
                          response, then the response given is multi-line.  After the
                          initial +OK, for each message in the maildrop, the POP3 server
                          responds with a line containing information for that message.
                          This line is called a "unique-id listing" for that message.

                          In order to simplify parsing, all POP3 servers are required to
                          use a certain format for unique-id listings.  A unique-id
                          listing consists of the message-number of the message,
                          followed by a single space and the unique-id of the message.
                          No information follows the unique-id in the unique-id listing.

                          The unique-id of a message is an arbitrary server-determined
                          string, consisting of one to 70 characters in the range 0x21
                          to 0x7E, which uniquely identifies a message within a
                          maildrop and which persists across sessions.  This
                          persistence is required even if a session ends without
                          entering the UPDATE state.  The server should never reuse an
                          unique-id in a given maildrop, for as long as the entity
                          using the unique-id exists.

                          Note that messages marked as deleted are not listed.

                          While it is generally preferable for server implementations
                          to store arbitrarily assigned unique-ids in the maildrop,
                          this specification is intended to permit unique-ids to be
                          calculated as a hash of the message.  Clients should be able
                          to handle a situation where two identical copies of a
                          message in a maildrop have the same unique-id.

                      Possible Responses:
                          +OK unique-id listing follows
                          -ERR no such message

                      Examples:
                          C: UIDL
                          S: +OK
                          S: 1 whqtswO00WBw418f9t5JxYwZ
                          S: 2 QhdPYR:00WBw1Ph7x7
                          S: .
                             ...
                          C: UIDL 2
                          S: +OK 2 QhdPYR:00WBw1Ph7x7
                             ...
                          C: UIDL 3
                          S: -ERR no such message, only 2 messages in maildrop
                    */

                    byte[] buffer = Encoding.UTF8.GetBytes("UIDL\r\n");

                    // Log
                    m_pPop3Client.LogAddWrite(buffer.Length,"UIDL");

                    // Start command sending.
                    m_pPop3Client.TcpStream.BeginWrite(buffer,0,buffer.Length,this.UidlCommandSendingCompleted,null);
                }
                catch(Exception x){
                    m_pException = x;
                    m_pPop3Client.LogAddException("Exception: " + x.Message,x);
                    SetState(AsyncOP_State.Completed);
                }

                // Set flag rise CompletedAsync event flag. The event is raised when async op completes.
                // If already completed sync, that flag has no effect.
                lock(m_pLock){
                    m_RiseCompleted = true;

                    return m_State == AsyncOP_State.Active;
                }
            }
Exemple #15
0
            /// <summary>
            /// Cleans up any resources being used.
            /// </summary>
            public void Dispose()
            {
                if(m_State == AsyncOP_State.Disposed){
                    return;
                }
                SetState(AsyncOP_State.Disposed);
                
                m_pException     = null;
                m_pPop3Client    = null;
                m_pResponseLines = null;

                this.CompletedAsync = null;
            }
Exemple #16
0
            /// <summary>
            /// Starts operation processing.
            /// </summary>
            /// <param name="owner">Owner POP3 client.</param>
            /// <returns>Returns true if asynchronous operation in progress or false if operation completed synchronously.</returns>
            /// <exception cref="ArgumentNullException">Is raised when <b>owner</b> is null reference.</exception>
            internal bool Start(POP3_Client owner)
            {
                if(owner == null){
                    throw new ArgumentNullException("owner");
                }

                m_pPop3Client = owner;

                SetState(AsyncOP_State.Active);

                try{
                    /* RFC 1935.5. LIST
                         Arguments:
                             a message-number (optional), which, if present, may NOT
                             refer to a message marked as deleted 

                         Restrictions:
                             may only be given in the TRANSACTION state

                         Discussion:
                             If an argument was given and the POP3 server issues a
                             positive response with a line containing information for
                             that message.  This line is called a "scan listing" for
                             that message.

                             If no argument was given and the POP3 server issues a
                             positive response, then the response given is multi-line.
                             After the initial +OK, for each message in the maildrop,
                             the POP3 server responds with a line containing
                             information for that message.  This line is also called a
                             "scan listing" for that message.  If there are no
                             messages in the maildrop, then the POP3 server responds
                             with no scan listings--it issues a positive response
                             followed by a line containing a termination octet and a
                             CRLF pair.

                             In order to simplify parsing, all POP3 servers are
                             required to use a certain format for scan listings.  A
                             scan listing consists of the message-number of the
                             message, followed by a single space and the exact size of
                             the message in octets.  Methods for calculating the exact
                             size of the message are described in the "Message Format"
                             section below.  This memo makes no requirement on what
                             follows the message size in the scan listing.  Minimal
                             implementations should just end that line of the response
                             with a CRLF pair.  More advanced implementations may
                             include other information, as parsed from the message.

                                NOTE: This memo STRONGLY discourages implementations
                                from supplying additional information in the scan
                                listing.  Other, optional, facilities are discussed
                                later on which permit the client to parse the messages
                                in the maildrop.

                             Note that messages marked as deleted are not listed.

                         Possible Responses:
                             +OK scan listing follows
                             -ERR no such message

                         Examples:
                             C: LIST
                             S: +OK 2 messages (320 octets)
                             S: 1 120
                             S: 2 200
                             S: .
                               ...
                             C: LIST 2
                             S: +OK 2 200
                               ...
                             C: LIST 3
                             S: -ERR no such message, only 2 messages in maildrop
                    */

                    byte[] buffer = Encoding.UTF8.GetBytes("LIST\r\n");

                    // Log
                    m_pPop3Client.LogAddWrite(buffer.Length,"LIST");

                    // Start command sending.
                    m_pPop3Client.TcpStream.BeginWrite(buffer,0,buffer.Length,this.ListCommandSendingCompleted,null);
                }
                catch(Exception x){
                    m_pException = x;
                    m_pPop3Client.LogAddException("Exception: " + x.Message,x);
                    SetState(AsyncOP_State.Completed);
                }

                // Set flag rise CompletedAsync event flag. The event is raised when async op completes.
                // If already completed sync, that flag has no effect.
                lock(m_pLock){
                    m_RiseCompleted = true;

                    return m_State == AsyncOP_State.Active;
                }
            }
Exemple #17
0
            /// <summary>
            /// Starts operation processing.
            /// </summary>
            /// <param name="owner">Owner POP3 client.</param>
            /// <returns>Returns true if asynchronous operation in progress or false if operation completed synchronously.</returns>
            /// <exception cref="ArgumentNullException">Is raised when <b>owner</b> is null reference.</exception>
            internal bool Start(POP3_Client owner)
            {
                if(owner == null){
                    throw new ArgumentNullException("owner");
                }

                m_pPop3Client = owner;

                SetState(AsyncOP_State.Active);

                try{
                    // Start executing LIST command.
                    POP3_Client.ListAsyncOP listOP = new ListAsyncOP();
                    listOP.CompletedAsync += delegate(object sender,EventArgs<ListAsyncOP> e){
                        ListCompleted(listOP);
                    };
                    if(!m_pPop3Client.ListAsync(listOP)){
                        ListCompleted(listOP);
                    }
                }
                catch(Exception x){
                    m_pException = x;
                    m_pPop3Client.LogAddException("Exception: " + x.Message,x);
                    SetState(AsyncOP_State.Completed);
                }

                // Set flag rise CompletedAsync event flag. The event is raised when async op completes.
                // If already completed sync, that flag has no effect.
                lock(m_pLock){
                    m_RiseCompleted = true;

                    return m_State == AsyncOP_State.Active;
                }
            }
Exemple #18
0
            /// <summary>
            /// Starts operation processing.
            /// </summary>
            /// <param name="owner">Owner POP3 client.</param>
            /// <returns>Returns true if asynchronous operation in progress or false if operation completed synchronously.</returns>
            /// <exception cref="ArgumentNullException">Is raised when <b>owner</b> is null reference.</exception>
            internal bool Start(POP3_Client owner)
            {
                if(owner == null){
                    throw new ArgumentNullException("owner");
                }

                m_pPop3Client = owner;

                SetState(AsyncOP_State.Active);

                try{
                    /* RFC 1939 5. RSET.
                        Arguments: none

                        Restrictions:
                            may only be given in the TRANSACTION state

                        Discussion:
                            If any messages have been marked as deleted by the POP3
                            server, they are unmarked.  The POP3 server then replies
                            with a positive response.

                        Possible Responses:
                            +OK

                        Examples:
                            C: RSET
                            S: +OK maildrop has 2 messages (320 octets)
			        */

                    byte[] buffer = Encoding.UTF8.GetBytes("RSET\r\n");

                    // Log
                    m_pPop3Client.LogAddWrite(buffer.Length,"RSET");

                    // Start command sending.
                    m_pPop3Client.TcpStream.BeginWrite(buffer,0,buffer.Length,this.RsetCommandSendingCompleted,null);
                }
                catch(Exception x){
                    m_pException = x;
                    m_pPop3Client.LogAddException("Exception: " + x.Message,x);
                    SetState(AsyncOP_State.Completed);
                }

                // Set flag rise CompletedAsync event flag. The event is raised when async op completes.
                // If already completed sync, that flag has no effect.
                lock(m_pLock){
                    m_RiseCompleted = true;

                    return m_State == AsyncOP_State.Active;
                }
            }
Exemple #19
0
            /// <summary>
            /// Starts operation processing.
            /// </summary>
            /// <param name="owner">Owner POP3 client message.</param>
            /// <returns>Returns true if asynchronous operation in progress or false if operation completed synchronously.</returns>
            /// <exception cref="ArgumentNullException">Is raised when <b>owner</b> is null reference.</exception>
            internal bool Start(POP3_ClientMessage owner)
            {
                if(owner == null){
                    throw new ArgumentNullException("owner");
                }

                m_pOwner      = owner;
                m_pPop3Client = owner.m_Pop3Client;

                SetState(AsyncOP_State.Active);

                try{
                    /* RFC 1939 7. TOP
                         Arguments:
                             a message-number (required) which may NOT refer to to a
                             message marked as deleted, and a non-negative number
                             of lines (required)

                         Restrictions:
                             may only be given in the TRANSACTION state

                         Discussion:
                             If the POP3 server issues a positive response, then the
                             response given is multi-line.  After the initial +OK, the
                             POP3 server sends the headers of the message, the blank
                             line separating the headers from the body, and then the
                             number of lines of the indicated message's body, being
                             careful to byte-stuff the termination character (as with
                             all multi-line responses).

                             Note that if the number of lines requested by the POP3
                             client is greater than than the number of lines in the
                             body, then the POP3 server sends the entire message.

                         Possible Responses:
                             +OK top of message follows
                             -ERR no such message

                         Examples:
                             C: TOP 1 10
                             S: +OK
                             S: <the POP3 server sends the headers of the
                                message, a blank line, and the first 10 lines
                                of the body of the message>
                             S: .
                                ...
                             C: TOP 100 3
                             S: -ERR no such message
			        */

                    byte[] buffer = Encoding.UTF8.GetBytes("TOP " + owner.SequenceNumber.ToString()+ " " + m_LineCount.ToString() + "\r\n");

                    // Log
                    m_pPop3Client.LogAddWrite(buffer.Length,"TOP " + owner.SequenceNumber.ToString()+ " " + m_LineCount.ToString());

                    // Start command sending.
                    m_pPop3Client.TcpStream.BeginWrite(buffer,0,buffer.Length,this.TopCommandSendingCompleted,null);
                }
                catch(Exception x){
                    m_pException = x;
                    m_pPop3Client.LogAddException("Exception: " + x.Message,x);
                    SetState(AsyncOP_State.Completed);
                }

                // Set flag rise CompletedAsync event flag. The event is raised when async op completes.
                // If already completed sync, that flag has no effect.
                lock(m_pLock){
                    m_RiseCompleted = true;

                    return m_State == AsyncOP_State.Active;
                }
            }
Exemple #20
0
            /// <summary>
            /// Starts operation processing.
            /// </summary>
            /// <param name="owner">Owner POP3 client message.</param>
            /// <returns>Returns true if asynchronous operation in progress or false if operation completed synchronously.</returns>
            /// <exception cref="ArgumentNullException">Is raised when <b>owner</b> is null reference.</exception>
            internal bool Start(POP3_ClientMessage owner)
            {
                if(owner == null){
                    throw new ArgumentNullException("owner");
                }

                m_pOwner      = owner;
                m_pPop3Client = owner.m_Pop3Client;

                SetState(AsyncOP_State.Active);

                try{
                    /* RFC 1939 5. DELE
                         Arguments:
                             a message-number (required) which may NOT refer to a
                             message marked as deleted

                         Restrictions:
                             may only be given in the TRANSACTION state

                         Discussion:
                             The POP3 server marks the message as deleted.  Any future
                             reference to the message-number associated with the message
                             in a POP3 command generates an error.  The POP3 server does
                             not actually delete the message until the POP3 session
                             enters the UPDATE state.

                         Possible Responses:
                             +OK message deleted
                             -ERR no such message

                         Examples:
                             C: DELE 1
                             S: +OK message 1 deleted
                                ...
                             C: DELE 2
                             S: -ERR message 2 already deleted
			        */

                    byte[] buffer = Encoding.UTF8.GetBytes("DELE " + owner.SequenceNumber.ToString() + "\r\n");

                    // Log
                    m_pPop3Client.LogAddWrite(buffer.Length,"DELE " + owner.SequenceNumber.ToString());

                    // Start command sending.
                    m_pPop3Client.TcpStream.BeginWrite(buffer,0,buffer.Length,this.DeleCommandSendingCompleted,null);
                }
                catch(Exception x){
                    m_pException = x;
                    m_pPop3Client.LogAddException("Exception: " + x.Message,x);
                    SetState(AsyncOP_State.Completed);
                }

                // Set flag rise CompletedAsync event flag. The event is raised when async op completes.
                // If already completed sync, that flag has no effect.
                lock(m_pLock){
                    m_RiseCompleted = true;

                    return m_State == AsyncOP_State.Active;
                }
            }
Exemple #21
0
        public override void init()
        {
            using (POP3_Client popClient = new POP3_Client())
            {
                popClient.Connect(m_host, m_port);
                popClient.Login(m_user, m_pwd);

                foreach (POP3_ClientMessage message in popClient.Messages)
                {
                    LumiSoft.Net.Mail.Mail_Message mime_header = LumiSoft.Net.Mail.Mail_Message.ParseFromByte(message.HeaderToByte());
                    if (mime_header != null && m_Filter(mime_header.Subject, null))
                    {
                        m_htmlBody = mime_header.BodyHtmlText;
                        return;
                    }

                }
            }
        }
Exemple #22
0
            /// <summary>
            /// Cleans up any resources being used.
            /// </summary>
            public void Dispose()
            {
                if(m_State == AsyncOP_State.Disposed){
                    return;
                }
                SetState(AsyncOP_State.Disposed);
                
                m_pException  = null;
                m_pOwner      = null;
                m_pPop3Client = null;
                m_pStream     = null;

                this.CompletedAsync = null;
            }
        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="pop3">Owner POP3 client.</param>
        internal POP3_ClientMessageCollection(POP3_Client pop3)
        {
            m_pPop3Client = pop3;

            m_pMessages = new List<POP3_ClientMessage>();
        }
        private void Server_AuthenticateUser(object sender,LumiSoft.Net.POP3.Server.AuthUser_EventArgs e)
        {
            try
            {
                e.Validated = m_pAPI.AuthUser(e.UserName,e.PasswData,e.AuthData,e.AuthType);
                if(e.Validated == false){
                    return;
                }

                //----- Remote pop3 servers ---------------------------------------//
                DataSet ds = m_pAPI.GetUserRemotePop3Servers(e.UserName);

                // Connect to external pop3 servers
                ArrayList extrnPop3Servers = new ArrayList();
                foreach(DataRow dr in ds.Tables["RemotePop3Servers"].Rows){
                    try
                    {
                        string server = dr["Server"].ToString();
                        int    port   = Convert.ToInt32(dr["Port"]);
                        string user   = dr["UserName"].ToString();
                        string passw  = dr["Password"].ToString();

                        POP3_Client clnt = new POP3_Client();
                        clnt.Connect(server,port);
                        clnt.Authenticate(user,passw,false);

                        extrnPop3Servers.Add(clnt);
                    }
                    catch(Exception x){
                    }
                }

                if(extrnPop3Servers.Count > 0){
                    e.Session.Tag = extrnPop3Servers;
                }
                //---------------------------------------------------------------------//
            }
            catch(Exception x)
            {
                e.Validated = false;
                Error.DumpError(x,new System.Diagnostics.StackTrace());
            }
        }
    public void display()
    {
        //需要首先设置这些信息
        HyoaClass.Hyoa_mail_config Hyoa_mail_config = new HyoaClass.Hyoa_mail_config();
        DataTable dtconfig = Hyoa_mail_config.Getmailconfigbyuserid(this.Session["hyuid"].ToString());
        if (dtconfig.Rows.Count > 0)
        {
            string pop3Server = dtconfig.Rows[0]["hy_pop3url"].ToString();// "pop.163.com";    //邮箱服务器 如:"pop.sina.com.cn";或 "pop.qq.com" 好像sina的比较快
            int pop3Port = System.Int32.Parse(dtconfig.Rows[0]["hy_pop3port"].ToString()); //110;          //端口号码   用"110"好使。最好看一下你的邮箱服务器用的是什么端口号
            bool pop3UseSsl = false;
            string lsmailid = dtconfig.Rows[0]["hy_mailid"].ToString();
            string username = lsmailid.Substring(0, lsmailid.IndexOf("@"));//"ztmfang2008";        //你的邮箱用户名
            string password = Decrypt(dtconfig.Rows[0]["hy_mailpwd"].ToString()); //"20120328";      //你的邮箱密码
            List<string> gotEmailIds = new List<string>();
            List<Mime> result = new List<Mime>();
            using (POP3_Client pop3 = new POP3_Client())
            {
                //与Pop3服务器建立连接
                pop3.Connect(pop3Server, pop3Port, pop3UseSsl);
                //验证身份
                pop3.Authenticate(username, password, false);
                //获取邮件信息列表
                POP3_ClientMessageCollection infos = pop3.Messages;
                foreach (POP3_ClientMessage info in infos)
                {
                    //每封Email会有一个在Pop3服务器范围内唯一的Id,检查这个Id是否存在就可以知道以前有没有接收过这封邮件
                    if (gotEmailIds.Contains(info.UID))
                        continue;
                    //获取这封邮件的内容
                    byte[] bytes = info.MessageToByte();
                    //记录这封邮件的Id
                    gotEmailIds.Add(info.UID);
                    //this.Response.Write("<script>alert('" + info.UID + "');</script>");
                    //解析从Pop3服务器发送过来的邮件信息
                    Mime m = Mime.Parse(bytes);

                    HyoaClass.Hyoa_global Hyoa_global = new HyoaClass.Hyoa_global();
                    HyoaClass.Hyoa_mail Hyoa_mail = new HyoaClass.Hyoa_mail();
                    HyoaClass.Hyoa_fileatt Hyoa_fileatt = new HyoaClass.Hyoa_fileatt();
                    //this.Response.Write("<script>alert('aaa');</script>");
                    string lsid = Hyoa_global.GetRandom();
                    string lsdocid = info.UID.ToString();

                    DataTable dtmail = Hyoa_mail.Getmailbydocid(lsdocid);
                    if (dtmail.Rows.Count > 0)
                    { }
                    else
                    {
                        Hyoa_mail.ID = lsid;
                        Hyoa_mail.DOCID = lsdocid;
                        Hyoa_mail.hy_type = "收件";
                        Hyoa_mail.hy_foldername = "收件箱";
                        Hyoa_mail.hy_fsrid = m.MainEntity.From.ToAddressListString().ToString();
                        Hyoa_mail.hy_fsrname = m.MainEntity.From.ToAddressListString().ToString();
                        Hyoa_mail.hy_jsrid = this.Session["hyuid"].ToString();
                        Hyoa_mail.hy_wbjsrid = m.MainEntity.To.ToAddressListString().ToString();
                        Hyoa_mail.hy_jsrname = this.Session["hyuname"].ToString();
                        Hyoa_mail.hy_title = m.MainEntity.Subject.ToString();
                        Hyoa_mail.hy_body = m.BodyHtml.ToString();
                        Hyoa_mail.hy_datetime = m.MainEntity.Date.ToString();
                        Hyoa_mail.hy_ifsavetofjx = "";
                        Hyoa_mail.hy_yxj = "";
                        Hyoa_mail.hy_yjbg = "";
                        Hyoa_mail.hy_zycd = "";
                        Hyoa_mail.hy_hz = "";

                        Hyoa_mail.Insert();
                        //this.Response.Write("<script>alert('bbb');</script>");

                        //获取附件
                        foreach (MimeEntity entry in m.Attachments)
                        {
                            string lsfileattid = Hyoa_global.GetRandom();
                            string fileName = entry.ContentDisposition_FileName; //获取文件名称
                            string path = Server.MapPath("~\\fileatt\\" + lsfileattid);
                            Directory.CreateDirectory(path);
                            path += "\\" + fileName;
                            if (File.Exists(path))
                            {
                                Random random = new Random();
                                int newfile = random.Next(1, 100000);
                                path = Server.MapPath("~\\fileatt\\" + lsfileattid + "\\" + newfile.ToString());
                                Directory.CreateDirectory(path);
                                path += "\\" + fileName;
                            }
                            byte[] data = entry.Data;
                            FileStream pFileStream = null;
                            pFileStream = new FileStream(path, FileMode.Create);
                            pFileStream.Write(data, 0, data.Length);
                            pFileStream.Close();

                            //向附件表插入记录
                            Hyoa_fileatt.ID = lsfileattid;
                            Hyoa_fileatt.hy_fatherid = lsdocid;
                            Hyoa_fileatt.hy_filename = fileName;
                            Hyoa_fileatt.hy_filepath = path.Substring(path.IndexOf("fileatt\\"));
                            Hyoa_fileatt.hy_filesize = data.Length.ToString();
                            Hyoa_fileatt.hy_userid = this.Session["hyuid"].ToString();
                            Hyoa_fileatt.hy_djsj = m.MainEntity.Date.ToString();
                            Hyoa_fileatt.hy_fatherfield = "";
                            Hyoa_fileatt.Insert();

                            //this.Response.Write("<script>alert('ccc');</script>");
                        }
                    }
                    //Response.Write("<br>From:" + m.MainEntity.From.ToAddressListString());
                    //Response.Write("<br>To:" + m.MainEntity.To.ToAddressListString());
                    //Response.Write("<br>Time:" + m.MainEntity.Date);            //发送时间
                    //Response.Write("<br>Subject:" + m.MainEntity.Subject);      //主题
                    //Response.Write("<br>Plain Body:" + m.BodyText);             //内容
                    //Response.Write("<br>Html Body:" + m.BodyHtml);              //HTML格式内容
                }
                this.Response.Write("<script>alert('邮件接收完成!');window.opener.location.reload();window.close();</script>");
            }
        }
        else
        {
            this.Response.Write("<script>alert('请先配置外网邮件信息!');</script>");
        }
    }
        /// <summary>
        /// Disposes message.
        /// </summary>
        internal void Dispose()
        {
            if(m_IsDisposed){
                return;
            }

            m_IsDisposed = true;
            m_Pop3Client = null;
        }
Exemple #27
0
            /// <summary>
            /// Starts operation processing.
            /// </summary>
            /// <param name="owner">Owner POP3 client.</param>
            /// <returns>Returns true if asynchronous operation in progress or false if operation completed synchronously.</returns>
            /// <exception cref="ArgumentNullException">Is raised when <b>owner</b> is null reference.</exception>
            internal bool Start(POP3_Client owner)
            {
                if(owner == null){
                    throw new ArgumentNullException("owner");
                }

                m_pPop3Client = owner;

                SetState(AsyncOP_State.Active);

                try{
                    byte[] buffer = Encoding.UTF8.GetBytes("USER " + m_User + "\r\n");

                    // Log
                    m_pPop3Client.LogAddWrite(buffer.Length,"USER " + m_User);

                    // Start command sending.
                    m_pPop3Client.TcpStream.BeginWrite(buffer,0,buffer.Length,this.UserCommandSendingCompleted,null);
                }
                catch(Exception x){
                    m_pException = x;
                    m_pPop3Client.LogAddException("Exception: " + x.Message,x);
                    SetState(AsyncOP_State.Completed);
                }

                // Set flag rise CompletedAsync event flag. The event is raised when async op completes.
                // If already completed sync, that flag has no effect.
                lock(m_pLock){
                    m_RiseCompleted = true;

                    return m_State == AsyncOP_State.Active;
                }
            }
 /// <summary>
 /// Default constructor.
 /// </summary>
 /// <param name="pop3">Owner POP3 client.</param>
 /// <param name="seqNumber">Message 1 based sequence number.</param>
 /// <param name="size">Message size in bytes.</param>
 internal POP3_ClientMessage(POP3_Client pop3, int seqNumber, int size)
 {
     m_Pop3Client     = pop3;
     m_SequenceNumber = seqNumber;
     m_Size           = size;
 }
Exemple #29
0
        static void pop3()
        { 
            List<string> gotemailids = new List<string>();
            using (LumiSoft.Net.POP3.Client.POP3_Client pop3 = new POP3_Client())
            {
                try
                {
                    //与pop3服务器建立连接
                    pop3.Connect("pop.qq.com", 110, false);
                    //验证身份
                    pop3.Login("*****@*****.**", "myhaiyan");

                    //获取邮件信息列表
                    POP3_ClientMessageCollection infos = pop3.Messages;
                    foreach (POP3_ClientMessage info in infos)
                    {
                        //每封email会有一个在pop3服务器范围内唯一的id,检查这个id是否存在就可以知道以前有没有接收过这封邮件
                        if (gotemailids.Contains(info.UID))
                            continue;
                        //获取这封邮件的内容
                        byte[] bytes = info.MessageToByte();
                        //记录这封邮件的id
                        gotemailids.Add(info.UID);

                        //解析从pop3服务器发送过来的邮件信息
                        Mime m = Mime.Parse(bytes);
                        if (m != null)
                        {
                            string mailfrom = "";
                            string mailfromname = "";
                            if (m.MainEntity.From != null)
                            {
                                for (int i = 0; i < m.MainEntity.From.Mailboxes.Length; i++)
                                {
                                    if (i == 0)
                                    {
                                        mailfrom = (m.MainEntity.From).Mailboxes[i].EmailAddress;
                                    }
                                    else
                                    {
                                        mailfrom += string.Format(",{0}", (m.MainEntity.From).Mailboxes[i].EmailAddress);
                                    }
                                    mailfromname = (m.MainEntity.From).Mailboxes[0].DisplayName != ""
                                                       ? (m.MainEntity.From).Mailboxes[0].DisplayName
                                                       : (m.MainEntity.From).Mailboxes[0].LocalPart;
                                }
                            }
                            string mailto = "";
                            string mailtotocollection = "";
                            if (m.MainEntity.To != null)
                            {
                                mailtotocollection = m.MainEntity.To.ToAddressListString();

                                for (int i = 0; i < m.MainEntity.To.Mailboxes.Length; i++)
                                {
                                    if (i == 0)
                                    {
                                        mailto = (m.MainEntity.To).Mailboxes[i].EmailAddress;
                                    }
                                    else
                                    {
                                        mailto += string.Format(",{0}", (m.MainEntity.To).Mailboxes[i].EmailAddress);
                                    }

                                }
                            }

                        }
                        //获取附件
                        foreach (MimeEntity entry in m.Attachments)
                        {
                            string filename = entry.ContentDisposition_FileName; //获取文件名称
                            string path = AppDomain.CurrentDomain.BaseDirectory + @"attch\" + filename;
                            if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + @"attch"))
                            {
                                Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + @"attch");
                            }
                            if (File.Exists(path))
                            {
                                Random random = new Random();
                                int newfile = random.Next(1, 100000);
                                path = AppDomain.CurrentDomain.BaseDirectory + @"attch\" + newfile.ToString();
                                Directory.CreateDirectory(path);
                                path += @"\" + filename;
                            }
                            byte[] data = entry.Data;
                            FileStream pfilestream = null;
                            pfilestream = new FileStream(path, FileMode.Create);
                            pfilestream.Write(data, 0, data.Length);
                            pfilestream.Close();
                        }
                    }

                }
                catch (Exception ex)
                {

                }
            }
        }
Exemple #30
0
 public ReceiverMail(BaseMailAccount receiver)
 {
     _pop3Client = new POP3_Client();
     _receiveAccount = receiver;//需要提前设置好接收账号用户密码及接收服务器,接收端口,是否ssl
     _invalidMails = new ManageMail();
 }
Exemple #31
0
            /// <summary>
            /// Starts operation processing.
            /// </summary>
            /// <param name="owner">Owner POP3 client.</param>
            /// <returns>Returns true if asynchronous operation in progress or false if operation completed synchronously.</returns>
            /// <exception cref="ArgumentNullException">Is raised when <b>owner</b> is null reference.</exception>
            internal bool Start(POP3_Client owner)
            {
                if(owner == null){
                    throw new ArgumentNullException("owner");
                }

                m_pPop3Client = owner;

                SetState(AsyncOP_State.Active);

                try{
                    /* RFC 1939 5 NOOP.
                        Arguments: none

                        Restrictions:
                            may only be given in the TRANSACTION state

                        Discussion:
                            The POP3 server does nothing, it merely replies with a
                            positive response.

                        Possible Responses:
                            +OK

                        Examples:
                            C: NOOP
                            S: +OK
                    */

                    byte[] buffer = Encoding.UTF8.GetBytes("NOOP\r\n");

                    // Log
                    m_pPop3Client.LogAddWrite(buffer.Length,"NOOP");

                    // Start command sending.
                    m_pPop3Client.TcpStream.BeginWrite(buffer,0,buffer.Length,this.NoopCommandSendingCompleted,null);
                }
                catch(Exception x){
                    m_pException = x;
                    m_pPop3Client.LogAddException("Exception: " + x.Message,x);
                    SetState(AsyncOP_State.Completed);
                }

                // Set flag rise CompletedAsync event flag. The event is raised when async op completes.
                // If already completed sync, that flag has no effect.
                lock(m_pLock){
                    m_RiseCompleted = true;

                    return m_State == AsyncOP_State.Active;
                }
            }
        /// <summary>
        /// Starts messages fetching.
        /// </summary>
        public void StartFetching()
        {
            if(m_Fetching){
                return;
            }

            m_Fetching = true;

            try{
                DataView dvUsers = m_pApi.GetUsers("ALL");

                using(DataView dvServers = m_pApi.GetUserRemoteServers("")){
                    foreach(DataRowView drV in dvServers){
                        try{
                            if(!ConvertEx.ToBoolean(drV["Enabled"])){
                                continue;
                            }

                            // Find user name from user ID
                            string userName = "";
                            dvUsers.RowFilter = "UserID='" + drV["UserID"] + "'";
                            if(dvUsers.Count > 0){
                                userName = dvUsers[0]["UserName"].ToString();
                            }
                            else{
                                continue;
                            }

                            string server = drV.Row["RemoteServer"].ToString();
                            int    port   = Convert.ToInt32(drV.Row["RemotePort"]);
                            string user   = drV.Row["RemoteUserName"].ToString();
                            string passw  = drV.Row["RemotePassword"].ToString();
                            bool   useSSL = ConvertEx.ToBoolean(drV["UseSSL"]);

                            // Connect and login to pop3 server
                            using(POP3_Client clnt = new POP3_Client()){
                                clnt.SessionLog += new LogEventHandler(clnt_SessionLog);
                                clnt.LogCommands = LogCommands;
                                clnt.Connect(server,port,useSSL);
                                clnt.Authenticate(user,passw,false);

                                POP3_MessagesInfo messagesInfo = clnt.GetMessagesInfo();
                                foreach(POP3_MessageInfo messageInfo in messagesInfo.Messages){
                                    // Download message
                                    byte[] message = clnt.GetMessage(messageInfo.MessageNumber);

                                    // Store message
                                    m_pServer.ProcessUserMsg("","",userName,"Inbox",new MemoryStream(message),null);

                                    // Delete message
                                    clnt.DeleteMessage(messageInfo.MessageNumber);
                                }
                            }
                        }
                        catch{
                        }
                    }
                }

                m_LastFetch = DateTime.Now;
            }
            catch(Exception x){
                Error.DumpError(m_pServer.Name,x);
            }
            m_Fetching = false;
        }
        public override void Open()
        {
            if (!(channelState == ChannelState.Closed || channelState == ChannelState.Broken))
            {
                return;
            }

            channelState = ChannelState.Connecting;

            try
            {
                client = new POP3_Client();

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

                client.Connect(Hostname, Port, IsSecured);

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

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